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 if (Subtarget.is64Bit()) { 255 setOperationAction(ISD::ROTL, MVT::i32, Custom); 256 setOperationAction(ISD::ROTR, MVT::i32, Custom); 257 } 258 } else { 259 setOperationAction(ISD::ROTL, XLenVT, Expand); 260 setOperationAction(ISD::ROTR, XLenVT, Expand); 261 } 262 263 if (Subtarget.hasStdExtZbp()) { 264 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 265 // more combining. 266 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 267 setOperationAction(ISD::BSWAP, XLenVT, Custom); 268 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 269 // BSWAP i8 doesn't exist. 270 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 271 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 272 273 if (Subtarget.is64Bit()) { 274 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 275 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 276 } 277 } else { 278 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 279 // pattern match it directly in isel. 280 setOperationAction(ISD::BSWAP, XLenVT, 281 Subtarget.hasStdExtZbb() ? Legal : Expand); 282 } 283 284 if (Subtarget.hasStdExtZbb()) { 285 setOperationAction(ISD::SMIN, XLenVT, Legal); 286 setOperationAction(ISD::SMAX, XLenVT, Legal); 287 setOperationAction(ISD::UMIN, XLenVT, Legal); 288 setOperationAction(ISD::UMAX, XLenVT, Legal); 289 290 if (Subtarget.is64Bit()) { 291 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 292 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 293 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 294 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 295 } 296 } else { 297 setOperationAction(ISD::CTTZ, XLenVT, Expand); 298 setOperationAction(ISD::CTLZ, XLenVT, Expand); 299 setOperationAction(ISD::CTPOP, XLenVT, Expand); 300 } 301 302 if (Subtarget.hasStdExtZbt()) { 303 setOperationAction(ISD::FSHL, XLenVT, Custom); 304 setOperationAction(ISD::FSHR, XLenVT, Custom); 305 setOperationAction(ISD::SELECT, XLenVT, Legal); 306 307 if (Subtarget.is64Bit()) { 308 setOperationAction(ISD::FSHL, MVT::i32, Custom); 309 setOperationAction(ISD::FSHR, MVT::i32, Custom); 310 } 311 } else { 312 setOperationAction(ISD::SELECT, XLenVT, Custom); 313 } 314 315 static const ISD::CondCode FPCCToExpand[] = { 316 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 317 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 318 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 319 320 static const ISD::NodeType FPOpToExpand[] = { 321 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 322 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 323 324 if (Subtarget.hasStdExtZfh()) 325 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 326 327 if (Subtarget.hasStdExtZfh()) { 328 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 329 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 330 setOperationAction(ISD::LRINT, MVT::f16, Legal); 331 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 332 setOperationAction(ISD::LROUND, MVT::f16, Legal); 333 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 334 setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal); 335 setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal); 336 setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal); 337 setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal); 338 setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal); 339 setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal); 340 setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal); 341 setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal); 342 setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal); 343 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 344 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 345 setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal); 346 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal); 348 for (auto CC : FPCCToExpand) 349 setCondCodeAction(CC, MVT::f16, Expand); 350 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 351 setOperationAction(ISD::SELECT, MVT::f16, Custom); 352 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 353 354 setOperationAction(ISD::FREM, MVT::f16, Promote); 355 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 356 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 357 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 358 setOperationAction(ISD::FRINT, MVT::f16, Promote); 359 setOperationAction(ISD::FROUND, MVT::f16, Promote); 360 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 361 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 362 setOperationAction(ISD::FPOW, MVT::f16, Promote); 363 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 364 setOperationAction(ISD::FCOS, MVT::f16, Promote); 365 setOperationAction(ISD::FSIN, MVT::f16, Promote); 366 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 367 setOperationAction(ISD::FEXP, MVT::f16, Promote); 368 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 369 setOperationAction(ISD::FLOG, MVT::f16, Promote); 370 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 371 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 372 373 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 374 // complete support for all operations in LegalizeDAG. 375 376 // We need to custom promote this. 377 if (Subtarget.is64Bit()) 378 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 379 } 380 381 if (Subtarget.hasStdExtF()) { 382 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 383 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 384 setOperationAction(ISD::LRINT, MVT::f32, Legal); 385 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 386 setOperationAction(ISD::LROUND, MVT::f32, Legal); 387 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 388 setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal); 389 setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal); 390 setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal); 391 setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal); 392 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 393 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 394 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 395 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 396 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 397 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 398 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 399 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 400 for (auto CC : FPCCToExpand) 401 setCondCodeAction(CC, MVT::f32, Expand); 402 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 403 setOperationAction(ISD::SELECT, MVT::f32, Custom); 404 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 405 for (auto Op : FPOpToExpand) 406 setOperationAction(Op, MVT::f32, Expand); 407 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 408 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 409 } 410 411 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 412 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 413 414 if (Subtarget.hasStdExtD()) { 415 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 416 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 417 setOperationAction(ISD::LRINT, MVT::f64, Legal); 418 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 419 setOperationAction(ISD::LROUND, MVT::f64, Legal); 420 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 421 setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal); 422 setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal); 423 setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal); 424 setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal); 425 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 426 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 427 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 428 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 429 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 430 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 431 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 432 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 433 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 434 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 435 for (auto CC : FPCCToExpand) 436 setCondCodeAction(CC, MVT::f64, Expand); 437 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 438 setOperationAction(ISD::SELECT, MVT::f64, Custom); 439 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 440 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 441 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 442 for (auto Op : FPOpToExpand) 443 setOperationAction(Op, MVT::f64, Expand); 444 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 445 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 446 } 447 448 if (Subtarget.is64Bit()) { 449 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 450 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 451 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 452 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 453 } 454 455 if (Subtarget.hasStdExtF()) { 456 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 457 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 458 459 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 460 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 461 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 462 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 463 464 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 465 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 466 } 467 468 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 469 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 470 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 471 setOperationAction(ISD::JumpTable, XLenVT, Custom); 472 473 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 474 475 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 476 // Unfortunately this can't be determined just from the ISA naming string. 477 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 478 Subtarget.is64Bit() ? Legal : Custom); 479 480 setOperationAction(ISD::TRAP, MVT::Other, Legal); 481 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 482 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 483 if (Subtarget.is64Bit()) 484 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 485 486 if (Subtarget.hasStdExtA()) { 487 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 488 setMinCmpXchgSizeInBits(32); 489 } else { 490 setMaxAtomicSizeInBitsSupported(0); 491 } 492 493 setBooleanContents(ZeroOrOneBooleanContent); 494 495 if (Subtarget.hasVInstructions()) { 496 setBooleanVectorContents(ZeroOrOneBooleanContent); 497 498 setOperationAction(ISD::VSCALE, XLenVT, Custom); 499 500 // RVV intrinsics may have illegal operands. 501 // We also need to custom legalize vmv.x.s. 502 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 503 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 504 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 505 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 506 if (Subtarget.is64Bit()) { 507 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 508 } else { 509 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 510 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 511 } 512 513 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 514 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 515 516 static const unsigned IntegerVPOps[] = { 517 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 518 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 519 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 520 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 521 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 522 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 523 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 524 ISD::VP_SELECT}; 525 526 static const unsigned FloatingPointVPOps[] = { 527 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 528 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 529 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT}; 530 531 if (!Subtarget.is64Bit()) { 532 // We must custom-lower certain vXi64 operations on RV32 due to the vector 533 // element type being illegal. 534 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 535 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 536 537 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 538 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 539 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 540 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 541 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 542 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 543 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 544 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 545 546 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 547 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 548 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 549 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 550 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 551 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 552 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 553 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 554 } 555 556 for (MVT VT : BoolVecVTs) { 557 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 558 559 // Mask VTs are custom-expanded into a series of standard nodes 560 setOperationAction(ISD::TRUNCATE, VT, Custom); 561 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 562 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 563 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 564 565 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 566 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 567 568 setOperationAction(ISD::SELECT, VT, Custom); 569 setOperationAction(ISD::SELECT_CC, VT, Expand); 570 setOperationAction(ISD::VSELECT, VT, Expand); 571 setOperationAction(ISD::VP_SELECT, VT, Expand); 572 573 setOperationAction(ISD::VP_AND, VT, Custom); 574 setOperationAction(ISD::VP_OR, VT, Custom); 575 setOperationAction(ISD::VP_XOR, VT, Custom); 576 577 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 578 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 579 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 580 581 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 582 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 583 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 584 585 // RVV has native int->float & float->int conversions where the 586 // element type sizes are within one power-of-two of each other. Any 587 // wider distances between type sizes have to be lowered as sequences 588 // which progressively narrow the gap in stages. 589 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 590 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 591 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 592 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 593 594 // Expand all extending loads to types larger than this, and truncating 595 // stores from types larger than this. 596 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 597 setTruncStoreAction(OtherVT, VT, Expand); 598 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 599 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 600 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 601 } 602 } 603 604 for (MVT VT : IntVecVTs) { 605 if (VT.getVectorElementType() == MVT::i64 && 606 !Subtarget.hasVInstructionsI64()) 607 continue; 608 609 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 610 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 611 612 // Vectors implement MULHS/MULHU. 613 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 614 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 615 616 setOperationAction(ISD::SMIN, VT, Legal); 617 setOperationAction(ISD::SMAX, VT, Legal); 618 setOperationAction(ISD::UMIN, VT, Legal); 619 setOperationAction(ISD::UMAX, VT, Legal); 620 621 setOperationAction(ISD::ROTL, VT, Expand); 622 setOperationAction(ISD::ROTR, VT, Expand); 623 624 setOperationAction(ISD::CTTZ, VT, Expand); 625 setOperationAction(ISD::CTLZ, VT, Expand); 626 setOperationAction(ISD::CTPOP, VT, Expand); 627 628 setOperationAction(ISD::BSWAP, VT, Expand); 629 630 // Custom-lower extensions and truncations from/to mask types. 631 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 632 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 633 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 634 635 // RVV has native int->float & float->int conversions where the 636 // element type sizes are within one power-of-two of each other. Any 637 // wider distances between type sizes have to be lowered as sequences 638 // which progressively narrow the gap in stages. 639 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 640 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 641 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 642 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 643 644 setOperationAction(ISD::SADDSAT, VT, Legal); 645 setOperationAction(ISD::UADDSAT, VT, Legal); 646 setOperationAction(ISD::SSUBSAT, VT, Legal); 647 setOperationAction(ISD::USUBSAT, VT, Legal); 648 649 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 650 // nodes which truncate by one power of two at a time. 651 setOperationAction(ISD::TRUNCATE, VT, Custom); 652 653 // Custom-lower insert/extract operations to simplify patterns. 654 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 655 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 656 657 // Custom-lower reduction operations to set up the corresponding custom 658 // nodes' operands. 659 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 660 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 661 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 662 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 663 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 664 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 665 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 666 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 667 668 for (unsigned VPOpc : IntegerVPOps) 669 setOperationAction(VPOpc, VT, Custom); 670 671 setOperationAction(ISD::LOAD, VT, Custom); 672 setOperationAction(ISD::STORE, VT, Custom); 673 674 setOperationAction(ISD::MLOAD, VT, Custom); 675 setOperationAction(ISD::MSTORE, VT, Custom); 676 setOperationAction(ISD::MGATHER, VT, Custom); 677 setOperationAction(ISD::MSCATTER, VT, Custom); 678 679 setOperationAction(ISD::VP_LOAD, VT, Custom); 680 setOperationAction(ISD::VP_STORE, VT, Custom); 681 setOperationAction(ISD::VP_GATHER, VT, Custom); 682 setOperationAction(ISD::VP_SCATTER, VT, Custom); 683 684 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 685 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 686 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 687 688 setOperationAction(ISD::SELECT, VT, Custom); 689 setOperationAction(ISD::SELECT_CC, VT, Expand); 690 691 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 692 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 693 694 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 695 setTruncStoreAction(VT, OtherVT, Expand); 696 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 697 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 698 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 699 } 700 701 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 702 // type that can represent the value exactly. 703 if (VT.getVectorElementType() != MVT::i64) { 704 MVT FloatEltVT = 705 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 706 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 707 if (isTypeLegal(FloatVT)) { 708 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 709 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 710 } 711 } 712 } 713 714 // Expand various CCs to best match the RVV ISA, which natively supports UNE 715 // but no other unordered comparisons, and supports all ordered comparisons 716 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 717 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 718 // and we pattern-match those back to the "original", swapping operands once 719 // more. This way we catch both operations and both "vf" and "fv" forms with 720 // fewer patterns. 721 static const ISD::CondCode VFPCCToExpand[] = { 722 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 723 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 724 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 725 }; 726 727 // Sets common operation actions on RVV floating-point vector types. 728 const auto SetCommonVFPActions = [&](MVT VT) { 729 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 730 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 731 // sizes are within one power-of-two of each other. Therefore conversions 732 // between vXf16 and vXf64 must be lowered as sequences which convert via 733 // vXf32. 734 setOperationAction(ISD::FP_ROUND, VT, Custom); 735 setOperationAction(ISD::FP_EXTEND, VT, Custom); 736 // Custom-lower insert/extract operations to simplify patterns. 737 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 738 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 739 // Expand various condition codes (explained above). 740 for (auto CC : VFPCCToExpand) 741 setCondCodeAction(CC, VT, Expand); 742 743 setOperationAction(ISD::FMINNUM, VT, Legal); 744 setOperationAction(ISD::FMAXNUM, VT, Legal); 745 746 setOperationAction(ISD::FTRUNC, VT, Custom); 747 setOperationAction(ISD::FCEIL, VT, Custom); 748 setOperationAction(ISD::FFLOOR, VT, Custom); 749 750 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 751 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 752 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 753 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 754 755 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 756 757 setOperationAction(ISD::LOAD, VT, Custom); 758 setOperationAction(ISD::STORE, VT, Custom); 759 760 setOperationAction(ISD::MLOAD, VT, Custom); 761 setOperationAction(ISD::MSTORE, VT, Custom); 762 setOperationAction(ISD::MGATHER, VT, Custom); 763 setOperationAction(ISD::MSCATTER, VT, Custom); 764 765 setOperationAction(ISD::VP_LOAD, VT, Custom); 766 setOperationAction(ISD::VP_STORE, VT, Custom); 767 setOperationAction(ISD::VP_GATHER, VT, Custom); 768 setOperationAction(ISD::VP_SCATTER, VT, Custom); 769 770 setOperationAction(ISD::SELECT, VT, Custom); 771 setOperationAction(ISD::SELECT_CC, VT, Expand); 772 773 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 774 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 775 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 776 777 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 778 779 for (unsigned VPOpc : FloatingPointVPOps) 780 setOperationAction(VPOpc, VT, Custom); 781 }; 782 783 // Sets common extload/truncstore actions on RVV floating-point vector 784 // types. 785 const auto SetCommonVFPExtLoadTruncStoreActions = 786 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 787 for (auto SmallVT : SmallerVTs) { 788 setTruncStoreAction(VT, SmallVT, Expand); 789 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 790 } 791 }; 792 793 if (Subtarget.hasVInstructionsF16()) 794 for (MVT VT : F16VecVTs) 795 SetCommonVFPActions(VT); 796 797 for (MVT VT : F32VecVTs) { 798 if (Subtarget.hasVInstructionsF32()) 799 SetCommonVFPActions(VT); 800 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 801 } 802 803 for (MVT VT : F64VecVTs) { 804 if (Subtarget.hasVInstructionsF64()) 805 SetCommonVFPActions(VT); 806 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 807 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 808 } 809 810 if (Subtarget.useRVVForFixedLengthVectors()) { 811 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 812 if (!useRVVForFixedLengthVectorVT(VT)) 813 continue; 814 815 // By default everything must be expanded. 816 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 817 setOperationAction(Op, VT, Expand); 818 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 819 setTruncStoreAction(VT, OtherVT, Expand); 820 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 821 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 822 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 823 } 824 825 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 826 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 827 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 828 829 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 830 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 831 832 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 833 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 834 835 setOperationAction(ISD::LOAD, VT, Custom); 836 setOperationAction(ISD::STORE, VT, Custom); 837 838 setOperationAction(ISD::SETCC, VT, Custom); 839 840 setOperationAction(ISD::SELECT, VT, Custom); 841 842 setOperationAction(ISD::TRUNCATE, VT, Custom); 843 844 setOperationAction(ISD::BITCAST, VT, Custom); 845 846 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 847 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 848 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 849 850 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 851 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 852 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 853 854 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 855 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 856 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 857 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 858 859 // Operations below are different for between masks and other vectors. 860 if (VT.getVectorElementType() == MVT::i1) { 861 setOperationAction(ISD::VP_AND, VT, Custom); 862 setOperationAction(ISD::VP_OR, VT, Custom); 863 setOperationAction(ISD::VP_XOR, VT, Custom); 864 setOperationAction(ISD::AND, VT, Custom); 865 setOperationAction(ISD::OR, VT, Custom); 866 setOperationAction(ISD::XOR, VT, Custom); 867 continue; 868 } 869 870 // Use SPLAT_VECTOR to prevent type legalization from destroying the 871 // splats when type legalizing i64 scalar on RV32. 872 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 873 // improvements first. 874 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 875 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 876 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 877 } 878 879 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 880 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 881 882 setOperationAction(ISD::MLOAD, VT, Custom); 883 setOperationAction(ISD::MSTORE, VT, Custom); 884 setOperationAction(ISD::MGATHER, VT, Custom); 885 setOperationAction(ISD::MSCATTER, VT, Custom); 886 887 setOperationAction(ISD::VP_LOAD, VT, Custom); 888 setOperationAction(ISD::VP_STORE, VT, Custom); 889 setOperationAction(ISD::VP_GATHER, VT, Custom); 890 setOperationAction(ISD::VP_SCATTER, VT, Custom); 891 892 setOperationAction(ISD::ADD, VT, Custom); 893 setOperationAction(ISD::MUL, VT, Custom); 894 setOperationAction(ISD::SUB, VT, Custom); 895 setOperationAction(ISD::AND, VT, Custom); 896 setOperationAction(ISD::OR, VT, Custom); 897 setOperationAction(ISD::XOR, VT, Custom); 898 setOperationAction(ISD::SDIV, VT, Custom); 899 setOperationAction(ISD::SREM, VT, Custom); 900 setOperationAction(ISD::UDIV, VT, Custom); 901 setOperationAction(ISD::UREM, VT, Custom); 902 setOperationAction(ISD::SHL, VT, Custom); 903 setOperationAction(ISD::SRA, VT, Custom); 904 setOperationAction(ISD::SRL, VT, Custom); 905 906 setOperationAction(ISD::SMIN, VT, Custom); 907 setOperationAction(ISD::SMAX, VT, Custom); 908 setOperationAction(ISD::UMIN, VT, Custom); 909 setOperationAction(ISD::UMAX, VT, Custom); 910 setOperationAction(ISD::ABS, VT, Custom); 911 912 setOperationAction(ISD::MULHS, VT, Custom); 913 setOperationAction(ISD::MULHU, VT, Custom); 914 915 setOperationAction(ISD::SADDSAT, VT, Custom); 916 setOperationAction(ISD::UADDSAT, VT, Custom); 917 setOperationAction(ISD::SSUBSAT, VT, Custom); 918 setOperationAction(ISD::USUBSAT, VT, Custom); 919 920 setOperationAction(ISD::VSELECT, VT, Custom); 921 setOperationAction(ISD::SELECT_CC, VT, Expand); 922 923 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 924 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 925 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 926 927 // Custom-lower reduction operations to set up the corresponding custom 928 // nodes' operands. 929 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 930 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 931 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 932 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 933 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 934 935 for (unsigned VPOpc : IntegerVPOps) 936 setOperationAction(VPOpc, VT, Custom); 937 938 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 939 // type that can represent the value exactly. 940 if (VT.getVectorElementType() != MVT::i64) { 941 MVT FloatEltVT = 942 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 943 EVT FloatVT = 944 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 945 if (isTypeLegal(FloatVT)) { 946 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 947 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 948 } 949 } 950 } 951 952 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 953 if (!useRVVForFixedLengthVectorVT(VT)) 954 continue; 955 956 // By default everything must be expanded. 957 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 958 setOperationAction(Op, VT, Expand); 959 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 960 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 961 setTruncStoreAction(VT, OtherVT, Expand); 962 } 963 964 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 965 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 966 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 967 968 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 969 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 970 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 971 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 972 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 973 974 setOperationAction(ISD::LOAD, VT, Custom); 975 setOperationAction(ISD::STORE, VT, Custom); 976 setOperationAction(ISD::MLOAD, VT, Custom); 977 setOperationAction(ISD::MSTORE, VT, Custom); 978 setOperationAction(ISD::MGATHER, VT, Custom); 979 setOperationAction(ISD::MSCATTER, VT, Custom); 980 981 setOperationAction(ISD::VP_LOAD, VT, Custom); 982 setOperationAction(ISD::VP_STORE, VT, Custom); 983 setOperationAction(ISD::VP_GATHER, VT, Custom); 984 setOperationAction(ISD::VP_SCATTER, VT, Custom); 985 986 setOperationAction(ISD::FADD, VT, Custom); 987 setOperationAction(ISD::FSUB, VT, Custom); 988 setOperationAction(ISD::FMUL, VT, Custom); 989 setOperationAction(ISD::FDIV, VT, Custom); 990 setOperationAction(ISD::FNEG, VT, Custom); 991 setOperationAction(ISD::FABS, VT, Custom); 992 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 993 setOperationAction(ISD::FSQRT, VT, Custom); 994 setOperationAction(ISD::FMA, VT, Custom); 995 setOperationAction(ISD::FMINNUM, VT, Custom); 996 setOperationAction(ISD::FMAXNUM, VT, Custom); 997 998 setOperationAction(ISD::FP_ROUND, VT, Custom); 999 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1000 1001 setOperationAction(ISD::FTRUNC, VT, Custom); 1002 setOperationAction(ISD::FCEIL, VT, Custom); 1003 setOperationAction(ISD::FFLOOR, VT, Custom); 1004 1005 for (auto CC : VFPCCToExpand) 1006 setCondCodeAction(CC, VT, Expand); 1007 1008 setOperationAction(ISD::VSELECT, VT, Custom); 1009 setOperationAction(ISD::SELECT, VT, Custom); 1010 setOperationAction(ISD::SELECT_CC, VT, Expand); 1011 1012 setOperationAction(ISD::BITCAST, VT, Custom); 1013 1014 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1015 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1016 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1017 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1018 1019 for (unsigned VPOpc : FloatingPointVPOps) 1020 setOperationAction(VPOpc, VT, Custom); 1021 } 1022 1023 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1024 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1025 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1026 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1027 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1028 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1029 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1030 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1031 } 1032 } 1033 1034 // Function alignments. 1035 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1036 setMinFunctionAlignment(FunctionAlignment); 1037 setPrefFunctionAlignment(FunctionAlignment); 1038 1039 setMinimumJumpTableEntries(5); 1040 1041 // Jumps are expensive, compared to logic 1042 setJumpIsExpensive(); 1043 1044 setTargetDAGCombine(ISD::ADD); 1045 setTargetDAGCombine(ISD::SUB); 1046 setTargetDAGCombine(ISD::AND); 1047 setTargetDAGCombine(ISD::OR); 1048 setTargetDAGCombine(ISD::XOR); 1049 setTargetDAGCombine(ISD::ANY_EXTEND); 1050 if (Subtarget.hasStdExtF()) { 1051 setTargetDAGCombine(ISD::ZERO_EXTEND); 1052 setTargetDAGCombine(ISD::FP_TO_SINT); 1053 setTargetDAGCombine(ISD::FP_TO_UINT); 1054 } 1055 if (Subtarget.hasVInstructions()) { 1056 setTargetDAGCombine(ISD::FCOPYSIGN); 1057 setTargetDAGCombine(ISD::MGATHER); 1058 setTargetDAGCombine(ISD::MSCATTER); 1059 setTargetDAGCombine(ISD::VP_GATHER); 1060 setTargetDAGCombine(ISD::VP_SCATTER); 1061 setTargetDAGCombine(ISD::SRA); 1062 setTargetDAGCombine(ISD::SRL); 1063 setTargetDAGCombine(ISD::SHL); 1064 setTargetDAGCombine(ISD::STORE); 1065 } 1066 } 1067 1068 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1069 LLVMContext &Context, 1070 EVT VT) const { 1071 if (!VT.isVector()) 1072 return getPointerTy(DL); 1073 if (Subtarget.hasVInstructions() && 1074 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1075 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1076 return VT.changeVectorElementTypeToInteger(); 1077 } 1078 1079 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1080 return Subtarget.getXLenVT(); 1081 } 1082 1083 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1084 const CallInst &I, 1085 MachineFunction &MF, 1086 unsigned Intrinsic) const { 1087 auto &DL = I.getModule()->getDataLayout(); 1088 switch (Intrinsic) { 1089 default: 1090 return false; 1091 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1092 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1093 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1094 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1095 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1096 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1097 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1098 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1099 case Intrinsic::riscv_masked_cmpxchg_i32: { 1100 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 1101 Info.opc = ISD::INTRINSIC_W_CHAIN; 1102 Info.memVT = MVT::getVT(PtrTy->getElementType()); 1103 Info.ptrVal = I.getArgOperand(0); 1104 Info.offset = 0; 1105 Info.align = Align(4); 1106 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1107 MachineMemOperand::MOVolatile; 1108 return true; 1109 } 1110 case Intrinsic::riscv_masked_strided_load: 1111 Info.opc = ISD::INTRINSIC_W_CHAIN; 1112 Info.ptrVal = I.getArgOperand(1); 1113 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1114 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1115 Info.size = MemoryLocation::UnknownSize; 1116 Info.flags |= MachineMemOperand::MOLoad; 1117 return true; 1118 case Intrinsic::riscv_masked_strided_store: 1119 Info.opc = ISD::INTRINSIC_VOID; 1120 Info.ptrVal = I.getArgOperand(1); 1121 Info.memVT = 1122 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1123 Info.align = Align( 1124 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1125 8); 1126 Info.size = MemoryLocation::UnknownSize; 1127 Info.flags |= MachineMemOperand::MOStore; 1128 return true; 1129 } 1130 } 1131 1132 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1133 const AddrMode &AM, Type *Ty, 1134 unsigned AS, 1135 Instruction *I) const { 1136 // No global is ever allowed as a base. 1137 if (AM.BaseGV) 1138 return false; 1139 1140 // Require a 12-bit signed offset. 1141 if (!isInt<12>(AM.BaseOffs)) 1142 return false; 1143 1144 switch (AM.Scale) { 1145 case 0: // "r+i" or just "i", depending on HasBaseReg. 1146 break; 1147 case 1: 1148 if (!AM.HasBaseReg) // allow "r+i". 1149 break; 1150 return false; // disallow "r+r" or "r+r+i". 1151 default: 1152 return false; 1153 } 1154 1155 return true; 1156 } 1157 1158 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1159 return isInt<12>(Imm); 1160 } 1161 1162 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1163 return isInt<12>(Imm); 1164 } 1165 1166 // On RV32, 64-bit integers are split into their high and low parts and held 1167 // in two different registers, so the trunc is free since the low register can 1168 // just be used. 1169 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1170 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1171 return false; 1172 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1173 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1174 return (SrcBits == 64 && DestBits == 32); 1175 } 1176 1177 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1178 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1179 !SrcVT.isInteger() || !DstVT.isInteger()) 1180 return false; 1181 unsigned SrcBits = SrcVT.getSizeInBits(); 1182 unsigned DestBits = DstVT.getSizeInBits(); 1183 return (SrcBits == 64 && DestBits == 32); 1184 } 1185 1186 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1187 // Zexts are free if they can be combined with a load. 1188 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1189 // poorly with type legalization of compares preferring sext. 1190 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1191 EVT MemVT = LD->getMemoryVT(); 1192 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1193 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1194 LD->getExtensionType() == ISD::ZEXTLOAD)) 1195 return true; 1196 } 1197 1198 return TargetLowering::isZExtFree(Val, VT2); 1199 } 1200 1201 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1202 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1203 } 1204 1205 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1206 return Subtarget.hasStdExtZbb(); 1207 } 1208 1209 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1210 return Subtarget.hasStdExtZbb(); 1211 } 1212 1213 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1214 EVT VT = Y.getValueType(); 1215 1216 // FIXME: Support vectors once we have tests. 1217 if (VT.isVector()) 1218 return false; 1219 1220 return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y); 1221 } 1222 1223 /// Check if sinking \p I's operands to I's basic block is profitable, because 1224 /// the operands can be folded into a target instruction, e.g. 1225 /// splats of scalars can fold into vector instructions. 1226 bool RISCVTargetLowering::shouldSinkOperands( 1227 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1228 using namespace llvm::PatternMatch; 1229 1230 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1231 return false; 1232 1233 auto IsSinker = [&](Instruction *I, int Operand) { 1234 switch (I->getOpcode()) { 1235 case Instruction::Add: 1236 case Instruction::Sub: 1237 case Instruction::Mul: 1238 case Instruction::And: 1239 case Instruction::Or: 1240 case Instruction::Xor: 1241 case Instruction::FAdd: 1242 case Instruction::FSub: 1243 case Instruction::FMul: 1244 case Instruction::FDiv: 1245 case Instruction::ICmp: 1246 case Instruction::FCmp: 1247 return true; 1248 case Instruction::Shl: 1249 case Instruction::LShr: 1250 case Instruction::AShr: 1251 case Instruction::UDiv: 1252 case Instruction::SDiv: 1253 case Instruction::URem: 1254 case Instruction::SRem: 1255 return Operand == 1; 1256 case Instruction::Call: 1257 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1258 switch (II->getIntrinsicID()) { 1259 case Intrinsic::fma: 1260 return Operand == 0 || Operand == 1; 1261 default: 1262 return false; 1263 } 1264 } 1265 return false; 1266 default: 1267 return false; 1268 } 1269 }; 1270 1271 for (auto OpIdx : enumerate(I->operands())) { 1272 if (!IsSinker(I, OpIdx.index())) 1273 continue; 1274 1275 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1276 // Make sure we are not already sinking this operand 1277 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1278 continue; 1279 1280 // We are looking for a splat that can be sunk. 1281 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1282 m_Undef(), m_ZeroMask()))) 1283 continue; 1284 1285 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1286 // and vector registers 1287 for (Use &U : Op->uses()) { 1288 Instruction *Insn = cast<Instruction>(U.getUser()); 1289 if (!IsSinker(Insn, U.getOperandNo())) 1290 return false; 1291 } 1292 1293 Ops.push_back(&Op->getOperandUse(0)); 1294 Ops.push_back(&OpIdx.value()); 1295 } 1296 return true; 1297 } 1298 1299 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1300 bool ForCodeSize) const { 1301 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1302 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1303 return false; 1304 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1305 return false; 1306 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1307 return false; 1308 if (Imm.isNegZero()) 1309 return false; 1310 return Imm.isZero(); 1311 } 1312 1313 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1314 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1315 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1316 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1317 } 1318 1319 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1320 CallingConv::ID CC, 1321 EVT VT) const { 1322 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1323 // We might still end up using a GPR but that will be decided based on ABI. 1324 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1325 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1326 return MVT::f32; 1327 1328 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1329 } 1330 1331 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1332 CallingConv::ID CC, 1333 EVT VT) const { 1334 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1335 // We might still end up using a GPR but that will be decided based on ABI. 1336 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1337 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1338 return 1; 1339 1340 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1341 } 1342 1343 // Changes the condition code and swaps operands if necessary, so the SetCC 1344 // operation matches one of the comparisons supported directly by branches 1345 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1346 // with 1/-1. 1347 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1348 ISD::CondCode &CC, SelectionDAG &DAG) { 1349 // Convert X > -1 to X >= 0. 1350 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1351 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1352 CC = ISD::SETGE; 1353 return; 1354 } 1355 // Convert X < 1 to 0 >= X. 1356 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1357 RHS = LHS; 1358 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1359 CC = ISD::SETGE; 1360 return; 1361 } 1362 1363 switch (CC) { 1364 default: 1365 break; 1366 case ISD::SETGT: 1367 case ISD::SETLE: 1368 case ISD::SETUGT: 1369 case ISD::SETULE: 1370 CC = ISD::getSetCCSwappedOperands(CC); 1371 std::swap(LHS, RHS); 1372 break; 1373 } 1374 } 1375 1376 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1377 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1378 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1379 if (VT.getVectorElementType() == MVT::i1) 1380 KnownSize *= 8; 1381 1382 switch (KnownSize) { 1383 default: 1384 llvm_unreachable("Invalid LMUL."); 1385 case 8: 1386 return RISCVII::VLMUL::LMUL_F8; 1387 case 16: 1388 return RISCVII::VLMUL::LMUL_F4; 1389 case 32: 1390 return RISCVII::VLMUL::LMUL_F2; 1391 case 64: 1392 return RISCVII::VLMUL::LMUL_1; 1393 case 128: 1394 return RISCVII::VLMUL::LMUL_2; 1395 case 256: 1396 return RISCVII::VLMUL::LMUL_4; 1397 case 512: 1398 return RISCVII::VLMUL::LMUL_8; 1399 } 1400 } 1401 1402 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1403 switch (LMul) { 1404 default: 1405 llvm_unreachable("Invalid LMUL."); 1406 case RISCVII::VLMUL::LMUL_F8: 1407 case RISCVII::VLMUL::LMUL_F4: 1408 case RISCVII::VLMUL::LMUL_F2: 1409 case RISCVII::VLMUL::LMUL_1: 1410 return RISCV::VRRegClassID; 1411 case RISCVII::VLMUL::LMUL_2: 1412 return RISCV::VRM2RegClassID; 1413 case RISCVII::VLMUL::LMUL_4: 1414 return RISCV::VRM4RegClassID; 1415 case RISCVII::VLMUL::LMUL_8: 1416 return RISCV::VRM8RegClassID; 1417 } 1418 } 1419 1420 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1421 RISCVII::VLMUL LMUL = getLMUL(VT); 1422 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1423 LMUL == RISCVII::VLMUL::LMUL_F4 || 1424 LMUL == RISCVII::VLMUL::LMUL_F2 || 1425 LMUL == RISCVII::VLMUL::LMUL_1) { 1426 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1427 "Unexpected subreg numbering"); 1428 return RISCV::sub_vrm1_0 + Index; 1429 } 1430 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1431 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1432 "Unexpected subreg numbering"); 1433 return RISCV::sub_vrm2_0 + Index; 1434 } 1435 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1436 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1437 "Unexpected subreg numbering"); 1438 return RISCV::sub_vrm4_0 + Index; 1439 } 1440 llvm_unreachable("Invalid vector type."); 1441 } 1442 1443 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1444 if (VT.getVectorElementType() == MVT::i1) 1445 return RISCV::VRRegClassID; 1446 return getRegClassIDForLMUL(getLMUL(VT)); 1447 } 1448 1449 // Attempt to decompose a subvector insert/extract between VecVT and 1450 // SubVecVT via subregister indices. Returns the subregister index that 1451 // can perform the subvector insert/extract with the given element index, as 1452 // well as the index corresponding to any leftover subvectors that must be 1453 // further inserted/extracted within the register class for SubVecVT. 1454 std::pair<unsigned, unsigned> 1455 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1456 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1457 const RISCVRegisterInfo *TRI) { 1458 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1459 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1460 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1461 "Register classes not ordered"); 1462 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1463 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1464 // Try to compose a subregister index that takes us from the incoming 1465 // LMUL>1 register class down to the outgoing one. At each step we half 1466 // the LMUL: 1467 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1468 // Note that this is not guaranteed to find a subregister index, such as 1469 // when we are extracting from one VR type to another. 1470 unsigned SubRegIdx = RISCV::NoSubRegister; 1471 for (const unsigned RCID : 1472 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1473 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1474 VecVT = VecVT.getHalfNumVectorElementsVT(); 1475 bool IsHi = 1476 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1477 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1478 getSubregIndexByMVT(VecVT, IsHi)); 1479 if (IsHi) 1480 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1481 } 1482 return {SubRegIdx, InsertExtractIdx}; 1483 } 1484 1485 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1486 // stores for those types. 1487 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1488 return !Subtarget.useRVVForFixedLengthVectors() || 1489 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1490 } 1491 1492 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1493 if (ScalarTy->isPointerTy()) 1494 return true; 1495 1496 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1497 ScalarTy->isIntegerTy(32)) 1498 return true; 1499 1500 if (ScalarTy->isIntegerTy(64)) 1501 return Subtarget.hasVInstructionsI64(); 1502 1503 if (ScalarTy->isHalfTy()) 1504 return Subtarget.hasVInstructionsF16(); 1505 if (ScalarTy->isFloatTy()) 1506 return Subtarget.hasVInstructionsF32(); 1507 if (ScalarTy->isDoubleTy()) 1508 return Subtarget.hasVInstructionsF64(); 1509 1510 return false; 1511 } 1512 1513 static bool useRVVForFixedLengthVectorVT(MVT VT, 1514 const RISCVSubtarget &Subtarget) { 1515 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1516 if (!Subtarget.useRVVForFixedLengthVectors()) 1517 return false; 1518 1519 // We only support a set of vector types with a consistent maximum fixed size 1520 // across all supported vector element types to avoid legalization issues. 1521 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1522 // fixed-length vector type we support is 1024 bytes. 1523 if (VT.getFixedSizeInBits() > 1024 * 8) 1524 return false; 1525 1526 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1527 1528 MVT EltVT = VT.getVectorElementType(); 1529 1530 // Don't use RVV for vectors we cannot scalarize if required. 1531 switch (EltVT.SimpleTy) { 1532 // i1 is supported but has different rules. 1533 default: 1534 return false; 1535 case MVT::i1: 1536 // Masks can only use a single register. 1537 if (VT.getVectorNumElements() > MinVLen) 1538 return false; 1539 MinVLen /= 8; 1540 break; 1541 case MVT::i8: 1542 case MVT::i16: 1543 case MVT::i32: 1544 break; 1545 case MVT::i64: 1546 if (!Subtarget.hasVInstructionsI64()) 1547 return false; 1548 break; 1549 case MVT::f16: 1550 if (!Subtarget.hasVInstructionsF16()) 1551 return false; 1552 break; 1553 case MVT::f32: 1554 if (!Subtarget.hasVInstructionsF32()) 1555 return false; 1556 break; 1557 case MVT::f64: 1558 if (!Subtarget.hasVInstructionsF64()) 1559 return false; 1560 break; 1561 } 1562 1563 // Reject elements larger than ELEN. 1564 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1565 return false; 1566 1567 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1568 // Don't use RVV for types that don't fit. 1569 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1570 return false; 1571 1572 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1573 // the base fixed length RVV support in place. 1574 if (!VT.isPow2VectorType()) 1575 return false; 1576 1577 return true; 1578 } 1579 1580 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1581 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1582 } 1583 1584 // Return the largest legal scalable vector type that matches VT's element type. 1585 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1586 const RISCVSubtarget &Subtarget) { 1587 // This may be called before legal types are setup. 1588 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1589 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1590 "Expected legal fixed length vector!"); 1591 1592 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1593 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1594 1595 MVT EltVT = VT.getVectorElementType(); 1596 switch (EltVT.SimpleTy) { 1597 default: 1598 llvm_unreachable("unexpected element type for RVV container"); 1599 case MVT::i1: 1600 case MVT::i8: 1601 case MVT::i16: 1602 case MVT::i32: 1603 case MVT::i64: 1604 case MVT::f16: 1605 case MVT::f32: 1606 case MVT::f64: { 1607 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1608 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1609 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1610 unsigned NumElts = 1611 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1612 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1613 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1614 return MVT::getScalableVectorVT(EltVT, NumElts); 1615 } 1616 } 1617 } 1618 1619 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1620 const RISCVSubtarget &Subtarget) { 1621 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1622 Subtarget); 1623 } 1624 1625 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1626 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1627 } 1628 1629 // Grow V to consume an entire RVV register. 1630 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1631 const RISCVSubtarget &Subtarget) { 1632 assert(VT.isScalableVector() && 1633 "Expected to convert into a scalable vector!"); 1634 assert(V.getValueType().isFixedLengthVector() && 1635 "Expected a fixed length vector operand!"); 1636 SDLoc DL(V); 1637 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1638 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1639 } 1640 1641 // Shrink V so it's just big enough to maintain a VT's worth of data. 1642 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1643 const RISCVSubtarget &Subtarget) { 1644 assert(VT.isFixedLengthVector() && 1645 "Expected to convert into a fixed length vector!"); 1646 assert(V.getValueType().isScalableVector() && 1647 "Expected a scalable vector operand!"); 1648 SDLoc DL(V); 1649 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1650 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1651 } 1652 1653 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1654 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1655 // the vector type that it is contained in. 1656 static std::pair<SDValue, SDValue> 1657 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1658 const RISCVSubtarget &Subtarget) { 1659 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1660 MVT XLenVT = Subtarget.getXLenVT(); 1661 SDValue VL = VecVT.isFixedLengthVector() 1662 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1663 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1664 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1665 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1666 return {Mask, VL}; 1667 } 1668 1669 // As above but assuming the given type is a scalable vector type. 1670 static std::pair<SDValue, SDValue> 1671 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1672 const RISCVSubtarget &Subtarget) { 1673 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1674 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1675 } 1676 1677 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1678 // of either is (currently) supported. This can get us into an infinite loop 1679 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1680 // as a ..., etc. 1681 // Until either (or both) of these can reliably lower any node, reporting that 1682 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1683 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1684 // which is not desirable. 1685 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1686 EVT VT, unsigned DefinedValues) const { 1687 return false; 1688 } 1689 1690 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1691 // Only splats are currently supported. 1692 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1693 return true; 1694 1695 return false; 1696 } 1697 1698 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1699 const RISCVSubtarget &Subtarget) { 1700 // RISCV FP-to-int conversions saturate to the destination register size, but 1701 // don't produce 0 for nan. We can use a conversion instruction and fix the 1702 // nan case with a compare and a select. 1703 SDValue Src = Op.getOperand(0); 1704 1705 EVT DstVT = Op.getValueType(); 1706 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1707 1708 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1709 unsigned Opc; 1710 if (SatVT == DstVT) 1711 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1712 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1713 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1714 else 1715 return SDValue(); 1716 // FIXME: Support other SatVTs by clamping before or after the conversion. 1717 1718 SDLoc DL(Op); 1719 SDValue FpToInt = DAG.getNode( 1720 Opc, DL, DstVT, Src, 1721 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1722 1723 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1724 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1725 } 1726 1727 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1728 // and back. Taking care to avoid converting values that are nan or already 1729 // correct. 1730 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1731 // have FRM dependencies modeled yet. 1732 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1733 MVT VT = Op.getSimpleValueType(); 1734 assert(VT.isVector() && "Unexpected type"); 1735 1736 SDLoc DL(Op); 1737 1738 // Freeze the source since we are increasing the number of uses. 1739 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1740 1741 // Truncate to integer and convert back to FP. 1742 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1743 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1744 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1745 1746 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1747 1748 if (Op.getOpcode() == ISD::FCEIL) { 1749 // If the truncated value is the greater than or equal to the original 1750 // value, we've computed the ceil. Otherwise, we went the wrong way and 1751 // need to increase by 1. 1752 // FIXME: This should use a masked operation. Handle here or in isel? 1753 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1754 DAG.getConstantFP(1.0, DL, VT)); 1755 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1756 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1757 } else if (Op.getOpcode() == ISD::FFLOOR) { 1758 // If the truncated value is the less than or equal to the original value, 1759 // we've computed the floor. Otherwise, we went the wrong way and need to 1760 // decrease by 1. 1761 // FIXME: This should use a masked operation. Handle here or in isel? 1762 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1763 DAG.getConstantFP(1.0, DL, VT)); 1764 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1765 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1766 } 1767 1768 // Restore the original sign so that -0.0 is preserved. 1769 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1770 1771 // Determine the largest integer that can be represented exactly. This and 1772 // values larger than it don't have any fractional bits so don't need to 1773 // be converted. 1774 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1775 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1776 APFloat MaxVal = APFloat(FltSem); 1777 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1778 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1779 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1780 1781 // If abs(Src) was larger than MaxVal or nan, keep it. 1782 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1783 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1784 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1785 } 1786 1787 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1788 const RISCVSubtarget &Subtarget) { 1789 MVT VT = Op.getSimpleValueType(); 1790 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1791 1792 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1793 1794 SDLoc DL(Op); 1795 SDValue Mask, VL; 1796 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1797 1798 unsigned Opc = 1799 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1800 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1801 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1802 } 1803 1804 struct VIDSequence { 1805 int64_t StepNumerator; 1806 unsigned StepDenominator; 1807 int64_t Addend; 1808 }; 1809 1810 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1811 // to the (non-zero) step S and start value X. This can be then lowered as the 1812 // RVV sequence (VID * S) + X, for example. 1813 // The step S is represented as an integer numerator divided by a positive 1814 // denominator. Note that the implementation currently only identifies 1815 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1816 // cannot detect 2/3, for example. 1817 // Note that this method will also match potentially unappealing index 1818 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1819 // determine whether this is worth generating code for. 1820 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1821 unsigned NumElts = Op.getNumOperands(); 1822 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1823 if (!Op.getValueType().isInteger()) 1824 return None; 1825 1826 Optional<unsigned> SeqStepDenom; 1827 Optional<int64_t> SeqStepNum, SeqAddend; 1828 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1829 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1830 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1831 // Assume undef elements match the sequence; we just have to be careful 1832 // when interpolating across them. 1833 if (Op.getOperand(Idx).isUndef()) 1834 continue; 1835 // The BUILD_VECTOR must be all constants. 1836 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1837 return None; 1838 1839 uint64_t Val = Op.getConstantOperandVal(Idx) & 1840 maskTrailingOnes<uint64_t>(EltSizeInBits); 1841 1842 if (PrevElt) { 1843 // Calculate the step since the last non-undef element, and ensure 1844 // it's consistent across the entire sequence. 1845 unsigned IdxDiff = Idx - PrevElt->second; 1846 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1847 1848 // A zero-value value difference means that we're somewhere in the middle 1849 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1850 // step change before evaluating the sequence. 1851 if (ValDiff != 0) { 1852 int64_t Remainder = ValDiff % IdxDiff; 1853 // Normalize the step if it's greater than 1. 1854 if (Remainder != ValDiff) { 1855 // The difference must cleanly divide the element span. 1856 if (Remainder != 0) 1857 return None; 1858 ValDiff /= IdxDiff; 1859 IdxDiff = 1; 1860 } 1861 1862 if (!SeqStepNum) 1863 SeqStepNum = ValDiff; 1864 else if (ValDiff != SeqStepNum) 1865 return None; 1866 1867 if (!SeqStepDenom) 1868 SeqStepDenom = IdxDiff; 1869 else if (IdxDiff != *SeqStepDenom) 1870 return None; 1871 } 1872 } 1873 1874 // Record and/or check any addend. 1875 if (SeqStepNum && SeqStepDenom) { 1876 uint64_t ExpectedVal = 1877 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1878 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1879 if (!SeqAddend) 1880 SeqAddend = Addend; 1881 else if (SeqAddend != Addend) 1882 return None; 1883 } 1884 1885 // Record this non-undef element for later. 1886 if (!PrevElt || PrevElt->first != Val) 1887 PrevElt = std::make_pair(Val, Idx); 1888 } 1889 // We need to have logged both a step and an addend for this to count as 1890 // a legal index sequence. 1891 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1892 return None; 1893 1894 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1895 } 1896 1897 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1898 const RISCVSubtarget &Subtarget) { 1899 MVT VT = Op.getSimpleValueType(); 1900 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1901 1902 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1903 1904 SDLoc DL(Op); 1905 SDValue Mask, VL; 1906 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1907 1908 MVT XLenVT = Subtarget.getXLenVT(); 1909 unsigned NumElts = Op.getNumOperands(); 1910 1911 if (VT.getVectorElementType() == MVT::i1) { 1912 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1913 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1914 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1915 } 1916 1917 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1918 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1919 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1920 } 1921 1922 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1923 // scalar integer chunks whose bit-width depends on the number of mask 1924 // bits and XLEN. 1925 // First, determine the most appropriate scalar integer type to use. This 1926 // is at most XLenVT, but may be shrunk to a smaller vector element type 1927 // according to the size of the final vector - use i8 chunks rather than 1928 // XLenVT if we're producing a v8i1. This results in more consistent 1929 // codegen across RV32 and RV64. 1930 unsigned NumViaIntegerBits = 1931 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1932 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1933 // If we have to use more than one INSERT_VECTOR_ELT then this 1934 // optimization is likely to increase code size; avoid peforming it in 1935 // such a case. We can use a load from a constant pool in this case. 1936 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1937 return SDValue(); 1938 // Now we can create our integer vector type. Note that it may be larger 1939 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1940 MVT IntegerViaVecVT = 1941 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1942 divideCeil(NumElts, NumViaIntegerBits)); 1943 1944 uint64_t Bits = 0; 1945 unsigned BitPos = 0, IntegerEltIdx = 0; 1946 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1947 1948 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1949 // Once we accumulate enough bits to fill our scalar type, insert into 1950 // our vector and clear our accumulated data. 1951 if (I != 0 && I % NumViaIntegerBits == 0) { 1952 if (NumViaIntegerBits <= 32) 1953 Bits = SignExtend64(Bits, 32); 1954 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1955 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1956 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1957 Bits = 0; 1958 BitPos = 0; 1959 IntegerEltIdx++; 1960 } 1961 SDValue V = Op.getOperand(I); 1962 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1963 Bits |= ((uint64_t)BitValue << BitPos); 1964 } 1965 1966 // Insert the (remaining) scalar value into position in our integer 1967 // vector type. 1968 if (NumViaIntegerBits <= 32) 1969 Bits = SignExtend64(Bits, 32); 1970 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1971 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1972 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1973 1974 if (NumElts < NumViaIntegerBits) { 1975 // If we're producing a smaller vector than our minimum legal integer 1976 // type, bitcast to the equivalent (known-legal) mask type, and extract 1977 // our final mask. 1978 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1979 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1980 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1981 DAG.getConstant(0, DL, XLenVT)); 1982 } else { 1983 // Else we must have produced an integer type with the same size as the 1984 // mask type; bitcast for the final result. 1985 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1986 Vec = DAG.getBitcast(VT, Vec); 1987 } 1988 1989 return Vec; 1990 } 1991 1992 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1993 // vector type, we have a legal equivalently-sized i8 type, so we can use 1994 // that. 1995 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1996 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1997 1998 SDValue WideVec; 1999 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2000 // For a splat, perform a scalar truncate before creating the wider 2001 // vector. 2002 assert(Splat.getValueType() == XLenVT && 2003 "Unexpected type for i1 splat value"); 2004 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2005 DAG.getConstant(1, DL, XLenVT)); 2006 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2007 } else { 2008 SmallVector<SDValue, 8> Ops(Op->op_values()); 2009 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2010 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2011 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2012 } 2013 2014 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2015 } 2016 2017 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2018 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2019 : RISCVISD::VMV_V_X_VL; 2020 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 2021 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2022 } 2023 2024 // Try and match index sequences, which we can lower to the vid instruction 2025 // with optional modifications. An all-undef vector is matched by 2026 // getSplatValue, above. 2027 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2028 int64_t StepNumerator = SimpleVID->StepNumerator; 2029 unsigned StepDenominator = SimpleVID->StepDenominator; 2030 int64_t Addend = SimpleVID->Addend; 2031 2032 assert(StepNumerator != 0 && "Invalid step"); 2033 bool Negate = false; 2034 int64_t SplatStepVal = StepNumerator; 2035 unsigned StepOpcode = ISD::MUL; 2036 if (StepNumerator != 1) { 2037 if (isPowerOf2_64(std::abs(StepNumerator))) { 2038 Negate = StepNumerator < 0; 2039 StepOpcode = ISD::SHL; 2040 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2041 } 2042 } 2043 2044 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2045 // threshold since it's the immediate value many RVV instructions accept. 2046 // There is no vmul.vi instruction so ensure multiply constant can fit in 2047 // a single addi instruction. 2048 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2049 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2050 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2051 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2052 // Convert right out of the scalable type so we can use standard ISD 2053 // nodes for the rest of the computation. If we used scalable types with 2054 // these, we'd lose the fixed-length vector info and generate worse 2055 // vsetvli code. 2056 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2057 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2058 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2059 SDValue SplatStep = DAG.getSplatVector( 2060 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2061 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2062 } 2063 if (StepDenominator != 1) { 2064 SDValue SplatStep = DAG.getSplatVector( 2065 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2066 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2067 } 2068 if (Addend != 0 || Negate) { 2069 SDValue SplatAddend = 2070 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2071 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2072 } 2073 return VID; 2074 } 2075 } 2076 2077 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2078 // when re-interpreted as a vector with a larger element type. For example, 2079 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2080 // could be instead splat as 2081 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2082 // TODO: This optimization could also work on non-constant splats, but it 2083 // would require bit-manipulation instructions to construct the splat value. 2084 SmallVector<SDValue> Sequence; 2085 unsigned EltBitSize = VT.getScalarSizeInBits(); 2086 const auto *BV = cast<BuildVectorSDNode>(Op); 2087 if (VT.isInteger() && EltBitSize < 64 && 2088 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2089 BV->getRepeatedSequence(Sequence) && 2090 (Sequence.size() * EltBitSize) <= 64) { 2091 unsigned SeqLen = Sequence.size(); 2092 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2093 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2094 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2095 ViaIntVT == MVT::i64) && 2096 "Unexpected sequence type"); 2097 2098 unsigned EltIdx = 0; 2099 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2100 uint64_t SplatValue = 0; 2101 // Construct the amalgamated value which can be splatted as this larger 2102 // vector type. 2103 for (const auto &SeqV : Sequence) { 2104 if (!SeqV.isUndef()) 2105 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2106 << (EltIdx * EltBitSize)); 2107 EltIdx++; 2108 } 2109 2110 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2111 // achieve better constant materializion. 2112 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2113 SplatValue = SignExtend64(SplatValue, 32); 2114 2115 // Since we can't introduce illegal i64 types at this stage, we can only 2116 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2117 // way we can use RVV instructions to splat. 2118 assert((ViaIntVT.bitsLE(XLenVT) || 2119 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2120 "Unexpected bitcast sequence"); 2121 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2122 SDValue ViaVL = 2123 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2124 MVT ViaContainerVT = 2125 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2126 SDValue Splat = 2127 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2128 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2129 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2130 return DAG.getBitcast(VT, Splat); 2131 } 2132 } 2133 2134 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2135 // which constitute a large proportion of the elements. In such cases we can 2136 // splat a vector with the dominant element and make up the shortfall with 2137 // INSERT_VECTOR_ELTs. 2138 // Note that this includes vectors of 2 elements by association. The 2139 // upper-most element is the "dominant" one, allowing us to use a splat to 2140 // "insert" the upper element, and an insert of the lower element at position 2141 // 0, which improves codegen. 2142 SDValue DominantValue; 2143 unsigned MostCommonCount = 0; 2144 DenseMap<SDValue, unsigned> ValueCounts; 2145 unsigned NumUndefElts = 2146 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2147 2148 // Track the number of scalar loads we know we'd be inserting, estimated as 2149 // any non-zero floating-point constant. Other kinds of element are either 2150 // already in registers or are materialized on demand. The threshold at which 2151 // a vector load is more desirable than several scalar materializion and 2152 // vector-insertion instructions is not known. 2153 unsigned NumScalarLoads = 0; 2154 2155 for (SDValue V : Op->op_values()) { 2156 if (V.isUndef()) 2157 continue; 2158 2159 ValueCounts.insert(std::make_pair(V, 0)); 2160 unsigned &Count = ValueCounts[V]; 2161 2162 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2163 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2164 2165 // Is this value dominant? In case of a tie, prefer the highest element as 2166 // it's cheaper to insert near the beginning of a vector than it is at the 2167 // end. 2168 if (++Count >= MostCommonCount) { 2169 DominantValue = V; 2170 MostCommonCount = Count; 2171 } 2172 } 2173 2174 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2175 unsigned NumDefElts = NumElts - NumUndefElts; 2176 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2177 2178 // Don't perform this optimization when optimizing for size, since 2179 // materializing elements and inserting them tends to cause code bloat. 2180 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2181 ((MostCommonCount > DominantValueCountThreshold) || 2182 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2183 // Start by splatting the most common element. 2184 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2185 2186 DenseSet<SDValue> Processed{DominantValue}; 2187 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2188 for (const auto &OpIdx : enumerate(Op->ops())) { 2189 const SDValue &V = OpIdx.value(); 2190 if (V.isUndef() || !Processed.insert(V).second) 2191 continue; 2192 if (ValueCounts[V] == 1) { 2193 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2194 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2195 } else { 2196 // Blend in all instances of this value using a VSELECT, using a 2197 // mask where each bit signals whether that element is the one 2198 // we're after. 2199 SmallVector<SDValue> Ops; 2200 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2201 return DAG.getConstant(V == V1, DL, XLenVT); 2202 }); 2203 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2204 DAG.getBuildVector(SelMaskTy, DL, Ops), 2205 DAG.getSplatBuildVector(VT, DL, V), Vec); 2206 } 2207 } 2208 2209 return Vec; 2210 } 2211 2212 return SDValue(); 2213 } 2214 2215 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2216 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2217 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2218 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2219 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2220 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2221 // node in order to try and match RVV vector/scalar instructions. 2222 if ((LoC >> 31) == HiC) 2223 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2224 2225 // If vl is equal to VLMax and Hi constant is equal to Lo, we could use 2226 // vmv.v.x whose EEW = 32 to lower it. 2227 auto *Const = dyn_cast<ConstantSDNode>(VL); 2228 if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) { 2229 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2230 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2231 // access the subtarget here now. 2232 auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL); 2233 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2234 } 2235 } 2236 2237 // Fall back to a stack store and stride x0 vector load. 2238 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2239 } 2240 2241 // Called by type legalization to handle splat of i64 on RV32. 2242 // FIXME: We can optimize this when the type has sign or zero bits in one 2243 // of the halves. 2244 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2245 SDValue VL, SelectionDAG &DAG) { 2246 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2247 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2248 DAG.getConstant(0, DL, MVT::i32)); 2249 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2250 DAG.getConstant(1, DL, MVT::i32)); 2251 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2252 } 2253 2254 // This function lowers a splat of a scalar operand Splat with the vector 2255 // length VL. It ensures the final sequence is type legal, which is useful when 2256 // lowering a splat after type legalization. 2257 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2258 SelectionDAG &DAG, 2259 const RISCVSubtarget &Subtarget) { 2260 if (VT.isFloatingPoint()) { 2261 // If VL is 1, we could use vfmv.s.f. 2262 if (isOneConstant(VL)) 2263 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT), 2264 Scalar, VL); 2265 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2266 } 2267 2268 MVT XLenVT = Subtarget.getXLenVT(); 2269 2270 // Simplest case is that the operand needs to be promoted to XLenVT. 2271 if (Scalar.getValueType().bitsLE(XLenVT)) { 2272 // If the operand is a constant, sign extend to increase our chances 2273 // of being able to use a .vi instruction. ANY_EXTEND would become a 2274 // a zero extend and the simm5 check in isel would fail. 2275 // FIXME: Should we ignore the upper bits in isel instead? 2276 unsigned ExtOpc = 2277 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2278 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2279 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2280 // If VL is 1 and the scalar value won't benefit from immediate, we could 2281 // use vmv.s.x. 2282 if (isOneConstant(VL) && 2283 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2284 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar, 2285 VL); 2286 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2287 } 2288 2289 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2290 "Unexpected scalar for splat lowering!"); 2291 2292 if (isOneConstant(VL) && isNullConstant(Scalar)) 2293 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), 2294 DAG.getConstant(0, DL, XLenVT), VL); 2295 2296 // Otherwise use the more complicated splatting algorithm. 2297 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2298 } 2299 2300 // Is the mask a slidedown that shifts in undefs. 2301 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) { 2302 int Size = Mask.size(); 2303 2304 // Elements shifted in should be undef. 2305 auto CheckUndefs = [&](int Shift) { 2306 for (int i = Size - Shift; i != Size; ++i) 2307 if (Mask[i] >= 0) 2308 return false; 2309 return true; 2310 }; 2311 2312 // Elements should be shifted or undef. 2313 auto MatchShift = [&](int Shift) { 2314 for (int i = 0; i != Size - Shift; ++i) 2315 if (Mask[i] >= 0 && Mask[i] != Shift + i) 2316 return false; 2317 return true; 2318 }; 2319 2320 // Try all possible shifts. 2321 for (int Shift = 1; Shift != Size; ++Shift) 2322 if (CheckUndefs(Shift) && MatchShift(Shift)) 2323 return Shift; 2324 2325 // No match. 2326 return -1; 2327 } 2328 2329 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2330 const RISCVSubtarget &Subtarget) { 2331 SDValue V1 = Op.getOperand(0); 2332 SDValue V2 = Op.getOperand(1); 2333 SDLoc DL(Op); 2334 MVT XLenVT = Subtarget.getXLenVT(); 2335 MVT VT = Op.getSimpleValueType(); 2336 unsigned NumElts = VT.getVectorNumElements(); 2337 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2338 2339 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2340 2341 SDValue TrueMask, VL; 2342 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2343 2344 if (SVN->isSplat()) { 2345 const int Lane = SVN->getSplatIndex(); 2346 if (Lane >= 0) { 2347 MVT SVT = VT.getVectorElementType(); 2348 2349 // Turn splatted vector load into a strided load with an X0 stride. 2350 SDValue V = V1; 2351 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2352 // with undef. 2353 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2354 int Offset = Lane; 2355 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2356 int OpElements = 2357 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2358 V = V.getOperand(Offset / OpElements); 2359 Offset %= OpElements; 2360 } 2361 2362 // We need to ensure the load isn't atomic or volatile. 2363 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2364 auto *Ld = cast<LoadSDNode>(V); 2365 Offset *= SVT.getStoreSize(); 2366 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2367 TypeSize::Fixed(Offset), DL); 2368 2369 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2370 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2371 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2372 SDValue IntID = 2373 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2374 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2375 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2376 SDValue NewLoad = DAG.getMemIntrinsicNode( 2377 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2378 DAG.getMachineFunction().getMachineMemOperand( 2379 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2380 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2381 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2382 } 2383 2384 // Otherwise use a scalar load and splat. This will give the best 2385 // opportunity to fold a splat into the operation. ISel can turn it into 2386 // the x0 strided load if we aren't able to fold away the select. 2387 if (SVT.isFloatingPoint()) 2388 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2389 Ld->getPointerInfo().getWithOffset(Offset), 2390 Ld->getOriginalAlign(), 2391 Ld->getMemOperand()->getFlags()); 2392 else 2393 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2394 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2395 Ld->getOriginalAlign(), 2396 Ld->getMemOperand()->getFlags()); 2397 DAG.makeEquivalentMemoryOrdering(Ld, V); 2398 2399 unsigned Opc = 2400 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2401 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2402 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2403 } 2404 2405 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2406 assert(Lane < (int)NumElts && "Unexpected lane!"); 2407 SDValue Gather = 2408 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2409 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2410 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2411 } 2412 } 2413 2414 // Try to match as a slidedown. 2415 int SlideAmt = matchShuffleAsSlideDown(SVN->getMask()); 2416 if (SlideAmt >= 0) { 2417 // TODO: Should we reduce the VL to account for the upper undef elements? 2418 // Requires additional vsetvlis, but might be faster to execute. 2419 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2420 SDValue SlideDown = 2421 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 2422 DAG.getUNDEF(ContainerVT), V1, 2423 DAG.getConstant(SlideAmt, DL, XLenVT), 2424 TrueMask, VL); 2425 return convertFromScalableVector(VT, SlideDown, DAG, Subtarget); 2426 } 2427 2428 // Detect shuffles which can be re-expressed as vector selects; these are 2429 // shuffles in which each element in the destination is taken from an element 2430 // at the corresponding index in either source vectors. 2431 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2432 int MaskIndex = MaskIdx.value(); 2433 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2434 }); 2435 2436 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2437 2438 SmallVector<SDValue> MaskVals; 2439 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2440 // merged with a second vrgather. 2441 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2442 2443 // By default we preserve the original operand order, and use a mask to 2444 // select LHS as true and RHS as false. However, since RVV vector selects may 2445 // feature splats but only on the LHS, we may choose to invert our mask and 2446 // instead select between RHS and LHS. 2447 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2448 bool InvertMask = IsSelect == SwapOps; 2449 2450 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2451 // half. 2452 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2453 2454 // Now construct the mask that will be used by the vselect or blended 2455 // vrgather operation. For vrgathers, construct the appropriate indices into 2456 // each vector. 2457 for (int MaskIndex : SVN->getMask()) { 2458 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2459 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2460 if (!IsSelect) { 2461 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2462 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2463 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2464 : DAG.getUNDEF(XLenVT)); 2465 GatherIndicesRHS.push_back( 2466 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2467 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2468 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2469 ++LHSIndexCounts[MaskIndex]; 2470 if (!IsLHSOrUndefIndex) 2471 ++RHSIndexCounts[MaskIndex - NumElts]; 2472 } 2473 } 2474 2475 if (SwapOps) { 2476 std::swap(V1, V2); 2477 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2478 } 2479 2480 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2481 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2482 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2483 2484 if (IsSelect) 2485 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2486 2487 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2488 // On such a large vector we're unable to use i8 as the index type. 2489 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2490 // may involve vector splitting if we're already at LMUL=8, or our 2491 // user-supplied maximum fixed-length LMUL. 2492 return SDValue(); 2493 } 2494 2495 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2496 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2497 MVT IndexVT = VT.changeTypeToInteger(); 2498 // Since we can't introduce illegal index types at this stage, use i16 and 2499 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2500 // than XLenVT. 2501 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2502 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2503 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2504 } 2505 2506 MVT IndexContainerVT = 2507 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2508 2509 SDValue Gather; 2510 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2511 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2512 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2513 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2514 } else { 2515 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2516 // If only one index is used, we can use a "splat" vrgather. 2517 // TODO: We can splat the most-common index and fix-up any stragglers, if 2518 // that's beneficial. 2519 if (LHSIndexCounts.size() == 1) { 2520 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2521 Gather = 2522 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2523 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2524 } else { 2525 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2526 LHSIndices = 2527 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2528 2529 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2530 TrueMask, VL); 2531 } 2532 } 2533 2534 // If a second vector operand is used by this shuffle, blend it in with an 2535 // additional vrgather. 2536 if (!V2.isUndef()) { 2537 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2538 // If only one index is used, we can use a "splat" vrgather. 2539 // TODO: We can splat the most-common index and fix-up any stragglers, if 2540 // that's beneficial. 2541 if (RHSIndexCounts.size() == 1) { 2542 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2543 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2544 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2545 } else { 2546 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2547 RHSIndices = 2548 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2549 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2550 VL); 2551 } 2552 2553 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2554 SelectMask = 2555 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2556 2557 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2558 Gather, VL); 2559 } 2560 2561 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2562 } 2563 2564 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2565 SDLoc DL, SelectionDAG &DAG, 2566 const RISCVSubtarget &Subtarget) { 2567 if (VT.isScalableVector()) 2568 return DAG.getFPExtendOrRound(Op, DL, VT); 2569 assert(VT.isFixedLengthVector() && 2570 "Unexpected value type for RVV FP extend/round lowering"); 2571 SDValue Mask, VL; 2572 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2573 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2574 ? RISCVISD::FP_EXTEND_VL 2575 : RISCVISD::FP_ROUND_VL; 2576 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2577 } 2578 2579 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2580 // the exponent. 2581 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2582 MVT VT = Op.getSimpleValueType(); 2583 unsigned EltSize = VT.getScalarSizeInBits(); 2584 SDValue Src = Op.getOperand(0); 2585 SDLoc DL(Op); 2586 2587 // We need a FP type that can represent the value. 2588 // TODO: Use f16 for i8 when possible? 2589 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2590 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2591 2592 // Legal types should have been checked in the RISCVTargetLowering 2593 // constructor. 2594 // TODO: Splitting may make sense in some cases. 2595 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2596 "Expected legal float type!"); 2597 2598 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2599 // The trailing zero count is equal to log2 of this single bit value. 2600 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2601 SDValue Neg = 2602 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2603 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2604 } 2605 2606 // We have a legal FP type, convert to it. 2607 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2608 // Bitcast to integer and shift the exponent to the LSB. 2609 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2610 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2611 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2612 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2613 DAG.getConstant(ShiftAmt, DL, IntVT)); 2614 // Truncate back to original type to allow vnsrl. 2615 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2616 // The exponent contains log2 of the value in biased form. 2617 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2618 2619 // For trailing zeros, we just need to subtract the bias. 2620 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2621 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2622 DAG.getConstant(ExponentBias, DL, VT)); 2623 2624 // For leading zeros, we need to remove the bias and convert from log2 to 2625 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2626 unsigned Adjust = ExponentBias + (EltSize - 1); 2627 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2628 } 2629 2630 // While RVV has alignment restrictions, we should always be able to load as a 2631 // legal equivalently-sized byte-typed vector instead. This method is 2632 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2633 // the load is already correctly-aligned, it returns SDValue(). 2634 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2635 SelectionDAG &DAG) const { 2636 auto *Load = cast<LoadSDNode>(Op); 2637 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2638 2639 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2640 Load->getMemoryVT(), 2641 *Load->getMemOperand())) 2642 return SDValue(); 2643 2644 SDLoc DL(Op); 2645 MVT VT = Op.getSimpleValueType(); 2646 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2647 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2648 "Unexpected unaligned RVV load type"); 2649 MVT NewVT = 2650 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2651 assert(NewVT.isValid() && 2652 "Expecting equally-sized RVV vector types to be legal"); 2653 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2654 Load->getPointerInfo(), Load->getOriginalAlign(), 2655 Load->getMemOperand()->getFlags()); 2656 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2657 } 2658 2659 // While RVV has alignment restrictions, we should always be able to store as a 2660 // legal equivalently-sized byte-typed vector instead. This method is 2661 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2662 // returns SDValue() if the store is already correctly aligned. 2663 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2664 SelectionDAG &DAG) const { 2665 auto *Store = cast<StoreSDNode>(Op); 2666 assert(Store && Store->getValue().getValueType().isVector() && 2667 "Expected vector store"); 2668 2669 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2670 Store->getMemoryVT(), 2671 *Store->getMemOperand())) 2672 return SDValue(); 2673 2674 SDLoc DL(Op); 2675 SDValue StoredVal = Store->getValue(); 2676 MVT VT = StoredVal.getSimpleValueType(); 2677 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2678 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2679 "Unexpected unaligned RVV store type"); 2680 MVT NewVT = 2681 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2682 assert(NewVT.isValid() && 2683 "Expecting equally-sized RVV vector types to be legal"); 2684 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2685 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2686 Store->getPointerInfo(), Store->getOriginalAlign(), 2687 Store->getMemOperand()->getFlags()); 2688 } 2689 2690 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2691 SelectionDAG &DAG) const { 2692 switch (Op.getOpcode()) { 2693 default: 2694 report_fatal_error("unimplemented operand"); 2695 case ISD::GlobalAddress: 2696 return lowerGlobalAddress(Op, DAG); 2697 case ISD::BlockAddress: 2698 return lowerBlockAddress(Op, DAG); 2699 case ISD::ConstantPool: 2700 return lowerConstantPool(Op, DAG); 2701 case ISD::JumpTable: 2702 return lowerJumpTable(Op, DAG); 2703 case ISD::GlobalTLSAddress: 2704 return lowerGlobalTLSAddress(Op, DAG); 2705 case ISD::SELECT: 2706 return lowerSELECT(Op, DAG); 2707 case ISD::BRCOND: 2708 return lowerBRCOND(Op, DAG); 2709 case ISD::VASTART: 2710 return lowerVASTART(Op, DAG); 2711 case ISD::FRAMEADDR: 2712 return lowerFRAMEADDR(Op, DAG); 2713 case ISD::RETURNADDR: 2714 return lowerRETURNADDR(Op, DAG); 2715 case ISD::SHL_PARTS: 2716 return lowerShiftLeftParts(Op, DAG); 2717 case ISD::SRA_PARTS: 2718 return lowerShiftRightParts(Op, DAG, true); 2719 case ISD::SRL_PARTS: 2720 return lowerShiftRightParts(Op, DAG, false); 2721 case ISD::BITCAST: { 2722 SDLoc DL(Op); 2723 EVT VT = Op.getValueType(); 2724 SDValue Op0 = Op.getOperand(0); 2725 EVT Op0VT = Op0.getValueType(); 2726 MVT XLenVT = Subtarget.getXLenVT(); 2727 if (VT.isFixedLengthVector()) { 2728 // We can handle fixed length vector bitcasts with a simple replacement 2729 // in isel. 2730 if (Op0VT.isFixedLengthVector()) 2731 return Op; 2732 // When bitcasting from scalar to fixed-length vector, insert the scalar 2733 // into a one-element vector of the result type, and perform a vector 2734 // bitcast. 2735 if (!Op0VT.isVector()) { 2736 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2737 if (!isTypeLegal(BVT)) 2738 return SDValue(); 2739 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2740 DAG.getUNDEF(BVT), Op0, 2741 DAG.getConstant(0, DL, XLenVT))); 2742 } 2743 return SDValue(); 2744 } 2745 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2746 // thus: bitcast the vector to a one-element vector type whose element type 2747 // is the same as the result type, and extract the first element. 2748 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2749 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2750 if (!isTypeLegal(BVT)) 2751 return SDValue(); 2752 SDValue BVec = DAG.getBitcast(BVT, Op0); 2753 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2754 DAG.getConstant(0, DL, XLenVT)); 2755 } 2756 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2757 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2758 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2759 return FPConv; 2760 } 2761 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2762 Subtarget.hasStdExtF()) { 2763 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2764 SDValue FPConv = 2765 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2766 return FPConv; 2767 } 2768 return SDValue(); 2769 } 2770 case ISD::INTRINSIC_WO_CHAIN: 2771 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2772 case ISD::INTRINSIC_W_CHAIN: 2773 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2774 case ISD::INTRINSIC_VOID: 2775 return LowerINTRINSIC_VOID(Op, DAG); 2776 case ISD::BSWAP: 2777 case ISD::BITREVERSE: { 2778 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2779 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2780 MVT VT = Op.getSimpleValueType(); 2781 SDLoc DL(Op); 2782 // Start with the maximum immediate value which is the bitwidth - 1. 2783 unsigned Imm = VT.getSizeInBits() - 1; 2784 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2785 if (Op.getOpcode() == ISD::BSWAP) 2786 Imm &= ~0x7U; 2787 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2788 DAG.getConstant(Imm, DL, VT)); 2789 } 2790 case ISD::FSHL: 2791 case ISD::FSHR: { 2792 MVT VT = Op.getSimpleValueType(); 2793 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2794 SDLoc DL(Op); 2795 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2796 return Op; 2797 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2798 // use log(XLen) bits. Mask the shift amount accordingly. 2799 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2800 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2801 DAG.getConstant(ShAmtWidth, DL, VT)); 2802 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2803 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2804 } 2805 case ISD::TRUNCATE: { 2806 SDLoc DL(Op); 2807 MVT VT = Op.getSimpleValueType(); 2808 // Only custom-lower vector truncates 2809 if (!VT.isVector()) 2810 return Op; 2811 2812 // Truncates to mask types are handled differently 2813 if (VT.getVectorElementType() == MVT::i1) 2814 return lowerVectorMaskTrunc(Op, DAG); 2815 2816 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2817 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2818 // truncate by one power of two at a time. 2819 MVT DstEltVT = VT.getVectorElementType(); 2820 2821 SDValue Src = Op.getOperand(0); 2822 MVT SrcVT = Src.getSimpleValueType(); 2823 MVT SrcEltVT = SrcVT.getVectorElementType(); 2824 2825 assert(DstEltVT.bitsLT(SrcEltVT) && 2826 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2827 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2828 "Unexpected vector truncate lowering"); 2829 2830 MVT ContainerVT = SrcVT; 2831 if (SrcVT.isFixedLengthVector()) { 2832 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2833 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2834 } 2835 2836 SDValue Result = Src; 2837 SDValue Mask, VL; 2838 std::tie(Mask, VL) = 2839 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2840 LLVMContext &Context = *DAG.getContext(); 2841 const ElementCount Count = ContainerVT.getVectorElementCount(); 2842 do { 2843 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2844 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2845 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2846 Mask, VL); 2847 } while (SrcEltVT != DstEltVT); 2848 2849 if (SrcVT.isFixedLengthVector()) 2850 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2851 2852 return Result; 2853 } 2854 case ISD::ANY_EXTEND: 2855 case ISD::ZERO_EXTEND: 2856 if (Op.getOperand(0).getValueType().isVector() && 2857 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2858 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2859 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2860 case ISD::SIGN_EXTEND: 2861 if (Op.getOperand(0).getValueType().isVector() && 2862 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2863 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2864 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2865 case ISD::SPLAT_VECTOR_PARTS: 2866 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2867 case ISD::INSERT_VECTOR_ELT: 2868 return lowerINSERT_VECTOR_ELT(Op, DAG); 2869 case ISD::EXTRACT_VECTOR_ELT: 2870 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2871 case ISD::VSCALE: { 2872 MVT VT = Op.getSimpleValueType(); 2873 SDLoc DL(Op); 2874 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2875 // We define our scalable vector types for lmul=1 to use a 64 bit known 2876 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2877 // vscale as VLENB / 8. 2878 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 2879 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2880 // We assume VLENB is a multiple of 8. We manually choose the best shift 2881 // here because SimplifyDemandedBits isn't always able to simplify it. 2882 uint64_t Val = Op.getConstantOperandVal(0); 2883 if (isPowerOf2_64(Val)) { 2884 uint64_t Log2 = Log2_64(Val); 2885 if (Log2 < 3) 2886 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2887 DAG.getConstant(3 - Log2, DL, VT)); 2888 if (Log2 > 3) 2889 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2890 DAG.getConstant(Log2 - 3, DL, VT)); 2891 return VLENB; 2892 } 2893 // If the multiplier is a multiple of 8, scale it down to avoid needing 2894 // to shift the VLENB value. 2895 if ((Val % 8) == 0) 2896 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2897 DAG.getConstant(Val / 8, DL, VT)); 2898 } 2899 2900 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2901 DAG.getConstant(3, DL, VT)); 2902 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2903 } 2904 case ISD::FPOWI: { 2905 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 2906 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 2907 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 2908 Op.getOperand(1).getValueType() == MVT::i32) { 2909 SDLoc DL(Op); 2910 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 2911 SDValue Powi = 2912 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 2913 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 2914 DAG.getIntPtrConstant(0, DL)); 2915 } 2916 return SDValue(); 2917 } 2918 case ISD::FP_EXTEND: { 2919 // RVV can only do fp_extend to types double the size as the source. We 2920 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2921 // via f32. 2922 SDLoc DL(Op); 2923 MVT VT = Op.getSimpleValueType(); 2924 SDValue Src = Op.getOperand(0); 2925 MVT SrcVT = Src.getSimpleValueType(); 2926 2927 // Prepare any fixed-length vector operands. 2928 MVT ContainerVT = VT; 2929 if (SrcVT.isFixedLengthVector()) { 2930 ContainerVT = getContainerForFixedLengthVector(VT); 2931 MVT SrcContainerVT = 2932 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2933 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2934 } 2935 2936 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2937 SrcVT.getVectorElementType() != MVT::f16) { 2938 // For scalable vectors, we only need to close the gap between 2939 // vXf16->vXf64. 2940 if (!VT.isFixedLengthVector()) 2941 return Op; 2942 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2943 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2944 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2945 } 2946 2947 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2948 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2949 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2950 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2951 2952 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2953 DL, DAG, Subtarget); 2954 if (VT.isFixedLengthVector()) 2955 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2956 return Extend; 2957 } 2958 case ISD::FP_ROUND: { 2959 // RVV can only do fp_round to types half the size as the source. We 2960 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2961 // conversion instruction. 2962 SDLoc DL(Op); 2963 MVT VT = Op.getSimpleValueType(); 2964 SDValue Src = Op.getOperand(0); 2965 MVT SrcVT = Src.getSimpleValueType(); 2966 2967 // Prepare any fixed-length vector operands. 2968 MVT ContainerVT = VT; 2969 if (VT.isFixedLengthVector()) { 2970 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2971 ContainerVT = 2972 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2973 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2974 } 2975 2976 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2977 SrcVT.getVectorElementType() != MVT::f64) { 2978 // For scalable vectors, we only need to close the gap between 2979 // vXf64<->vXf16. 2980 if (!VT.isFixedLengthVector()) 2981 return Op; 2982 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2983 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2984 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2985 } 2986 2987 SDValue Mask, VL; 2988 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2989 2990 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2991 SDValue IntermediateRound = 2992 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2993 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2994 DL, DAG, Subtarget); 2995 2996 if (VT.isFixedLengthVector()) 2997 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2998 return Round; 2999 } 3000 case ISD::FP_TO_SINT: 3001 case ISD::FP_TO_UINT: 3002 case ISD::SINT_TO_FP: 3003 case ISD::UINT_TO_FP: { 3004 // RVV can only do fp<->int conversions to types half/double the size as 3005 // the source. We custom-lower any conversions that do two hops into 3006 // sequences. 3007 MVT VT = Op.getSimpleValueType(); 3008 if (!VT.isVector()) 3009 return Op; 3010 SDLoc DL(Op); 3011 SDValue Src = Op.getOperand(0); 3012 MVT EltVT = VT.getVectorElementType(); 3013 MVT SrcVT = Src.getSimpleValueType(); 3014 MVT SrcEltVT = SrcVT.getVectorElementType(); 3015 unsigned EltSize = EltVT.getSizeInBits(); 3016 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3017 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3018 "Unexpected vector element types"); 3019 3020 bool IsInt2FP = SrcEltVT.isInteger(); 3021 // Widening conversions 3022 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3023 if (IsInt2FP) { 3024 // Do a regular integer sign/zero extension then convert to float. 3025 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3026 VT.getVectorElementCount()); 3027 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3028 ? ISD::ZERO_EXTEND 3029 : ISD::SIGN_EXTEND; 3030 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3031 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3032 } 3033 // FP2Int 3034 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3035 // Do one doubling fp_extend then complete the operation by converting 3036 // to int. 3037 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3038 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3039 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3040 } 3041 3042 // Narrowing conversions 3043 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3044 if (IsInt2FP) { 3045 // One narrowing int_to_fp, then an fp_round. 3046 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3047 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3048 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3049 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3050 } 3051 // FP2Int 3052 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3053 // representable by the integer, the result is poison. 3054 MVT IVecVT = 3055 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3056 VT.getVectorElementCount()); 3057 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3058 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3059 } 3060 3061 // Scalable vectors can exit here. Patterns will handle equally-sized 3062 // conversions halving/doubling ones. 3063 if (!VT.isFixedLengthVector()) 3064 return Op; 3065 3066 // For fixed-length vectors we lower to a custom "VL" node. 3067 unsigned RVVOpc = 0; 3068 switch (Op.getOpcode()) { 3069 default: 3070 llvm_unreachable("Impossible opcode"); 3071 case ISD::FP_TO_SINT: 3072 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3073 break; 3074 case ISD::FP_TO_UINT: 3075 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3076 break; 3077 case ISD::SINT_TO_FP: 3078 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3079 break; 3080 case ISD::UINT_TO_FP: 3081 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3082 break; 3083 } 3084 3085 MVT ContainerVT, SrcContainerVT; 3086 // Derive the reference container type from the larger vector type. 3087 if (SrcEltSize > EltSize) { 3088 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3089 ContainerVT = 3090 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3091 } else { 3092 ContainerVT = getContainerForFixedLengthVector(VT); 3093 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3094 } 3095 3096 SDValue Mask, VL; 3097 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3098 3099 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3100 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3101 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3102 } 3103 case ISD::FP_TO_SINT_SAT: 3104 case ISD::FP_TO_UINT_SAT: 3105 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3106 case ISD::FTRUNC: 3107 case ISD::FCEIL: 3108 case ISD::FFLOOR: 3109 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3110 case ISD::VECREDUCE_ADD: 3111 case ISD::VECREDUCE_UMAX: 3112 case ISD::VECREDUCE_SMAX: 3113 case ISD::VECREDUCE_UMIN: 3114 case ISD::VECREDUCE_SMIN: 3115 return lowerVECREDUCE(Op, DAG); 3116 case ISD::VECREDUCE_AND: 3117 case ISD::VECREDUCE_OR: 3118 case ISD::VECREDUCE_XOR: 3119 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3120 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3121 return lowerVECREDUCE(Op, DAG); 3122 case ISD::VECREDUCE_FADD: 3123 case ISD::VECREDUCE_SEQ_FADD: 3124 case ISD::VECREDUCE_FMIN: 3125 case ISD::VECREDUCE_FMAX: 3126 return lowerFPVECREDUCE(Op, DAG); 3127 case ISD::VP_REDUCE_ADD: 3128 case ISD::VP_REDUCE_UMAX: 3129 case ISD::VP_REDUCE_SMAX: 3130 case ISD::VP_REDUCE_UMIN: 3131 case ISD::VP_REDUCE_SMIN: 3132 case ISD::VP_REDUCE_FADD: 3133 case ISD::VP_REDUCE_SEQ_FADD: 3134 case ISD::VP_REDUCE_FMIN: 3135 case ISD::VP_REDUCE_FMAX: 3136 return lowerVPREDUCE(Op, DAG); 3137 case ISD::VP_REDUCE_AND: 3138 case ISD::VP_REDUCE_OR: 3139 case ISD::VP_REDUCE_XOR: 3140 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3141 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3142 return lowerVPREDUCE(Op, DAG); 3143 case ISD::INSERT_SUBVECTOR: 3144 return lowerINSERT_SUBVECTOR(Op, DAG); 3145 case ISD::EXTRACT_SUBVECTOR: 3146 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3147 case ISD::STEP_VECTOR: 3148 return lowerSTEP_VECTOR(Op, DAG); 3149 case ISD::VECTOR_REVERSE: 3150 return lowerVECTOR_REVERSE(Op, DAG); 3151 case ISD::BUILD_VECTOR: 3152 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3153 case ISD::SPLAT_VECTOR: 3154 if (Op.getValueType().getVectorElementType() == MVT::i1) 3155 return lowerVectorMaskSplat(Op, DAG); 3156 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3157 case ISD::VECTOR_SHUFFLE: 3158 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3159 case ISD::CONCAT_VECTORS: { 3160 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3161 // better than going through the stack, as the default expansion does. 3162 SDLoc DL(Op); 3163 MVT VT = Op.getSimpleValueType(); 3164 unsigned NumOpElts = 3165 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3166 SDValue Vec = DAG.getUNDEF(VT); 3167 for (const auto &OpIdx : enumerate(Op->ops())) { 3168 SDValue SubVec = OpIdx.value(); 3169 // Don't insert undef subvectors. 3170 if (SubVec.isUndef()) 3171 continue; 3172 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3173 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3174 } 3175 return Vec; 3176 } 3177 case ISD::LOAD: 3178 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3179 return V; 3180 if (Op.getValueType().isFixedLengthVector()) 3181 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3182 return Op; 3183 case ISD::STORE: 3184 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3185 return V; 3186 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3187 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3188 return Op; 3189 case ISD::MLOAD: 3190 case ISD::VP_LOAD: 3191 return lowerMaskedLoad(Op, DAG); 3192 case ISD::MSTORE: 3193 case ISD::VP_STORE: 3194 return lowerMaskedStore(Op, DAG); 3195 case ISD::SETCC: 3196 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3197 case ISD::ADD: 3198 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3199 case ISD::SUB: 3200 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3201 case ISD::MUL: 3202 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3203 case ISD::MULHS: 3204 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3205 case ISD::MULHU: 3206 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3207 case ISD::AND: 3208 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3209 RISCVISD::AND_VL); 3210 case ISD::OR: 3211 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3212 RISCVISD::OR_VL); 3213 case ISD::XOR: 3214 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3215 RISCVISD::XOR_VL); 3216 case ISD::SDIV: 3217 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3218 case ISD::SREM: 3219 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3220 case ISD::UDIV: 3221 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3222 case ISD::UREM: 3223 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3224 case ISD::SHL: 3225 case ISD::SRA: 3226 case ISD::SRL: 3227 if (Op.getSimpleValueType().isFixedLengthVector()) 3228 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3229 // This can be called for an i32 shift amount that needs to be promoted. 3230 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3231 "Unexpected custom legalisation"); 3232 return SDValue(); 3233 case ISD::SADDSAT: 3234 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3235 case ISD::UADDSAT: 3236 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3237 case ISD::SSUBSAT: 3238 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3239 case ISD::USUBSAT: 3240 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3241 case ISD::FADD: 3242 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3243 case ISD::FSUB: 3244 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3245 case ISD::FMUL: 3246 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3247 case ISD::FDIV: 3248 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3249 case ISD::FNEG: 3250 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3251 case ISD::FABS: 3252 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3253 case ISD::FSQRT: 3254 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3255 case ISD::FMA: 3256 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3257 case ISD::SMIN: 3258 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3259 case ISD::SMAX: 3260 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3261 case ISD::UMIN: 3262 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3263 case ISD::UMAX: 3264 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3265 case ISD::FMINNUM: 3266 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3267 case ISD::FMAXNUM: 3268 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3269 case ISD::ABS: 3270 return lowerABS(Op, DAG); 3271 case ISD::CTLZ_ZERO_UNDEF: 3272 case ISD::CTTZ_ZERO_UNDEF: 3273 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3274 case ISD::VSELECT: 3275 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3276 case ISD::FCOPYSIGN: 3277 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3278 case ISD::MGATHER: 3279 case ISD::VP_GATHER: 3280 return lowerMaskedGather(Op, DAG); 3281 case ISD::MSCATTER: 3282 case ISD::VP_SCATTER: 3283 return lowerMaskedScatter(Op, DAG); 3284 case ISD::FLT_ROUNDS_: 3285 return lowerGET_ROUNDING(Op, DAG); 3286 case ISD::SET_ROUNDING: 3287 return lowerSET_ROUNDING(Op, DAG); 3288 case ISD::VP_SELECT: 3289 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3290 case ISD::VP_ADD: 3291 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3292 case ISD::VP_SUB: 3293 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3294 case ISD::VP_MUL: 3295 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3296 case ISD::VP_SDIV: 3297 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3298 case ISD::VP_UDIV: 3299 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3300 case ISD::VP_SREM: 3301 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3302 case ISD::VP_UREM: 3303 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3304 case ISD::VP_AND: 3305 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3306 case ISD::VP_OR: 3307 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3308 case ISD::VP_XOR: 3309 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3310 case ISD::VP_ASHR: 3311 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3312 case ISD::VP_LSHR: 3313 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3314 case ISD::VP_SHL: 3315 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3316 case ISD::VP_FADD: 3317 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3318 case ISD::VP_FSUB: 3319 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3320 case ISD::VP_FMUL: 3321 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3322 case ISD::VP_FDIV: 3323 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3324 } 3325 } 3326 3327 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3328 SelectionDAG &DAG, unsigned Flags) { 3329 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3330 } 3331 3332 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3333 SelectionDAG &DAG, unsigned Flags) { 3334 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3335 Flags); 3336 } 3337 3338 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3339 SelectionDAG &DAG, unsigned Flags) { 3340 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3341 N->getOffset(), Flags); 3342 } 3343 3344 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3345 SelectionDAG &DAG, unsigned Flags) { 3346 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3347 } 3348 3349 template <class NodeTy> 3350 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3351 bool IsLocal) const { 3352 SDLoc DL(N); 3353 EVT Ty = getPointerTy(DAG.getDataLayout()); 3354 3355 if (isPositionIndependent()) { 3356 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3357 if (IsLocal) 3358 // Use PC-relative addressing to access the symbol. This generates the 3359 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3360 // %pcrel_lo(auipc)). 3361 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3362 3363 // Use PC-relative addressing to access the GOT for this symbol, then load 3364 // the address from the GOT. This generates the pattern (PseudoLA sym), 3365 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3366 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3367 } 3368 3369 switch (getTargetMachine().getCodeModel()) { 3370 default: 3371 report_fatal_error("Unsupported code model for lowering"); 3372 case CodeModel::Small: { 3373 // Generate a sequence for accessing addresses within the first 2 GiB of 3374 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3375 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3376 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3377 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3378 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3379 } 3380 case CodeModel::Medium: { 3381 // Generate a sequence for accessing addresses within any 2GiB range within 3382 // the address space. This generates the pattern (PseudoLLA sym), which 3383 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3384 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3385 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3386 } 3387 } 3388 } 3389 3390 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3391 SelectionDAG &DAG) const { 3392 SDLoc DL(Op); 3393 EVT Ty = Op.getValueType(); 3394 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3395 int64_t Offset = N->getOffset(); 3396 MVT XLenVT = Subtarget.getXLenVT(); 3397 3398 const GlobalValue *GV = N->getGlobal(); 3399 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3400 SDValue Addr = getAddr(N, DAG, IsLocal); 3401 3402 // In order to maximise the opportunity for common subexpression elimination, 3403 // emit a separate ADD node for the global address offset instead of folding 3404 // it in the global address node. Later peephole optimisations may choose to 3405 // fold it back in when profitable. 3406 if (Offset != 0) 3407 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3408 DAG.getConstant(Offset, DL, XLenVT)); 3409 return Addr; 3410 } 3411 3412 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3413 SelectionDAG &DAG) const { 3414 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3415 3416 return getAddr(N, DAG); 3417 } 3418 3419 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3420 SelectionDAG &DAG) const { 3421 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3422 3423 return getAddr(N, DAG); 3424 } 3425 3426 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3427 SelectionDAG &DAG) const { 3428 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3429 3430 return getAddr(N, DAG); 3431 } 3432 3433 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3434 SelectionDAG &DAG, 3435 bool UseGOT) const { 3436 SDLoc DL(N); 3437 EVT Ty = getPointerTy(DAG.getDataLayout()); 3438 const GlobalValue *GV = N->getGlobal(); 3439 MVT XLenVT = Subtarget.getXLenVT(); 3440 3441 if (UseGOT) { 3442 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3443 // load the address from the GOT and add the thread pointer. This generates 3444 // the pattern (PseudoLA_TLS_IE sym), which expands to 3445 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3446 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3447 SDValue Load = 3448 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3449 3450 // Add the thread pointer. 3451 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3452 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3453 } 3454 3455 // Generate a sequence for accessing the address relative to the thread 3456 // pointer, with the appropriate adjustment for the thread pointer offset. 3457 // This generates the pattern 3458 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3459 SDValue AddrHi = 3460 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3461 SDValue AddrAdd = 3462 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3463 SDValue AddrLo = 3464 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3465 3466 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3467 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3468 SDValue MNAdd = SDValue( 3469 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3470 0); 3471 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3472 } 3473 3474 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3475 SelectionDAG &DAG) const { 3476 SDLoc DL(N); 3477 EVT Ty = getPointerTy(DAG.getDataLayout()); 3478 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3479 const GlobalValue *GV = N->getGlobal(); 3480 3481 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3482 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3483 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3484 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3485 SDValue Load = 3486 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3487 3488 // Prepare argument list to generate call. 3489 ArgListTy Args; 3490 ArgListEntry Entry; 3491 Entry.Node = Load; 3492 Entry.Ty = CallTy; 3493 Args.push_back(Entry); 3494 3495 // Setup call to __tls_get_addr. 3496 TargetLowering::CallLoweringInfo CLI(DAG); 3497 CLI.setDebugLoc(DL) 3498 .setChain(DAG.getEntryNode()) 3499 .setLibCallee(CallingConv::C, CallTy, 3500 DAG.getExternalSymbol("__tls_get_addr", Ty), 3501 std::move(Args)); 3502 3503 return LowerCallTo(CLI).first; 3504 } 3505 3506 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3507 SelectionDAG &DAG) const { 3508 SDLoc DL(Op); 3509 EVT Ty = Op.getValueType(); 3510 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3511 int64_t Offset = N->getOffset(); 3512 MVT XLenVT = Subtarget.getXLenVT(); 3513 3514 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3515 3516 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3517 CallingConv::GHC) 3518 report_fatal_error("In GHC calling convention TLS is not supported"); 3519 3520 SDValue Addr; 3521 switch (Model) { 3522 case TLSModel::LocalExec: 3523 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3524 break; 3525 case TLSModel::InitialExec: 3526 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3527 break; 3528 case TLSModel::LocalDynamic: 3529 case TLSModel::GeneralDynamic: 3530 Addr = getDynamicTLSAddr(N, DAG); 3531 break; 3532 } 3533 3534 // In order to maximise the opportunity for common subexpression elimination, 3535 // emit a separate ADD node for the global address offset instead of folding 3536 // it in the global address node. Later peephole optimisations may choose to 3537 // fold it back in when profitable. 3538 if (Offset != 0) 3539 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3540 DAG.getConstant(Offset, DL, XLenVT)); 3541 return Addr; 3542 } 3543 3544 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3545 SDValue CondV = Op.getOperand(0); 3546 SDValue TrueV = Op.getOperand(1); 3547 SDValue FalseV = Op.getOperand(2); 3548 SDLoc DL(Op); 3549 MVT VT = Op.getSimpleValueType(); 3550 MVT XLenVT = Subtarget.getXLenVT(); 3551 3552 // Lower vector SELECTs to VSELECTs by splatting the condition. 3553 if (VT.isVector()) { 3554 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3555 SDValue CondSplat = VT.isScalableVector() 3556 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3557 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3558 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3559 } 3560 3561 // If the result type is XLenVT and CondV is the output of a SETCC node 3562 // which also operated on XLenVT inputs, then merge the SETCC node into the 3563 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3564 // compare+branch instructions. i.e.: 3565 // (select (setcc lhs, rhs, cc), truev, falsev) 3566 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3567 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3568 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3569 SDValue LHS = CondV.getOperand(0); 3570 SDValue RHS = CondV.getOperand(1); 3571 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3572 ISD::CondCode CCVal = CC->get(); 3573 3574 // Special case for a select of 2 constants that have a diffence of 1. 3575 // Normally this is done by DAGCombine, but if the select is introduced by 3576 // type legalization or op legalization, we miss it. Restricting to SETLT 3577 // case for now because that is what signed saturating add/sub need. 3578 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3579 // but we would probably want to swap the true/false values if the condition 3580 // is SETGE/SETLE to avoid an XORI. 3581 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3582 CCVal == ISD::SETLT) { 3583 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3584 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3585 if (TrueVal - 1 == FalseVal) 3586 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3587 if (TrueVal + 1 == FalseVal) 3588 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3589 } 3590 3591 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3592 3593 SDValue TargetCC = DAG.getCondCode(CCVal); 3594 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3595 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3596 } 3597 3598 // Otherwise: 3599 // (select condv, truev, falsev) 3600 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3601 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3602 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3603 3604 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3605 3606 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3607 } 3608 3609 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3610 SDValue CondV = Op.getOperand(1); 3611 SDLoc DL(Op); 3612 MVT XLenVT = Subtarget.getXLenVT(); 3613 3614 if (CondV.getOpcode() == ISD::SETCC && 3615 CondV.getOperand(0).getValueType() == XLenVT) { 3616 SDValue LHS = CondV.getOperand(0); 3617 SDValue RHS = CondV.getOperand(1); 3618 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3619 3620 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3621 3622 SDValue TargetCC = DAG.getCondCode(CCVal); 3623 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3624 LHS, RHS, TargetCC, Op.getOperand(2)); 3625 } 3626 3627 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3628 CondV, DAG.getConstant(0, DL, XLenVT), 3629 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3630 } 3631 3632 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3633 MachineFunction &MF = DAG.getMachineFunction(); 3634 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3635 3636 SDLoc DL(Op); 3637 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3638 getPointerTy(MF.getDataLayout())); 3639 3640 // vastart just stores the address of the VarArgsFrameIndex slot into the 3641 // memory location argument. 3642 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3643 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3644 MachinePointerInfo(SV)); 3645 } 3646 3647 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3648 SelectionDAG &DAG) const { 3649 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3650 MachineFunction &MF = DAG.getMachineFunction(); 3651 MachineFrameInfo &MFI = MF.getFrameInfo(); 3652 MFI.setFrameAddressIsTaken(true); 3653 Register FrameReg = RI.getFrameRegister(MF); 3654 int XLenInBytes = Subtarget.getXLen() / 8; 3655 3656 EVT VT = Op.getValueType(); 3657 SDLoc DL(Op); 3658 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3659 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3660 while (Depth--) { 3661 int Offset = -(XLenInBytes * 2); 3662 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3663 DAG.getIntPtrConstant(Offset, DL)); 3664 FrameAddr = 3665 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3666 } 3667 return FrameAddr; 3668 } 3669 3670 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3671 SelectionDAG &DAG) const { 3672 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3673 MachineFunction &MF = DAG.getMachineFunction(); 3674 MachineFrameInfo &MFI = MF.getFrameInfo(); 3675 MFI.setReturnAddressIsTaken(true); 3676 MVT XLenVT = Subtarget.getXLenVT(); 3677 int XLenInBytes = Subtarget.getXLen() / 8; 3678 3679 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3680 return SDValue(); 3681 3682 EVT VT = Op.getValueType(); 3683 SDLoc DL(Op); 3684 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3685 if (Depth) { 3686 int Off = -XLenInBytes; 3687 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3688 SDValue Offset = DAG.getConstant(Off, DL, VT); 3689 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3690 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3691 MachinePointerInfo()); 3692 } 3693 3694 // Return the value of the return address register, marking it an implicit 3695 // live-in. 3696 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3697 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3698 } 3699 3700 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3701 SelectionDAG &DAG) const { 3702 SDLoc DL(Op); 3703 SDValue Lo = Op.getOperand(0); 3704 SDValue Hi = Op.getOperand(1); 3705 SDValue Shamt = Op.getOperand(2); 3706 EVT VT = Lo.getValueType(); 3707 3708 // if Shamt-XLEN < 0: // Shamt < XLEN 3709 // Lo = Lo << Shamt 3710 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3711 // else: 3712 // Lo = 0 3713 // Hi = Lo << (Shamt-XLEN) 3714 3715 SDValue Zero = DAG.getConstant(0, DL, VT); 3716 SDValue One = DAG.getConstant(1, DL, VT); 3717 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3718 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3719 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3720 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3721 3722 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3723 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3724 SDValue ShiftRightLo = 3725 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3726 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3727 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3728 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3729 3730 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3731 3732 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3733 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3734 3735 SDValue Parts[2] = {Lo, Hi}; 3736 return DAG.getMergeValues(Parts, DL); 3737 } 3738 3739 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3740 bool IsSRA) const { 3741 SDLoc DL(Op); 3742 SDValue Lo = Op.getOperand(0); 3743 SDValue Hi = Op.getOperand(1); 3744 SDValue Shamt = Op.getOperand(2); 3745 EVT VT = Lo.getValueType(); 3746 3747 // SRA expansion: 3748 // if Shamt-XLEN < 0: // Shamt < XLEN 3749 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3750 // Hi = Hi >>s Shamt 3751 // else: 3752 // Lo = Hi >>s (Shamt-XLEN); 3753 // Hi = Hi >>s (XLEN-1) 3754 // 3755 // SRL expansion: 3756 // if Shamt-XLEN < 0: // Shamt < XLEN 3757 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3758 // Hi = Hi >>u Shamt 3759 // else: 3760 // Lo = Hi >>u (Shamt-XLEN); 3761 // Hi = 0; 3762 3763 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3764 3765 SDValue Zero = DAG.getConstant(0, DL, VT); 3766 SDValue One = DAG.getConstant(1, DL, VT); 3767 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3768 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3769 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3770 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3771 3772 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3773 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3774 SDValue ShiftLeftHi = 3775 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3776 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3777 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3778 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3779 SDValue HiFalse = 3780 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3781 3782 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3783 3784 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3785 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3786 3787 SDValue Parts[2] = {Lo, Hi}; 3788 return DAG.getMergeValues(Parts, DL); 3789 } 3790 3791 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3792 // legal equivalently-sized i8 type, so we can use that as a go-between. 3793 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3794 SelectionDAG &DAG) const { 3795 SDLoc DL(Op); 3796 MVT VT = Op.getSimpleValueType(); 3797 SDValue SplatVal = Op.getOperand(0); 3798 // All-zeros or all-ones splats are handled specially. 3799 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3800 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3801 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3802 } 3803 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3804 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3805 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3806 } 3807 MVT XLenVT = Subtarget.getXLenVT(); 3808 assert(SplatVal.getValueType() == XLenVT && 3809 "Unexpected type for i1 splat value"); 3810 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3811 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3812 DAG.getConstant(1, DL, XLenVT)); 3813 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3814 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3815 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3816 } 3817 3818 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3819 // illegal (currently only vXi64 RV32). 3820 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3821 // them to SPLAT_VECTOR_I64 3822 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3823 SelectionDAG &DAG) const { 3824 SDLoc DL(Op); 3825 MVT VecVT = Op.getSimpleValueType(); 3826 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3827 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3828 3829 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3830 SDValue Lo = Op.getOperand(0); 3831 SDValue Hi = Op.getOperand(1); 3832 3833 if (VecVT.isFixedLengthVector()) { 3834 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3835 SDLoc DL(Op); 3836 SDValue Mask, VL; 3837 std::tie(Mask, VL) = 3838 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3839 3840 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3841 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3842 } 3843 3844 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3845 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3846 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3847 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3848 // node in order to try and match RVV vector/scalar instructions. 3849 if ((LoC >> 31) == HiC) 3850 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3851 } 3852 3853 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3854 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3855 isa<ConstantSDNode>(Hi.getOperand(1)) && 3856 Hi.getConstantOperandVal(1) == 31) 3857 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3858 3859 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3860 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3861 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3862 } 3863 3864 // Custom-lower extensions from mask vectors by using a vselect either with 1 3865 // for zero/any-extension or -1 for sign-extension: 3866 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3867 // Note that any-extension is lowered identically to zero-extension. 3868 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3869 int64_t ExtTrueVal) const { 3870 SDLoc DL(Op); 3871 MVT VecVT = Op.getSimpleValueType(); 3872 SDValue Src = Op.getOperand(0); 3873 // Only custom-lower extensions from mask types 3874 assert(Src.getValueType().isVector() && 3875 Src.getValueType().getVectorElementType() == MVT::i1); 3876 3877 MVT XLenVT = Subtarget.getXLenVT(); 3878 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3879 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3880 3881 if (VecVT.isScalableVector()) { 3882 // Be careful not to introduce illegal scalar types at this stage, and be 3883 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3884 // illegal and must be expanded. Since we know that the constants are 3885 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3886 bool IsRV32E64 = 3887 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3888 3889 if (!IsRV32E64) { 3890 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3891 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3892 } else { 3893 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3894 SplatTrueVal = 3895 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3896 } 3897 3898 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3899 } 3900 3901 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3902 MVT I1ContainerVT = 3903 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3904 3905 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3906 3907 SDValue Mask, VL; 3908 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3909 3910 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3911 SplatTrueVal = 3912 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3913 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3914 SplatTrueVal, SplatZero, VL); 3915 3916 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3917 } 3918 3919 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3920 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3921 MVT ExtVT = Op.getSimpleValueType(); 3922 // Only custom-lower extensions from fixed-length vector types. 3923 if (!ExtVT.isFixedLengthVector()) 3924 return Op; 3925 MVT VT = Op.getOperand(0).getSimpleValueType(); 3926 // Grab the canonical container type for the extended type. Infer the smaller 3927 // type from that to ensure the same number of vector elements, as we know 3928 // the LMUL will be sufficient to hold the smaller type. 3929 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3930 // Get the extended container type manually to ensure the same number of 3931 // vector elements between source and dest. 3932 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3933 ContainerExtVT.getVectorElementCount()); 3934 3935 SDValue Op1 = 3936 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3937 3938 SDLoc DL(Op); 3939 SDValue Mask, VL; 3940 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3941 3942 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3943 3944 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3945 } 3946 3947 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3948 // setcc operation: 3949 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3950 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3951 SelectionDAG &DAG) const { 3952 SDLoc DL(Op); 3953 EVT MaskVT = Op.getValueType(); 3954 // Only expect to custom-lower truncations to mask types 3955 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3956 "Unexpected type for vector mask lowering"); 3957 SDValue Src = Op.getOperand(0); 3958 MVT VecVT = Src.getSimpleValueType(); 3959 3960 // If this is a fixed vector, we need to convert it to a scalable vector. 3961 MVT ContainerVT = VecVT; 3962 if (VecVT.isFixedLengthVector()) { 3963 ContainerVT = getContainerForFixedLengthVector(VecVT); 3964 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3965 } 3966 3967 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3968 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3969 3970 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3971 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3972 3973 if (VecVT.isScalableVector()) { 3974 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3975 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3976 } 3977 3978 SDValue Mask, VL; 3979 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3980 3981 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3982 SDValue Trunc = 3983 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3984 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3985 DAG.getCondCode(ISD::SETNE), Mask, VL); 3986 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3987 } 3988 3989 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3990 // first position of a vector, and that vector is slid up to the insert index. 3991 // By limiting the active vector length to index+1 and merging with the 3992 // original vector (with an undisturbed tail policy for elements >= VL), we 3993 // achieve the desired result of leaving all elements untouched except the one 3994 // at VL-1, which is replaced with the desired value. 3995 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3996 SelectionDAG &DAG) const { 3997 SDLoc DL(Op); 3998 MVT VecVT = Op.getSimpleValueType(); 3999 SDValue Vec = Op.getOperand(0); 4000 SDValue Val = Op.getOperand(1); 4001 SDValue Idx = Op.getOperand(2); 4002 4003 if (VecVT.getVectorElementType() == MVT::i1) { 4004 // FIXME: For now we just promote to an i8 vector and insert into that, 4005 // but this is probably not optimal. 4006 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4007 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4008 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4009 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4010 } 4011 4012 MVT ContainerVT = VecVT; 4013 // If the operand is a fixed-length vector, convert to a scalable one. 4014 if (VecVT.isFixedLengthVector()) { 4015 ContainerVT = getContainerForFixedLengthVector(VecVT); 4016 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4017 } 4018 4019 MVT XLenVT = Subtarget.getXLenVT(); 4020 4021 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4022 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4023 // Even i64-element vectors on RV32 can be lowered without scalar 4024 // legalization if the most-significant 32 bits of the value are not affected 4025 // by the sign-extension of the lower 32 bits. 4026 // TODO: We could also catch sign extensions of a 32-bit value. 4027 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4028 const auto *CVal = cast<ConstantSDNode>(Val); 4029 if (isInt<32>(CVal->getSExtValue())) { 4030 IsLegalInsert = true; 4031 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4032 } 4033 } 4034 4035 SDValue Mask, VL; 4036 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4037 4038 SDValue ValInVec; 4039 4040 if (IsLegalInsert) { 4041 unsigned Opc = 4042 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4043 if (isNullConstant(Idx)) { 4044 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4045 if (!VecVT.isFixedLengthVector()) 4046 return Vec; 4047 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4048 } 4049 ValInVec = 4050 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4051 } else { 4052 // On RV32, i64-element vectors must be specially handled to place the 4053 // value at element 0, by using two vslide1up instructions in sequence on 4054 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4055 // this. 4056 SDValue One = DAG.getConstant(1, DL, XLenVT); 4057 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4058 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4059 MVT I32ContainerVT = 4060 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4061 SDValue I32Mask = 4062 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4063 // Limit the active VL to two. 4064 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4065 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4066 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4067 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 4068 InsertI64VL); 4069 // First slide in the hi value, then the lo in underneath it. 4070 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4071 ValHi, I32Mask, InsertI64VL); 4072 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4073 ValLo, I32Mask, InsertI64VL); 4074 // Bitcast back to the right container type. 4075 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4076 } 4077 4078 // Now that the value is in a vector, slide it into position. 4079 SDValue InsertVL = 4080 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4081 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4082 ValInVec, Idx, Mask, InsertVL); 4083 if (!VecVT.isFixedLengthVector()) 4084 return Slideup; 4085 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4086 } 4087 4088 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4089 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4090 // types this is done using VMV_X_S to allow us to glean information about the 4091 // sign bits of the result. 4092 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4093 SelectionDAG &DAG) const { 4094 SDLoc DL(Op); 4095 SDValue Idx = Op.getOperand(1); 4096 SDValue Vec = Op.getOperand(0); 4097 EVT EltVT = Op.getValueType(); 4098 MVT VecVT = Vec.getSimpleValueType(); 4099 MVT XLenVT = Subtarget.getXLenVT(); 4100 4101 if (VecVT.getVectorElementType() == MVT::i1) { 4102 // FIXME: For now we just promote to an i8 vector and extract from that, 4103 // but this is probably not optimal. 4104 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4105 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4106 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4107 } 4108 4109 // If this is a fixed vector, we need to convert it to a scalable vector. 4110 MVT ContainerVT = VecVT; 4111 if (VecVT.isFixedLengthVector()) { 4112 ContainerVT = getContainerForFixedLengthVector(VecVT); 4113 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4114 } 4115 4116 // If the index is 0, the vector is already in the right position. 4117 if (!isNullConstant(Idx)) { 4118 // Use a VL of 1 to avoid processing more elements than we need. 4119 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4120 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4121 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4122 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4123 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4124 } 4125 4126 if (!EltVT.isInteger()) { 4127 // Floating-point extracts are handled in TableGen. 4128 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4129 DAG.getConstant(0, DL, XLenVT)); 4130 } 4131 4132 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4133 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4134 } 4135 4136 // Some RVV intrinsics may claim that they want an integer operand to be 4137 // promoted or expanded. 4138 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4139 const RISCVSubtarget &Subtarget) { 4140 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4141 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4142 "Unexpected opcode"); 4143 4144 if (!Subtarget.hasVInstructions()) 4145 return SDValue(); 4146 4147 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4148 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4149 SDLoc DL(Op); 4150 4151 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4152 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4153 if (!II || !II->hasSplatOperand()) 4154 return SDValue(); 4155 4156 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4157 assert(SplatOp < Op.getNumOperands()); 4158 4159 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4160 SDValue &ScalarOp = Operands[SplatOp]; 4161 MVT OpVT = ScalarOp.getSimpleValueType(); 4162 MVT XLenVT = Subtarget.getXLenVT(); 4163 4164 // If this isn't a scalar, or its type is XLenVT we're done. 4165 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4166 return SDValue(); 4167 4168 // Simplest case is that the operand needs to be promoted to XLenVT. 4169 if (OpVT.bitsLT(XLenVT)) { 4170 // If the operand is a constant, sign extend to increase our chances 4171 // of being able to use a .vi instruction. ANY_EXTEND would become a 4172 // a zero extend and the simm5 check in isel would fail. 4173 // FIXME: Should we ignore the upper bits in isel instead? 4174 unsigned ExtOpc = 4175 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4176 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4177 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4178 } 4179 4180 // Use the previous operand to get the vXi64 VT. The result might be a mask 4181 // VT for compares. Using the previous operand assumes that the previous 4182 // operand will never have a smaller element size than a scalar operand and 4183 // that a widening operation never uses SEW=64. 4184 // NOTE: If this fails the below assert, we can probably just find the 4185 // element count from any operand or result and use it to construct the VT. 4186 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4187 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4188 4189 // The more complex case is when the scalar is larger than XLenVT. 4190 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4191 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4192 4193 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4194 // on the instruction to sign-extend since SEW>XLEN. 4195 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4196 if (isInt<32>(CVal->getSExtValue())) { 4197 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4198 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4199 } 4200 } 4201 4202 // We need to convert the scalar to a splat vector. 4203 // FIXME: Can we implicitly truncate the scalar if it is known to 4204 // be sign extended? 4205 SDValue VL = Op.getOperand(II->VLOperand + 1 + HasChain); 4206 assert(VL.getValueType() == XLenVT); 4207 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4208 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4209 } 4210 4211 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4212 SelectionDAG &DAG) const { 4213 unsigned IntNo = Op.getConstantOperandVal(0); 4214 SDLoc DL(Op); 4215 MVT XLenVT = Subtarget.getXLenVT(); 4216 4217 switch (IntNo) { 4218 default: 4219 break; // Don't custom lower most intrinsics. 4220 case Intrinsic::thread_pointer: { 4221 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4222 return DAG.getRegister(RISCV::X4, PtrVT); 4223 } 4224 case Intrinsic::riscv_orc_b: 4225 // Lower to the GORCI encoding for orc.b. 4226 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 4227 DAG.getConstant(7, DL, XLenVT)); 4228 case Intrinsic::riscv_grev: 4229 case Intrinsic::riscv_gorc: { 4230 unsigned Opc = 4231 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4232 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4233 } 4234 case Intrinsic::riscv_shfl: 4235 case Intrinsic::riscv_unshfl: { 4236 unsigned Opc = 4237 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4238 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4239 } 4240 case Intrinsic::riscv_bcompress: 4241 case Intrinsic::riscv_bdecompress: { 4242 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4243 : RISCVISD::BDECOMPRESS; 4244 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4245 } 4246 case Intrinsic::riscv_bfp: 4247 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4248 Op.getOperand(2)); 4249 case Intrinsic::riscv_vmv_x_s: 4250 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4251 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4252 Op.getOperand(1)); 4253 case Intrinsic::riscv_vmv_v_x: 4254 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4255 Op.getSimpleValueType(), DL, DAG, Subtarget); 4256 case Intrinsic::riscv_vfmv_v_f: 4257 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4258 Op.getOperand(1), Op.getOperand(2)); 4259 case Intrinsic::riscv_vmv_s_x: { 4260 SDValue Scalar = Op.getOperand(2); 4261 4262 if (Scalar.getValueType().bitsLE(XLenVT)) { 4263 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4264 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4265 Op.getOperand(1), Scalar, Op.getOperand(3)); 4266 } 4267 4268 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4269 4270 // This is an i64 value that lives in two scalar registers. We have to 4271 // insert this in a convoluted way. First we build vXi64 splat containing 4272 // the/ two values that we assemble using some bit math. Next we'll use 4273 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4274 // to merge element 0 from our splat into the source vector. 4275 // FIXME: This is probably not the best way to do this, but it is 4276 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4277 // point. 4278 // sw lo, (a0) 4279 // sw hi, 4(a0) 4280 // vlse vX, (a0) 4281 // 4282 // vid.v vVid 4283 // vmseq.vx mMask, vVid, 0 4284 // vmerge.vvm vDest, vSrc, vVal, mMask 4285 MVT VT = Op.getSimpleValueType(); 4286 SDValue Vec = Op.getOperand(1); 4287 SDValue VL = Op.getOperand(3); 4288 4289 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4290 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4291 DAG.getConstant(0, DL, MVT::i32), VL); 4292 4293 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4294 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4295 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4296 SDValue SelectCond = 4297 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4298 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4299 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4300 Vec, VL); 4301 } 4302 case Intrinsic::riscv_vslide1up: 4303 case Intrinsic::riscv_vslide1down: 4304 case Intrinsic::riscv_vslide1up_mask: 4305 case Intrinsic::riscv_vslide1down_mask: { 4306 // We need to special case these when the scalar is larger than XLen. 4307 unsigned NumOps = Op.getNumOperands(); 4308 bool IsMasked = NumOps == 7; 4309 unsigned OpOffset = IsMasked ? 1 : 0; 4310 SDValue Scalar = Op.getOperand(2 + OpOffset); 4311 if (Scalar.getValueType().bitsLE(XLenVT)) 4312 break; 4313 4314 // Splatting a sign extended constant is fine. 4315 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4316 if (isInt<32>(CVal->getSExtValue())) 4317 break; 4318 4319 MVT VT = Op.getSimpleValueType(); 4320 assert(VT.getVectorElementType() == MVT::i64 && 4321 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4322 4323 // Convert the vector source to the equivalent nxvXi32 vector. 4324 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4325 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4326 4327 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4328 DAG.getConstant(0, DL, XLenVT)); 4329 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4330 DAG.getConstant(1, DL, XLenVT)); 4331 4332 // Double the VL since we halved SEW. 4333 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 4334 SDValue I32VL = 4335 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4336 4337 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4338 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4339 4340 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4341 // instructions. 4342 if (IntNo == Intrinsic::riscv_vslide1up || 4343 IntNo == Intrinsic::riscv_vslide1up_mask) { 4344 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4345 I32Mask, I32VL); 4346 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4347 I32Mask, I32VL); 4348 } else { 4349 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4350 I32Mask, I32VL); 4351 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4352 I32Mask, I32VL); 4353 } 4354 4355 // Convert back to nxvXi64. 4356 Vec = DAG.getBitcast(VT, Vec); 4357 4358 if (!IsMasked) 4359 return Vec; 4360 4361 // Apply mask after the operation. 4362 SDValue Mask = Op.getOperand(NumOps - 3); 4363 SDValue MaskedOff = Op.getOperand(1); 4364 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4365 } 4366 } 4367 4368 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4369 } 4370 4371 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4372 SelectionDAG &DAG) const { 4373 unsigned IntNo = Op.getConstantOperandVal(1); 4374 switch (IntNo) { 4375 default: 4376 break; 4377 case Intrinsic::riscv_masked_strided_load: { 4378 SDLoc DL(Op); 4379 MVT XLenVT = Subtarget.getXLenVT(); 4380 4381 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4382 // the selection of the masked intrinsics doesn't do this for us. 4383 SDValue Mask = Op.getOperand(5); 4384 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4385 4386 MVT VT = Op->getSimpleValueType(0); 4387 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4388 4389 SDValue PassThru = Op.getOperand(2); 4390 if (!IsUnmasked) { 4391 MVT MaskVT = 4392 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4393 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4394 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4395 } 4396 4397 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4398 4399 SDValue IntID = DAG.getTargetConstant( 4400 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4401 XLenVT); 4402 4403 auto *Load = cast<MemIntrinsicSDNode>(Op); 4404 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4405 if (!IsUnmasked) 4406 Ops.push_back(PassThru); 4407 Ops.push_back(Op.getOperand(3)); // Ptr 4408 Ops.push_back(Op.getOperand(4)); // Stride 4409 if (!IsUnmasked) 4410 Ops.push_back(Mask); 4411 Ops.push_back(VL); 4412 if (!IsUnmasked) { 4413 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4414 Ops.push_back(Policy); 4415 } 4416 4417 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4418 SDValue Result = 4419 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4420 Load->getMemoryVT(), Load->getMemOperand()); 4421 SDValue Chain = Result.getValue(1); 4422 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4423 return DAG.getMergeValues({Result, Chain}, DL); 4424 } 4425 } 4426 4427 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4428 } 4429 4430 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4431 SelectionDAG &DAG) const { 4432 unsigned IntNo = Op.getConstantOperandVal(1); 4433 switch (IntNo) { 4434 default: 4435 break; 4436 case Intrinsic::riscv_masked_strided_store: { 4437 SDLoc DL(Op); 4438 MVT XLenVT = Subtarget.getXLenVT(); 4439 4440 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4441 // the selection of the masked intrinsics doesn't do this for us. 4442 SDValue Mask = Op.getOperand(5); 4443 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4444 4445 SDValue Val = Op.getOperand(2); 4446 MVT VT = Val.getSimpleValueType(); 4447 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4448 4449 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4450 if (!IsUnmasked) { 4451 MVT MaskVT = 4452 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4453 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4454 } 4455 4456 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4457 4458 SDValue IntID = DAG.getTargetConstant( 4459 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4460 XLenVT); 4461 4462 auto *Store = cast<MemIntrinsicSDNode>(Op); 4463 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4464 Ops.push_back(Val); 4465 Ops.push_back(Op.getOperand(3)); // Ptr 4466 Ops.push_back(Op.getOperand(4)); // Stride 4467 if (!IsUnmasked) 4468 Ops.push_back(Mask); 4469 Ops.push_back(VL); 4470 4471 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4472 Ops, Store->getMemoryVT(), 4473 Store->getMemOperand()); 4474 } 4475 } 4476 4477 return SDValue(); 4478 } 4479 4480 static MVT getLMUL1VT(MVT VT) { 4481 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4482 "Unexpected vector MVT"); 4483 return MVT::getScalableVectorVT( 4484 VT.getVectorElementType(), 4485 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4486 } 4487 4488 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4489 switch (ISDOpcode) { 4490 default: 4491 llvm_unreachable("Unhandled reduction"); 4492 case ISD::VECREDUCE_ADD: 4493 return RISCVISD::VECREDUCE_ADD_VL; 4494 case ISD::VECREDUCE_UMAX: 4495 return RISCVISD::VECREDUCE_UMAX_VL; 4496 case ISD::VECREDUCE_SMAX: 4497 return RISCVISD::VECREDUCE_SMAX_VL; 4498 case ISD::VECREDUCE_UMIN: 4499 return RISCVISD::VECREDUCE_UMIN_VL; 4500 case ISD::VECREDUCE_SMIN: 4501 return RISCVISD::VECREDUCE_SMIN_VL; 4502 case ISD::VECREDUCE_AND: 4503 return RISCVISD::VECREDUCE_AND_VL; 4504 case ISD::VECREDUCE_OR: 4505 return RISCVISD::VECREDUCE_OR_VL; 4506 case ISD::VECREDUCE_XOR: 4507 return RISCVISD::VECREDUCE_XOR_VL; 4508 } 4509 } 4510 4511 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4512 SelectionDAG &DAG, 4513 bool IsVP) const { 4514 SDLoc DL(Op); 4515 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4516 MVT VecVT = Vec.getSimpleValueType(); 4517 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4518 Op.getOpcode() == ISD::VECREDUCE_OR || 4519 Op.getOpcode() == ISD::VECREDUCE_XOR || 4520 Op.getOpcode() == ISD::VP_REDUCE_AND || 4521 Op.getOpcode() == ISD::VP_REDUCE_OR || 4522 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4523 "Unexpected reduction lowering"); 4524 4525 MVT XLenVT = Subtarget.getXLenVT(); 4526 assert(Op.getValueType() == XLenVT && 4527 "Expected reduction output to be legalized to XLenVT"); 4528 4529 MVT ContainerVT = VecVT; 4530 if (VecVT.isFixedLengthVector()) { 4531 ContainerVT = getContainerForFixedLengthVector(VecVT); 4532 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4533 } 4534 4535 SDValue Mask, VL; 4536 if (IsVP) { 4537 Mask = Op.getOperand(2); 4538 VL = Op.getOperand(3); 4539 } else { 4540 std::tie(Mask, VL) = 4541 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4542 } 4543 4544 unsigned BaseOpc; 4545 ISD::CondCode CC; 4546 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4547 4548 switch (Op.getOpcode()) { 4549 default: 4550 llvm_unreachable("Unhandled reduction"); 4551 case ISD::VECREDUCE_AND: 4552 case ISD::VP_REDUCE_AND: { 4553 // vcpop ~x == 0 4554 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4555 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4556 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4557 CC = ISD::SETEQ; 4558 BaseOpc = ISD::AND; 4559 break; 4560 } 4561 case ISD::VECREDUCE_OR: 4562 case ISD::VP_REDUCE_OR: 4563 // vcpop x != 0 4564 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4565 CC = ISD::SETNE; 4566 BaseOpc = ISD::OR; 4567 break; 4568 case ISD::VECREDUCE_XOR: 4569 case ISD::VP_REDUCE_XOR: { 4570 // ((vcpop x) & 1) != 0 4571 SDValue One = DAG.getConstant(1, DL, XLenVT); 4572 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4573 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4574 CC = ISD::SETNE; 4575 BaseOpc = ISD::XOR; 4576 break; 4577 } 4578 } 4579 4580 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4581 4582 if (!IsVP) 4583 return SetCC; 4584 4585 // Now include the start value in the operation. 4586 // Note that we must return the start value when no elements are operated 4587 // upon. The vcpop instructions we've emitted in each case above will return 4588 // 0 for an inactive vector, and so we've already received the neutral value: 4589 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4590 // can simply include the start value. 4591 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4592 } 4593 4594 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4595 SelectionDAG &DAG) const { 4596 SDLoc DL(Op); 4597 SDValue Vec = Op.getOperand(0); 4598 EVT VecEVT = Vec.getValueType(); 4599 4600 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4601 4602 // Due to ordering in legalize types we may have a vector type that needs to 4603 // be split. Do that manually so we can get down to a legal type. 4604 while (getTypeAction(*DAG.getContext(), VecEVT) == 4605 TargetLowering::TypeSplitVector) { 4606 SDValue Lo, Hi; 4607 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4608 VecEVT = Lo.getValueType(); 4609 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4610 } 4611 4612 // TODO: The type may need to be widened rather than split. Or widened before 4613 // it can be split. 4614 if (!isTypeLegal(VecEVT)) 4615 return SDValue(); 4616 4617 MVT VecVT = VecEVT.getSimpleVT(); 4618 MVT VecEltVT = VecVT.getVectorElementType(); 4619 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4620 4621 MVT ContainerVT = VecVT; 4622 if (VecVT.isFixedLengthVector()) { 4623 ContainerVT = getContainerForFixedLengthVector(VecVT); 4624 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4625 } 4626 4627 MVT M1VT = getLMUL1VT(ContainerVT); 4628 MVT XLenVT = Subtarget.getXLenVT(); 4629 4630 SDValue Mask, VL; 4631 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4632 4633 SDValue NeutralElem = 4634 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4635 SDValue IdentitySplat = lowerScalarSplat( 4636 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4637 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4638 IdentitySplat, Mask, VL); 4639 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4640 DAG.getConstant(0, DL, XLenVT)); 4641 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4642 } 4643 4644 // Given a reduction op, this function returns the matching reduction opcode, 4645 // the vector SDValue and the scalar SDValue required to lower this to a 4646 // RISCVISD node. 4647 static std::tuple<unsigned, SDValue, SDValue> 4648 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4649 SDLoc DL(Op); 4650 auto Flags = Op->getFlags(); 4651 unsigned Opcode = Op.getOpcode(); 4652 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4653 switch (Opcode) { 4654 default: 4655 llvm_unreachable("Unhandled reduction"); 4656 case ISD::VECREDUCE_FADD: { 4657 // Use positive zero if we can. It is cheaper to materialize. 4658 SDValue Zero = 4659 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 4660 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 4661 } 4662 case ISD::VECREDUCE_SEQ_FADD: 4663 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4664 Op.getOperand(0)); 4665 case ISD::VECREDUCE_FMIN: 4666 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4667 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4668 case ISD::VECREDUCE_FMAX: 4669 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4670 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4671 } 4672 } 4673 4674 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4675 SelectionDAG &DAG) const { 4676 SDLoc DL(Op); 4677 MVT VecEltVT = Op.getSimpleValueType(); 4678 4679 unsigned RVVOpcode; 4680 SDValue VectorVal, ScalarVal; 4681 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4682 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4683 MVT VecVT = VectorVal.getSimpleValueType(); 4684 4685 MVT ContainerVT = VecVT; 4686 if (VecVT.isFixedLengthVector()) { 4687 ContainerVT = getContainerForFixedLengthVector(VecVT); 4688 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4689 } 4690 4691 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4692 MVT XLenVT = Subtarget.getXLenVT(); 4693 4694 SDValue Mask, VL; 4695 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4696 4697 SDValue ScalarSplat = lowerScalarSplat( 4698 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4699 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4700 VectorVal, ScalarSplat, Mask, VL); 4701 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4702 DAG.getConstant(0, DL, XLenVT)); 4703 } 4704 4705 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4706 switch (ISDOpcode) { 4707 default: 4708 llvm_unreachable("Unhandled reduction"); 4709 case ISD::VP_REDUCE_ADD: 4710 return RISCVISD::VECREDUCE_ADD_VL; 4711 case ISD::VP_REDUCE_UMAX: 4712 return RISCVISD::VECREDUCE_UMAX_VL; 4713 case ISD::VP_REDUCE_SMAX: 4714 return RISCVISD::VECREDUCE_SMAX_VL; 4715 case ISD::VP_REDUCE_UMIN: 4716 return RISCVISD::VECREDUCE_UMIN_VL; 4717 case ISD::VP_REDUCE_SMIN: 4718 return RISCVISD::VECREDUCE_SMIN_VL; 4719 case ISD::VP_REDUCE_AND: 4720 return RISCVISD::VECREDUCE_AND_VL; 4721 case ISD::VP_REDUCE_OR: 4722 return RISCVISD::VECREDUCE_OR_VL; 4723 case ISD::VP_REDUCE_XOR: 4724 return RISCVISD::VECREDUCE_XOR_VL; 4725 case ISD::VP_REDUCE_FADD: 4726 return RISCVISD::VECREDUCE_FADD_VL; 4727 case ISD::VP_REDUCE_SEQ_FADD: 4728 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4729 case ISD::VP_REDUCE_FMAX: 4730 return RISCVISD::VECREDUCE_FMAX_VL; 4731 case ISD::VP_REDUCE_FMIN: 4732 return RISCVISD::VECREDUCE_FMIN_VL; 4733 } 4734 } 4735 4736 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4737 SelectionDAG &DAG) const { 4738 SDLoc DL(Op); 4739 SDValue Vec = Op.getOperand(1); 4740 EVT VecEVT = Vec.getValueType(); 4741 4742 // TODO: The type may need to be widened rather than split. Or widened before 4743 // it can be split. 4744 if (!isTypeLegal(VecEVT)) 4745 return SDValue(); 4746 4747 MVT VecVT = VecEVT.getSimpleVT(); 4748 MVT VecEltVT = VecVT.getVectorElementType(); 4749 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4750 4751 MVT ContainerVT = VecVT; 4752 if (VecVT.isFixedLengthVector()) { 4753 ContainerVT = getContainerForFixedLengthVector(VecVT); 4754 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4755 } 4756 4757 SDValue VL = Op.getOperand(3); 4758 SDValue Mask = Op.getOperand(2); 4759 4760 MVT M1VT = getLMUL1VT(ContainerVT); 4761 MVT XLenVT = Subtarget.getXLenVT(); 4762 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4763 4764 SDValue StartSplat = 4765 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 4766 DL, DAG, Subtarget); 4767 SDValue Reduction = 4768 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4769 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4770 DAG.getConstant(0, DL, XLenVT)); 4771 if (!VecVT.isInteger()) 4772 return Elt0; 4773 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4774 } 4775 4776 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4777 SelectionDAG &DAG) const { 4778 SDValue Vec = Op.getOperand(0); 4779 SDValue SubVec = Op.getOperand(1); 4780 MVT VecVT = Vec.getSimpleValueType(); 4781 MVT SubVecVT = SubVec.getSimpleValueType(); 4782 4783 SDLoc DL(Op); 4784 MVT XLenVT = Subtarget.getXLenVT(); 4785 unsigned OrigIdx = Op.getConstantOperandVal(2); 4786 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4787 4788 // We don't have the ability to slide mask vectors up indexed by their i1 4789 // elements; the smallest we can do is i8. Often we are able to bitcast to 4790 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4791 // into a scalable one, we might not necessarily have enough scalable 4792 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4793 if (SubVecVT.getVectorElementType() == MVT::i1 && 4794 (OrigIdx != 0 || !Vec.isUndef())) { 4795 if (VecVT.getVectorMinNumElements() >= 8 && 4796 SubVecVT.getVectorMinNumElements() >= 8) { 4797 assert(OrigIdx % 8 == 0 && "Invalid index"); 4798 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4799 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4800 "Unexpected mask vector lowering"); 4801 OrigIdx /= 8; 4802 SubVecVT = 4803 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4804 SubVecVT.isScalableVector()); 4805 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4806 VecVT.isScalableVector()); 4807 Vec = DAG.getBitcast(VecVT, Vec); 4808 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4809 } else { 4810 // We can't slide this mask vector up indexed by its i1 elements. 4811 // This poses a problem when we wish to insert a scalable vector which 4812 // can't be re-expressed as a larger type. Just choose the slow path and 4813 // extend to a larger type, then truncate back down. 4814 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4815 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4816 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4817 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4818 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4819 Op.getOperand(2)); 4820 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4821 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4822 } 4823 } 4824 4825 // If the subvector vector is a fixed-length type, we cannot use subregister 4826 // manipulation to simplify the codegen; we don't know which register of a 4827 // LMUL group contains the specific subvector as we only know the minimum 4828 // register size. Therefore we must slide the vector group up the full 4829 // amount. 4830 if (SubVecVT.isFixedLengthVector()) { 4831 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 4832 return Op; 4833 MVT ContainerVT = VecVT; 4834 if (VecVT.isFixedLengthVector()) { 4835 ContainerVT = getContainerForFixedLengthVector(VecVT); 4836 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4837 } 4838 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4839 DAG.getUNDEF(ContainerVT), SubVec, 4840 DAG.getConstant(0, DL, XLenVT)); 4841 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 4842 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 4843 return DAG.getBitcast(Op.getValueType(), SubVec); 4844 } 4845 SDValue Mask = 4846 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4847 // Set the vector length to only the number of elements we care about. Note 4848 // that for slideup this includes the offset. 4849 SDValue VL = 4850 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4851 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4852 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4853 SubVec, SlideupAmt, Mask, VL); 4854 if (VecVT.isFixedLengthVector()) 4855 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4856 return DAG.getBitcast(Op.getValueType(), Slideup); 4857 } 4858 4859 unsigned SubRegIdx, RemIdx; 4860 std::tie(SubRegIdx, RemIdx) = 4861 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4862 VecVT, SubVecVT, OrigIdx, TRI); 4863 4864 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4865 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4866 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4867 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4868 4869 // 1. If the Idx has been completely eliminated and this subvector's size is 4870 // a vector register or a multiple thereof, or the surrounding elements are 4871 // undef, then this is a subvector insert which naturally aligns to a vector 4872 // register. These can easily be handled using subregister manipulation. 4873 // 2. If the subvector is smaller than a vector register, then the insertion 4874 // must preserve the undisturbed elements of the register. We do this by 4875 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4876 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4877 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4878 // LMUL=1 type back into the larger vector (resolving to another subregister 4879 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4880 // to avoid allocating a large register group to hold our subvector. 4881 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4882 return Op; 4883 4884 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4885 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4886 // (in our case undisturbed). This means we can set up a subvector insertion 4887 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4888 // size of the subvector. 4889 MVT InterSubVT = VecVT; 4890 SDValue AlignedExtract = Vec; 4891 unsigned AlignedIdx = OrigIdx - RemIdx; 4892 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4893 InterSubVT = getLMUL1VT(VecVT); 4894 // Extract a subvector equal to the nearest full vector register type. This 4895 // should resolve to a EXTRACT_SUBREG instruction. 4896 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4897 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4898 } 4899 4900 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4901 // For scalable vectors this must be further multiplied by vscale. 4902 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4903 4904 SDValue Mask, VL; 4905 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4906 4907 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4908 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4909 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4910 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4911 4912 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4913 DAG.getUNDEF(InterSubVT), SubVec, 4914 DAG.getConstant(0, DL, XLenVT)); 4915 4916 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4917 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4918 4919 // If required, insert this subvector back into the correct vector register. 4920 // This should resolve to an INSERT_SUBREG instruction. 4921 if (VecVT.bitsGT(InterSubVT)) 4922 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4923 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4924 4925 // We might have bitcast from a mask type: cast back to the original type if 4926 // required. 4927 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4928 } 4929 4930 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4931 SelectionDAG &DAG) const { 4932 SDValue Vec = Op.getOperand(0); 4933 MVT SubVecVT = Op.getSimpleValueType(); 4934 MVT VecVT = Vec.getSimpleValueType(); 4935 4936 SDLoc DL(Op); 4937 MVT XLenVT = Subtarget.getXLenVT(); 4938 unsigned OrigIdx = Op.getConstantOperandVal(1); 4939 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4940 4941 // We don't have the ability to slide mask vectors down indexed by their i1 4942 // elements; the smallest we can do is i8. Often we are able to bitcast to 4943 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4944 // from a scalable one, we might not necessarily have enough scalable 4945 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4946 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4947 if (VecVT.getVectorMinNumElements() >= 8 && 4948 SubVecVT.getVectorMinNumElements() >= 8) { 4949 assert(OrigIdx % 8 == 0 && "Invalid index"); 4950 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4951 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4952 "Unexpected mask vector lowering"); 4953 OrigIdx /= 8; 4954 SubVecVT = 4955 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4956 SubVecVT.isScalableVector()); 4957 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4958 VecVT.isScalableVector()); 4959 Vec = DAG.getBitcast(VecVT, Vec); 4960 } else { 4961 // We can't slide this mask vector down, indexed by its i1 elements. 4962 // This poses a problem when we wish to extract a scalable vector which 4963 // can't be re-expressed as a larger type. Just choose the slow path and 4964 // extend to a larger type, then truncate back down. 4965 // TODO: We could probably improve this when extracting certain fixed 4966 // from fixed, where we can extract as i8 and shift the correct element 4967 // right to reach the desired subvector? 4968 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4969 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4970 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4971 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4972 Op.getOperand(1)); 4973 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4974 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4975 } 4976 } 4977 4978 // If the subvector vector is a fixed-length type, we cannot use subregister 4979 // manipulation to simplify the codegen; we don't know which register of a 4980 // LMUL group contains the specific subvector as we only know the minimum 4981 // register size. Therefore we must slide the vector group down the full 4982 // amount. 4983 if (SubVecVT.isFixedLengthVector()) { 4984 // With an index of 0 this is a cast-like subvector, which can be performed 4985 // with subregister operations. 4986 if (OrigIdx == 0) 4987 return Op; 4988 MVT ContainerVT = VecVT; 4989 if (VecVT.isFixedLengthVector()) { 4990 ContainerVT = getContainerForFixedLengthVector(VecVT); 4991 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4992 } 4993 SDValue Mask = 4994 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4995 // Set the vector length to only the number of elements we care about. This 4996 // avoids sliding down elements we're going to discard straight away. 4997 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4998 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4999 SDValue Slidedown = 5000 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5001 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5002 // Now we can use a cast-like subvector extract to get the result. 5003 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5004 DAG.getConstant(0, DL, XLenVT)); 5005 return DAG.getBitcast(Op.getValueType(), Slidedown); 5006 } 5007 5008 unsigned SubRegIdx, RemIdx; 5009 std::tie(SubRegIdx, RemIdx) = 5010 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5011 VecVT, SubVecVT, OrigIdx, TRI); 5012 5013 // If the Idx has been completely eliminated then this is a subvector extract 5014 // which naturally aligns to a vector register. These can easily be handled 5015 // using subregister manipulation. 5016 if (RemIdx == 0) 5017 return Op; 5018 5019 // Else we must shift our vector register directly to extract the subvector. 5020 // Do this using VSLIDEDOWN. 5021 5022 // If the vector type is an LMUL-group type, extract a subvector equal to the 5023 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5024 // instruction. 5025 MVT InterSubVT = VecVT; 5026 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5027 InterSubVT = getLMUL1VT(VecVT); 5028 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5029 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5030 } 5031 5032 // Slide this vector register down by the desired number of elements in order 5033 // to place the desired subvector starting at element 0. 5034 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5035 // For scalable vectors this must be further multiplied by vscale. 5036 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5037 5038 SDValue Mask, VL; 5039 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5040 SDValue Slidedown = 5041 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5042 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5043 5044 // Now the vector is in the right position, extract our final subvector. This 5045 // should resolve to a COPY. 5046 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5047 DAG.getConstant(0, DL, XLenVT)); 5048 5049 // We might have bitcast from a mask type: cast back to the original type if 5050 // required. 5051 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5052 } 5053 5054 // Lower step_vector to the vid instruction. Any non-identity step value must 5055 // be accounted for my manual expansion. 5056 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5057 SelectionDAG &DAG) const { 5058 SDLoc DL(Op); 5059 MVT VT = Op.getSimpleValueType(); 5060 MVT XLenVT = Subtarget.getXLenVT(); 5061 SDValue Mask, VL; 5062 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5063 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5064 uint64_t StepValImm = Op.getConstantOperandVal(0); 5065 if (StepValImm != 1) { 5066 if (isPowerOf2_64(StepValImm)) { 5067 SDValue StepVal = 5068 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 5069 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5070 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5071 } else { 5072 SDValue StepVal = lowerScalarSplat( 5073 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 5074 DL, DAG, Subtarget); 5075 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5076 } 5077 } 5078 return StepVec; 5079 } 5080 5081 // Implement vector_reverse using vrgather.vv with indices determined by 5082 // subtracting the id of each element from (VLMAX-1). This will convert 5083 // the indices like so: 5084 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5085 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5086 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5087 SelectionDAG &DAG) const { 5088 SDLoc DL(Op); 5089 MVT VecVT = Op.getSimpleValueType(); 5090 unsigned EltSize = VecVT.getScalarSizeInBits(); 5091 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5092 5093 unsigned MaxVLMAX = 0; 5094 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5095 if (VectorBitsMax != 0) 5096 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5097 5098 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5099 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5100 5101 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5102 // to use vrgatherei16.vv. 5103 // TODO: It's also possible to use vrgatherei16.vv for other types to 5104 // decrease register width for the index calculation. 5105 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5106 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5107 // Reverse each half, then reassemble them in reverse order. 5108 // NOTE: It's also possible that after splitting that VLMAX no longer 5109 // requires vrgatherei16.vv. 5110 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5111 SDValue Lo, Hi; 5112 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5113 EVT LoVT, HiVT; 5114 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5115 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5116 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5117 // Reassemble the low and high pieces reversed. 5118 // FIXME: This is a CONCAT_VECTORS. 5119 SDValue Res = 5120 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5121 DAG.getIntPtrConstant(0, DL)); 5122 return DAG.getNode( 5123 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5124 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5125 } 5126 5127 // Just promote the int type to i16 which will double the LMUL. 5128 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5129 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5130 } 5131 5132 MVT XLenVT = Subtarget.getXLenVT(); 5133 SDValue Mask, VL; 5134 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5135 5136 // Calculate VLMAX-1 for the desired SEW. 5137 unsigned MinElts = VecVT.getVectorMinNumElements(); 5138 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5139 DAG.getConstant(MinElts, DL, XLenVT)); 5140 SDValue VLMinus1 = 5141 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5142 5143 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5144 bool IsRV32E64 = 5145 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5146 SDValue SplatVL; 5147 if (!IsRV32E64) 5148 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5149 else 5150 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 5151 5152 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5153 SDValue Indices = 5154 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5155 5156 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5157 } 5158 5159 SDValue 5160 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5161 SelectionDAG &DAG) const { 5162 SDLoc DL(Op); 5163 auto *Load = cast<LoadSDNode>(Op); 5164 5165 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5166 Load->getMemoryVT(), 5167 *Load->getMemOperand()) && 5168 "Expecting a correctly-aligned load"); 5169 5170 MVT VT = Op.getSimpleValueType(); 5171 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5172 5173 SDValue VL = 5174 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5175 5176 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5177 SDValue NewLoad = DAG.getMemIntrinsicNode( 5178 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5179 Load->getMemoryVT(), Load->getMemOperand()); 5180 5181 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5182 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5183 } 5184 5185 SDValue 5186 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5187 SelectionDAG &DAG) const { 5188 SDLoc DL(Op); 5189 auto *Store = cast<StoreSDNode>(Op); 5190 5191 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5192 Store->getMemoryVT(), 5193 *Store->getMemOperand()) && 5194 "Expecting a correctly-aligned store"); 5195 5196 SDValue StoreVal = Store->getValue(); 5197 MVT VT = StoreVal.getSimpleValueType(); 5198 5199 // If the size less than a byte, we need to pad with zeros to make a byte. 5200 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5201 VT = MVT::v8i1; 5202 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5203 DAG.getConstant(0, DL, VT), StoreVal, 5204 DAG.getIntPtrConstant(0, DL)); 5205 } 5206 5207 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5208 5209 SDValue VL = 5210 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5211 5212 SDValue NewValue = 5213 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5214 return DAG.getMemIntrinsicNode( 5215 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5216 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5217 Store->getMemoryVT(), Store->getMemOperand()); 5218 } 5219 5220 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5221 SelectionDAG &DAG) const { 5222 SDLoc DL(Op); 5223 MVT VT = Op.getSimpleValueType(); 5224 5225 const auto *MemSD = cast<MemSDNode>(Op); 5226 EVT MemVT = MemSD->getMemoryVT(); 5227 MachineMemOperand *MMO = MemSD->getMemOperand(); 5228 SDValue Chain = MemSD->getChain(); 5229 SDValue BasePtr = MemSD->getBasePtr(); 5230 5231 SDValue Mask, PassThru, VL; 5232 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5233 Mask = VPLoad->getMask(); 5234 PassThru = DAG.getUNDEF(VT); 5235 VL = VPLoad->getVectorLength(); 5236 } else { 5237 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5238 Mask = MLoad->getMask(); 5239 PassThru = MLoad->getPassThru(); 5240 } 5241 5242 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5243 5244 MVT XLenVT = Subtarget.getXLenVT(); 5245 5246 MVT ContainerVT = VT; 5247 if (VT.isFixedLengthVector()) { 5248 ContainerVT = getContainerForFixedLengthVector(VT); 5249 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5250 if (!IsUnmasked) { 5251 MVT MaskVT = 5252 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5253 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5254 } 5255 } 5256 5257 if (!VL) 5258 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5259 5260 unsigned IntID = 5261 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5262 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5263 if (!IsUnmasked) 5264 Ops.push_back(PassThru); 5265 Ops.push_back(BasePtr); 5266 if (!IsUnmasked) 5267 Ops.push_back(Mask); 5268 Ops.push_back(VL); 5269 if (!IsUnmasked) 5270 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5271 5272 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5273 5274 SDValue Result = 5275 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5276 Chain = Result.getValue(1); 5277 5278 if (VT.isFixedLengthVector()) 5279 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5280 5281 return DAG.getMergeValues({Result, Chain}, DL); 5282 } 5283 5284 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5285 SelectionDAG &DAG) const { 5286 SDLoc DL(Op); 5287 5288 const auto *MemSD = cast<MemSDNode>(Op); 5289 EVT MemVT = MemSD->getMemoryVT(); 5290 MachineMemOperand *MMO = MemSD->getMemOperand(); 5291 SDValue Chain = MemSD->getChain(); 5292 SDValue BasePtr = MemSD->getBasePtr(); 5293 SDValue Val, Mask, VL; 5294 5295 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5296 Val = VPStore->getValue(); 5297 Mask = VPStore->getMask(); 5298 VL = VPStore->getVectorLength(); 5299 } else { 5300 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5301 Val = MStore->getValue(); 5302 Mask = MStore->getMask(); 5303 } 5304 5305 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5306 5307 MVT VT = Val.getSimpleValueType(); 5308 MVT XLenVT = Subtarget.getXLenVT(); 5309 5310 MVT ContainerVT = VT; 5311 if (VT.isFixedLengthVector()) { 5312 ContainerVT = getContainerForFixedLengthVector(VT); 5313 5314 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5315 if (!IsUnmasked) { 5316 MVT MaskVT = 5317 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5318 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5319 } 5320 } 5321 5322 if (!VL) 5323 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5324 5325 unsigned IntID = 5326 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5327 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5328 Ops.push_back(Val); 5329 Ops.push_back(BasePtr); 5330 if (!IsUnmasked) 5331 Ops.push_back(Mask); 5332 Ops.push_back(VL); 5333 5334 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5335 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5336 } 5337 5338 SDValue 5339 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5340 SelectionDAG &DAG) const { 5341 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5342 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5343 5344 MVT VT = Op.getSimpleValueType(); 5345 5346 SDValue Op1 = 5347 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5348 SDValue Op2 = 5349 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5350 5351 SDLoc DL(Op); 5352 SDValue VL = 5353 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5354 5355 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5356 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5357 5358 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5359 Op.getOperand(2), Mask, VL); 5360 5361 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5362 } 5363 5364 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5365 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5366 MVT VT = Op.getSimpleValueType(); 5367 5368 if (VT.getVectorElementType() == MVT::i1) 5369 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5370 5371 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5372 } 5373 5374 SDValue 5375 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5376 SelectionDAG &DAG) const { 5377 unsigned Opc; 5378 switch (Op.getOpcode()) { 5379 default: llvm_unreachable("Unexpected opcode!"); 5380 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5381 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5382 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5383 } 5384 5385 return lowerToScalableOp(Op, DAG, Opc); 5386 } 5387 5388 // Lower vector ABS to smax(X, sub(0, X)). 5389 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5390 SDLoc DL(Op); 5391 MVT VT = Op.getSimpleValueType(); 5392 SDValue X = Op.getOperand(0); 5393 5394 assert(VT.isFixedLengthVector() && "Unexpected type"); 5395 5396 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5397 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5398 5399 SDValue Mask, VL; 5400 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5401 5402 SDValue SplatZero = 5403 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5404 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5405 SDValue NegX = 5406 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5407 SDValue Max = 5408 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5409 5410 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5411 } 5412 5413 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5414 SDValue Op, SelectionDAG &DAG) const { 5415 SDLoc DL(Op); 5416 MVT VT = Op.getSimpleValueType(); 5417 SDValue Mag = Op.getOperand(0); 5418 SDValue Sign = Op.getOperand(1); 5419 assert(Mag.getValueType() == Sign.getValueType() && 5420 "Can only handle COPYSIGN with matching types."); 5421 5422 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5423 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5424 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5425 5426 SDValue Mask, VL; 5427 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5428 5429 SDValue CopySign = 5430 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5431 5432 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5433 } 5434 5435 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5436 SDValue Op, SelectionDAG &DAG) const { 5437 MVT VT = Op.getSimpleValueType(); 5438 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5439 5440 MVT I1ContainerVT = 5441 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5442 5443 SDValue CC = 5444 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5445 SDValue Op1 = 5446 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5447 SDValue Op2 = 5448 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5449 5450 SDLoc DL(Op); 5451 SDValue Mask, VL; 5452 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5453 5454 SDValue Select = 5455 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5456 5457 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5458 } 5459 5460 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5461 unsigned NewOpc, 5462 bool HasMask) const { 5463 MVT VT = Op.getSimpleValueType(); 5464 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5465 5466 // Create list of operands by converting existing ones to scalable types. 5467 SmallVector<SDValue, 6> Ops; 5468 for (const SDValue &V : Op->op_values()) { 5469 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5470 5471 // Pass through non-vector operands. 5472 if (!V.getValueType().isVector()) { 5473 Ops.push_back(V); 5474 continue; 5475 } 5476 5477 // "cast" fixed length vector to a scalable vector. 5478 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5479 "Only fixed length vectors are supported!"); 5480 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5481 } 5482 5483 SDLoc DL(Op); 5484 SDValue Mask, VL; 5485 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5486 if (HasMask) 5487 Ops.push_back(Mask); 5488 Ops.push_back(VL); 5489 5490 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5491 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5492 } 5493 5494 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5495 // * Operands of each node are assumed to be in the same order. 5496 // * The EVL operand is promoted from i32 to i64 on RV64. 5497 // * Fixed-length vectors are converted to their scalable-vector container 5498 // types. 5499 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5500 unsigned RISCVISDOpc) const { 5501 SDLoc DL(Op); 5502 MVT VT = Op.getSimpleValueType(); 5503 SmallVector<SDValue, 4> Ops; 5504 5505 for (const auto &OpIdx : enumerate(Op->ops())) { 5506 SDValue V = OpIdx.value(); 5507 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5508 // Pass through operands which aren't fixed-length vectors. 5509 if (!V.getValueType().isFixedLengthVector()) { 5510 Ops.push_back(V); 5511 continue; 5512 } 5513 // "cast" fixed length vector to a scalable vector. 5514 MVT OpVT = V.getSimpleValueType(); 5515 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5516 assert(useRVVForFixedLengthVectorVT(OpVT) && 5517 "Only fixed length vectors are supported!"); 5518 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5519 } 5520 5521 if (!VT.isFixedLengthVector()) 5522 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5523 5524 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5525 5526 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5527 5528 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5529 } 5530 5531 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 5532 unsigned MaskOpc, 5533 unsigned VecOpc) const { 5534 MVT VT = Op.getSimpleValueType(); 5535 if (VT.getVectorElementType() != MVT::i1) 5536 return lowerVPOp(Op, DAG, VecOpc); 5537 5538 // It is safe to drop mask parameter as masked-off elements are undef. 5539 SDValue Op1 = Op->getOperand(0); 5540 SDValue Op2 = Op->getOperand(1); 5541 SDValue VL = Op->getOperand(3); 5542 5543 MVT ContainerVT = VT; 5544 const bool IsFixed = VT.isFixedLengthVector(); 5545 if (IsFixed) { 5546 ContainerVT = getContainerForFixedLengthVector(VT); 5547 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 5548 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 5549 } 5550 5551 SDLoc DL(Op); 5552 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 5553 if (!IsFixed) 5554 return Val; 5555 return convertFromScalableVector(VT, Val, DAG, Subtarget); 5556 } 5557 5558 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5559 // matched to a RVV indexed load. The RVV indexed load instructions only 5560 // support the "unsigned unscaled" addressing mode; indices are implicitly 5561 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5562 // signed or scaled indexing is extended to the XLEN value type and scaled 5563 // accordingly. 5564 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5565 SelectionDAG &DAG) const { 5566 SDLoc DL(Op); 5567 MVT VT = Op.getSimpleValueType(); 5568 5569 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5570 EVT MemVT = MemSD->getMemoryVT(); 5571 MachineMemOperand *MMO = MemSD->getMemOperand(); 5572 SDValue Chain = MemSD->getChain(); 5573 SDValue BasePtr = MemSD->getBasePtr(); 5574 5575 ISD::LoadExtType LoadExtType; 5576 SDValue Index, Mask, PassThru, VL; 5577 5578 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5579 Index = VPGN->getIndex(); 5580 Mask = VPGN->getMask(); 5581 PassThru = DAG.getUNDEF(VT); 5582 VL = VPGN->getVectorLength(); 5583 // VP doesn't support extending loads. 5584 LoadExtType = ISD::NON_EXTLOAD; 5585 } else { 5586 // Else it must be a MGATHER. 5587 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5588 Index = MGN->getIndex(); 5589 Mask = MGN->getMask(); 5590 PassThru = MGN->getPassThru(); 5591 LoadExtType = MGN->getExtensionType(); 5592 } 5593 5594 MVT IndexVT = Index.getSimpleValueType(); 5595 MVT XLenVT = Subtarget.getXLenVT(); 5596 5597 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5598 "Unexpected VTs!"); 5599 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5600 // Targets have to explicitly opt-in for extending vector loads. 5601 assert(LoadExtType == ISD::NON_EXTLOAD && 5602 "Unexpected extending MGATHER/VP_GATHER"); 5603 (void)LoadExtType; 5604 5605 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5606 // the selection of the masked intrinsics doesn't do this for us. 5607 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5608 5609 MVT ContainerVT = VT; 5610 if (VT.isFixedLengthVector()) { 5611 // We need to use the larger of the result and index type to determine the 5612 // scalable type to use so we don't increase LMUL for any operand/result. 5613 if (VT.bitsGE(IndexVT)) { 5614 ContainerVT = getContainerForFixedLengthVector(VT); 5615 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5616 ContainerVT.getVectorElementCount()); 5617 } else { 5618 IndexVT = getContainerForFixedLengthVector(IndexVT); 5619 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5620 IndexVT.getVectorElementCount()); 5621 } 5622 5623 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5624 5625 if (!IsUnmasked) { 5626 MVT MaskVT = 5627 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5628 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5629 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5630 } 5631 } 5632 5633 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5634 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5635 Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index); 5636 } 5637 5638 if (!VL) 5639 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5640 5641 unsigned IntID = 5642 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5643 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5644 if (!IsUnmasked) 5645 Ops.push_back(PassThru); 5646 Ops.push_back(BasePtr); 5647 Ops.push_back(Index); 5648 if (!IsUnmasked) 5649 Ops.push_back(Mask); 5650 Ops.push_back(VL); 5651 if (!IsUnmasked) 5652 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5653 5654 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5655 SDValue Result = 5656 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5657 Chain = Result.getValue(1); 5658 5659 if (VT.isFixedLengthVector()) 5660 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5661 5662 return DAG.getMergeValues({Result, Chain}, DL); 5663 } 5664 5665 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5666 // matched to a RVV indexed store. The RVV indexed store instructions only 5667 // support the "unsigned unscaled" addressing mode; indices are implicitly 5668 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5669 // signed or scaled indexing is extended to the XLEN value type and scaled 5670 // accordingly. 5671 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5672 SelectionDAG &DAG) const { 5673 SDLoc DL(Op); 5674 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5675 EVT MemVT = MemSD->getMemoryVT(); 5676 MachineMemOperand *MMO = MemSD->getMemOperand(); 5677 SDValue Chain = MemSD->getChain(); 5678 SDValue BasePtr = MemSD->getBasePtr(); 5679 5680 bool IsTruncatingStore = false; 5681 SDValue Index, Mask, Val, VL; 5682 5683 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5684 Index = VPSN->getIndex(); 5685 Mask = VPSN->getMask(); 5686 Val = VPSN->getValue(); 5687 VL = VPSN->getVectorLength(); 5688 // VP doesn't support truncating stores. 5689 IsTruncatingStore = false; 5690 } else { 5691 // Else it must be a MSCATTER. 5692 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5693 Index = MSN->getIndex(); 5694 Mask = MSN->getMask(); 5695 Val = MSN->getValue(); 5696 IsTruncatingStore = MSN->isTruncatingStore(); 5697 } 5698 5699 MVT VT = Val.getSimpleValueType(); 5700 MVT IndexVT = Index.getSimpleValueType(); 5701 MVT XLenVT = Subtarget.getXLenVT(); 5702 5703 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5704 "Unexpected VTs!"); 5705 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5706 // Targets have to explicitly opt-in for extending vector loads and 5707 // truncating vector stores. 5708 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5709 (void)IsTruncatingStore; 5710 5711 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5712 // the selection of the masked intrinsics doesn't do this for us. 5713 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5714 5715 MVT ContainerVT = VT; 5716 if (VT.isFixedLengthVector()) { 5717 // We need to use the larger of the value and index type to determine the 5718 // scalable type to use so we don't increase LMUL for any operand/result. 5719 if (VT.bitsGE(IndexVT)) { 5720 ContainerVT = getContainerForFixedLengthVector(VT); 5721 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5722 ContainerVT.getVectorElementCount()); 5723 } else { 5724 IndexVT = getContainerForFixedLengthVector(IndexVT); 5725 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5726 IndexVT.getVectorElementCount()); 5727 } 5728 5729 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5730 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5731 5732 if (!IsUnmasked) { 5733 MVT MaskVT = 5734 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5735 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5736 } 5737 } 5738 5739 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5740 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5741 Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index); 5742 } 5743 5744 if (!VL) 5745 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5746 5747 unsigned IntID = 5748 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5749 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5750 Ops.push_back(Val); 5751 Ops.push_back(BasePtr); 5752 Ops.push_back(Index); 5753 if (!IsUnmasked) 5754 Ops.push_back(Mask); 5755 Ops.push_back(VL); 5756 5757 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5758 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5759 } 5760 5761 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5762 SelectionDAG &DAG) const { 5763 const MVT XLenVT = Subtarget.getXLenVT(); 5764 SDLoc DL(Op); 5765 SDValue Chain = Op->getOperand(0); 5766 SDValue SysRegNo = DAG.getTargetConstant( 5767 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5768 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5769 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5770 5771 // Encoding used for rounding mode in RISCV differs from that used in 5772 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5773 // table, which consists of a sequence of 4-bit fields, each representing 5774 // corresponding FLT_ROUNDS mode. 5775 static const int Table = 5776 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5777 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5778 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5779 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5780 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5781 5782 SDValue Shift = 5783 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5784 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5785 DAG.getConstant(Table, DL, XLenVT), Shift); 5786 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5787 DAG.getConstant(7, DL, XLenVT)); 5788 5789 return DAG.getMergeValues({Masked, Chain}, DL); 5790 } 5791 5792 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5793 SelectionDAG &DAG) const { 5794 const MVT XLenVT = Subtarget.getXLenVT(); 5795 SDLoc DL(Op); 5796 SDValue Chain = Op->getOperand(0); 5797 SDValue RMValue = Op->getOperand(1); 5798 SDValue SysRegNo = DAG.getTargetConstant( 5799 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5800 5801 // Encoding used for rounding mode in RISCV differs from that used in 5802 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5803 // a table, which consists of a sequence of 4-bit fields, each representing 5804 // corresponding RISCV mode. 5805 static const unsigned Table = 5806 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5807 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5808 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5809 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5810 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5811 5812 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5813 DAG.getConstant(2, DL, XLenVT)); 5814 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5815 DAG.getConstant(Table, DL, XLenVT), Shift); 5816 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5817 DAG.getConstant(0x7, DL, XLenVT)); 5818 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5819 RMValue); 5820 } 5821 5822 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 5823 switch (IntNo) { 5824 default: 5825 llvm_unreachable("Unexpected Intrinsic"); 5826 case Intrinsic::riscv_grev: 5827 return RISCVISD::GREVW; 5828 case Intrinsic::riscv_gorc: 5829 return RISCVISD::GORCW; 5830 case Intrinsic::riscv_bcompress: 5831 return RISCVISD::BCOMPRESSW; 5832 case Intrinsic::riscv_bdecompress: 5833 return RISCVISD::BDECOMPRESSW; 5834 case Intrinsic::riscv_bfp: 5835 return RISCVISD::BFPW; 5836 } 5837 } 5838 5839 // Converts the given intrinsic to a i64 operation with any extension. 5840 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 5841 unsigned IntNo) { 5842 SDLoc DL(N); 5843 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 5844 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5845 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 5846 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 5847 // ReplaceNodeResults requires we maintain the same type for the return value. 5848 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5849 } 5850 5851 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5852 // form of the given Opcode. 5853 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5854 switch (Opcode) { 5855 default: 5856 llvm_unreachable("Unexpected opcode"); 5857 case ISD::SHL: 5858 return RISCVISD::SLLW; 5859 case ISD::SRA: 5860 return RISCVISD::SRAW; 5861 case ISD::SRL: 5862 return RISCVISD::SRLW; 5863 case ISD::SDIV: 5864 return RISCVISD::DIVW; 5865 case ISD::UDIV: 5866 return RISCVISD::DIVUW; 5867 case ISD::UREM: 5868 return RISCVISD::REMUW; 5869 case ISD::ROTL: 5870 return RISCVISD::ROLW; 5871 case ISD::ROTR: 5872 return RISCVISD::RORW; 5873 case RISCVISD::GREV: 5874 return RISCVISD::GREVW; 5875 case RISCVISD::GORC: 5876 return RISCVISD::GORCW; 5877 } 5878 } 5879 5880 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5881 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5882 // otherwise be promoted to i64, making it difficult to select the 5883 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5884 // type i8/i16/i32 is lost. 5885 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5886 unsigned ExtOpc = ISD::ANY_EXTEND) { 5887 SDLoc DL(N); 5888 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5889 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5890 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5891 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5892 // ReplaceNodeResults requires we maintain the same type for the return value. 5893 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5894 } 5895 5896 // Converts the given 32-bit operation to a i64 operation with signed extension 5897 // semantic to reduce the signed extension instructions. 5898 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5899 SDLoc DL(N); 5900 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5901 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5902 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5903 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5904 DAG.getValueType(MVT::i32)); 5905 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5906 } 5907 5908 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5909 SmallVectorImpl<SDValue> &Results, 5910 SelectionDAG &DAG) const { 5911 SDLoc DL(N); 5912 switch (N->getOpcode()) { 5913 default: 5914 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5915 case ISD::STRICT_FP_TO_SINT: 5916 case ISD::STRICT_FP_TO_UINT: 5917 case ISD::FP_TO_SINT: 5918 case ISD::FP_TO_UINT: { 5919 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5920 "Unexpected custom legalisation"); 5921 bool IsStrict = N->isStrictFPOpcode(); 5922 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5923 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5924 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5925 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5926 TargetLowering::TypeSoftenFloat) { 5927 if (!isTypeLegal(Op0.getValueType())) 5928 return; 5929 if (IsStrict) { 5930 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 5931 : RISCVISD::STRICT_FCVT_WU_RV64; 5932 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 5933 SDValue Res = DAG.getNode( 5934 Opc, DL, VTs, N->getOperand(0), Op0, 5935 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 5936 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5937 Results.push_back(Res.getValue(1)); 5938 return; 5939 } 5940 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 5941 SDValue Res = 5942 DAG.getNode(Opc, DL, MVT::i64, Op0, 5943 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 5944 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5945 return; 5946 } 5947 // If the FP type needs to be softened, emit a library call using the 'si' 5948 // version. If we left it to default legalization we'd end up with 'di'. If 5949 // the FP type doesn't need to be softened just let generic type 5950 // legalization promote the result type. 5951 RTLIB::Libcall LC; 5952 if (IsSigned) 5953 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5954 else 5955 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5956 MakeLibCallOptions CallOptions; 5957 EVT OpVT = Op0.getValueType(); 5958 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5959 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5960 SDValue Result; 5961 std::tie(Result, Chain) = 5962 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5963 Results.push_back(Result); 5964 if (IsStrict) 5965 Results.push_back(Chain); 5966 break; 5967 } 5968 case ISD::READCYCLECOUNTER: { 5969 assert(!Subtarget.is64Bit() && 5970 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5971 5972 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5973 SDValue RCW = 5974 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5975 5976 Results.push_back( 5977 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5978 Results.push_back(RCW.getValue(2)); 5979 break; 5980 } 5981 case ISD::MUL: { 5982 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5983 unsigned XLen = Subtarget.getXLen(); 5984 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5985 if (Size > XLen) { 5986 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5987 SDValue LHS = N->getOperand(0); 5988 SDValue RHS = N->getOperand(1); 5989 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5990 5991 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5992 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5993 // We need exactly one side to be unsigned. 5994 if (LHSIsU == RHSIsU) 5995 return; 5996 5997 auto MakeMULPair = [&](SDValue S, SDValue U) { 5998 MVT XLenVT = Subtarget.getXLenVT(); 5999 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6000 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6001 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6002 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6003 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6004 }; 6005 6006 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6007 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6008 6009 // The other operand should be signed, but still prefer MULH when 6010 // possible. 6011 if (RHSIsU && LHSIsS && !RHSIsS) 6012 Results.push_back(MakeMULPair(LHS, RHS)); 6013 else if (LHSIsU && RHSIsS && !LHSIsS) 6014 Results.push_back(MakeMULPair(RHS, LHS)); 6015 6016 return; 6017 } 6018 LLVM_FALLTHROUGH; 6019 } 6020 case ISD::ADD: 6021 case ISD::SUB: 6022 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6023 "Unexpected custom legalisation"); 6024 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6025 break; 6026 case ISD::SHL: 6027 case ISD::SRA: 6028 case ISD::SRL: 6029 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6030 "Unexpected custom legalisation"); 6031 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6032 Results.push_back(customLegalizeToWOp(N, DAG)); 6033 break; 6034 } 6035 6036 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6037 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6038 // shift amount. 6039 if (N->getOpcode() == ISD::SHL) { 6040 SDLoc DL(N); 6041 SDValue NewOp0 = 6042 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6043 SDValue NewOp1 = 6044 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6045 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6046 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6047 DAG.getValueType(MVT::i32)); 6048 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6049 } 6050 6051 break; 6052 case ISD::ROTL: 6053 case ISD::ROTR: 6054 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6055 "Unexpected custom legalisation"); 6056 Results.push_back(customLegalizeToWOp(N, DAG)); 6057 break; 6058 case ISD::CTTZ: 6059 case ISD::CTTZ_ZERO_UNDEF: 6060 case ISD::CTLZ: 6061 case ISD::CTLZ_ZERO_UNDEF: { 6062 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6063 "Unexpected custom legalisation"); 6064 6065 SDValue NewOp0 = 6066 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6067 bool IsCTZ = 6068 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6069 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6070 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6071 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6072 return; 6073 } 6074 case ISD::SDIV: 6075 case ISD::UDIV: 6076 case ISD::UREM: { 6077 MVT VT = N->getSimpleValueType(0); 6078 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6079 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6080 "Unexpected custom legalisation"); 6081 // Don't promote division/remainder by constant since we should expand those 6082 // to multiply by magic constant. 6083 // FIXME: What if the expansion is disabled for minsize. 6084 if (N->getOperand(1).getOpcode() == ISD::Constant) 6085 return; 6086 6087 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6088 // the upper 32 bits. For other types we need to sign or zero extend 6089 // based on the opcode. 6090 unsigned ExtOpc = ISD::ANY_EXTEND; 6091 if (VT != MVT::i32) 6092 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6093 : ISD::ZERO_EXTEND; 6094 6095 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6096 break; 6097 } 6098 case ISD::UADDO: 6099 case ISD::USUBO: { 6100 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6101 "Unexpected custom legalisation"); 6102 bool IsAdd = N->getOpcode() == ISD::UADDO; 6103 // Create an ADDW or SUBW. 6104 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6105 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6106 SDValue Res = 6107 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6108 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6109 DAG.getValueType(MVT::i32)); 6110 6111 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6112 // Since the inputs are sign extended from i32, this is equivalent to 6113 // comparing the lower 32 bits. 6114 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6115 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6116 IsAdd ? ISD::SETULT : ISD::SETUGT); 6117 6118 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6119 Results.push_back(Overflow); 6120 return; 6121 } 6122 case ISD::UADDSAT: 6123 case ISD::USUBSAT: { 6124 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6125 "Unexpected custom legalisation"); 6126 if (Subtarget.hasStdExtZbb()) { 6127 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6128 // sign extend allows overflow of the lower 32 bits to be detected on 6129 // the promoted size. 6130 SDValue LHS = 6131 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6132 SDValue RHS = 6133 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6134 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6135 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6136 return; 6137 } 6138 6139 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6140 // promotion for UADDO/USUBO. 6141 Results.push_back(expandAddSubSat(N, DAG)); 6142 return; 6143 } 6144 case ISD::BITCAST: { 6145 EVT VT = N->getValueType(0); 6146 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6147 SDValue Op0 = N->getOperand(0); 6148 EVT Op0VT = Op0.getValueType(); 6149 MVT XLenVT = Subtarget.getXLenVT(); 6150 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6151 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6152 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6153 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6154 Subtarget.hasStdExtF()) { 6155 SDValue FPConv = 6156 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6157 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6158 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6159 isTypeLegal(Op0VT)) { 6160 // Custom-legalize bitcasts from fixed-length vector types to illegal 6161 // scalar types in order to improve codegen. Bitcast the vector to a 6162 // one-element vector type whose element type is the same as the result 6163 // type, and extract the first element. 6164 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6165 if (isTypeLegal(BVT)) { 6166 SDValue BVec = DAG.getBitcast(BVT, Op0); 6167 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6168 DAG.getConstant(0, DL, XLenVT))); 6169 } 6170 } 6171 break; 6172 } 6173 case RISCVISD::GREV: 6174 case RISCVISD::GORC: { 6175 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6176 "Unexpected custom legalisation"); 6177 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6178 // This is similar to customLegalizeToWOp, except that we pass the second 6179 // operand (a TargetConstant) straight through: it is already of type 6180 // XLenVT. 6181 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6182 SDValue NewOp0 = 6183 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6184 SDValue NewOp1 = 6185 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6186 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6187 // ReplaceNodeResults requires we maintain the same type for the return 6188 // value. 6189 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6190 break; 6191 } 6192 case RISCVISD::SHFL: { 6193 // There is no SHFLIW instruction, but we can just promote the operation. 6194 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6195 "Unexpected custom legalisation"); 6196 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6197 SDValue NewOp0 = 6198 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6199 SDValue NewOp1 = 6200 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6201 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6202 // ReplaceNodeResults requires we maintain the same type for the return 6203 // value. 6204 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6205 break; 6206 } 6207 case ISD::BSWAP: 6208 case ISD::BITREVERSE: { 6209 MVT VT = N->getSimpleValueType(0); 6210 MVT XLenVT = Subtarget.getXLenVT(); 6211 assert((VT == MVT::i8 || VT == MVT::i16 || 6212 (VT == MVT::i32 && Subtarget.is64Bit())) && 6213 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6214 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6215 unsigned Imm = VT.getSizeInBits() - 1; 6216 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6217 if (N->getOpcode() == ISD::BSWAP) 6218 Imm &= ~0x7U; 6219 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6220 SDValue GREVI = 6221 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6222 // ReplaceNodeResults requires we maintain the same type for the return 6223 // value. 6224 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6225 break; 6226 } 6227 case ISD::FSHL: 6228 case ISD::FSHR: { 6229 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6230 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6231 SDValue NewOp0 = 6232 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6233 SDValue NewOp1 = 6234 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6235 SDValue NewOp2 = 6236 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6237 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6238 // Mask the shift amount to 5 bits. 6239 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6240 DAG.getConstant(0x1f, DL, MVT::i64)); 6241 unsigned Opc = 6242 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 6243 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 6244 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6245 break; 6246 } 6247 case ISD::EXTRACT_VECTOR_ELT: { 6248 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6249 // type is illegal (currently only vXi64 RV32). 6250 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6251 // transferred to the destination register. We issue two of these from the 6252 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6253 // first element. 6254 SDValue Vec = N->getOperand(0); 6255 SDValue Idx = N->getOperand(1); 6256 6257 // The vector type hasn't been legalized yet so we can't issue target 6258 // specific nodes if it needs legalization. 6259 // FIXME: We would manually legalize if it's important. 6260 if (!isTypeLegal(Vec.getValueType())) 6261 return; 6262 6263 MVT VecVT = Vec.getSimpleValueType(); 6264 6265 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6266 VecVT.getVectorElementType() == MVT::i64 && 6267 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6268 6269 // If this is a fixed vector, we need to convert it to a scalable vector. 6270 MVT ContainerVT = VecVT; 6271 if (VecVT.isFixedLengthVector()) { 6272 ContainerVT = getContainerForFixedLengthVector(VecVT); 6273 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6274 } 6275 6276 MVT XLenVT = Subtarget.getXLenVT(); 6277 6278 // Use a VL of 1 to avoid processing more elements than we need. 6279 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6280 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6281 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6282 6283 // Unless the index is known to be 0, we must slide the vector down to get 6284 // the desired element into index 0. 6285 if (!isNullConstant(Idx)) { 6286 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6287 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6288 } 6289 6290 // Extract the lower XLEN bits of the correct vector element. 6291 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6292 6293 // To extract the upper XLEN bits of the vector element, shift the first 6294 // element right by 32 bits and re-extract the lower XLEN bits. 6295 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6296 DAG.getConstant(32, DL, XLenVT), VL); 6297 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6298 ThirtyTwoV, Mask, VL); 6299 6300 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6301 6302 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6303 break; 6304 } 6305 case ISD::INTRINSIC_WO_CHAIN: { 6306 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6307 switch (IntNo) { 6308 default: 6309 llvm_unreachable( 6310 "Don't know how to custom type legalize this intrinsic!"); 6311 case Intrinsic::riscv_grev: 6312 case Intrinsic::riscv_gorc: 6313 case Intrinsic::riscv_bcompress: 6314 case Intrinsic::riscv_bdecompress: 6315 case Intrinsic::riscv_bfp: { 6316 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6317 "Unexpected custom legalisation"); 6318 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6319 break; 6320 } 6321 case Intrinsic::riscv_orc_b: { 6322 // Lower to the GORCI encoding for orc.b with the operand extended. 6323 SDValue NewOp = 6324 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6325 // If Zbp is enabled, use GORCIW which will sign extend the result. 6326 unsigned Opc = 6327 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6328 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6329 DAG.getConstant(7, DL, MVT::i64)); 6330 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6331 return; 6332 } 6333 case Intrinsic::riscv_shfl: 6334 case Intrinsic::riscv_unshfl: { 6335 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6336 "Unexpected custom legalisation"); 6337 SDValue NewOp1 = 6338 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6339 SDValue NewOp2 = 6340 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6341 unsigned Opc = 6342 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6343 if (isa<ConstantSDNode>(N->getOperand(2))) { 6344 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6345 DAG.getConstant(0xf, DL, MVT::i64)); 6346 Opc = 6347 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6348 } 6349 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6350 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6351 break; 6352 } 6353 case Intrinsic::riscv_vmv_x_s: { 6354 EVT VT = N->getValueType(0); 6355 MVT XLenVT = Subtarget.getXLenVT(); 6356 if (VT.bitsLT(XLenVT)) { 6357 // Simple case just extract using vmv.x.s and truncate. 6358 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6359 Subtarget.getXLenVT(), N->getOperand(1)); 6360 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6361 return; 6362 } 6363 6364 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6365 "Unexpected custom legalization"); 6366 6367 // We need to do the move in two steps. 6368 SDValue Vec = N->getOperand(1); 6369 MVT VecVT = Vec.getSimpleValueType(); 6370 6371 // First extract the lower XLEN bits of the element. 6372 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6373 6374 // To extract the upper XLEN bits of the vector element, shift the first 6375 // element right by 32 bits and re-extract the lower XLEN bits. 6376 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6377 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6378 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6379 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6380 DAG.getConstant(32, DL, XLenVT), VL); 6381 SDValue LShr32 = 6382 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6383 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6384 6385 Results.push_back( 6386 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6387 break; 6388 } 6389 } 6390 break; 6391 } 6392 case ISD::VECREDUCE_ADD: 6393 case ISD::VECREDUCE_AND: 6394 case ISD::VECREDUCE_OR: 6395 case ISD::VECREDUCE_XOR: 6396 case ISD::VECREDUCE_SMAX: 6397 case ISD::VECREDUCE_UMAX: 6398 case ISD::VECREDUCE_SMIN: 6399 case ISD::VECREDUCE_UMIN: 6400 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6401 Results.push_back(V); 6402 break; 6403 case ISD::VP_REDUCE_ADD: 6404 case ISD::VP_REDUCE_AND: 6405 case ISD::VP_REDUCE_OR: 6406 case ISD::VP_REDUCE_XOR: 6407 case ISD::VP_REDUCE_SMAX: 6408 case ISD::VP_REDUCE_UMAX: 6409 case ISD::VP_REDUCE_SMIN: 6410 case ISD::VP_REDUCE_UMIN: 6411 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6412 Results.push_back(V); 6413 break; 6414 case ISD::FLT_ROUNDS_: { 6415 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6416 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6417 Results.push_back(Res.getValue(0)); 6418 Results.push_back(Res.getValue(1)); 6419 break; 6420 } 6421 } 6422 } 6423 6424 // A structure to hold one of the bit-manipulation patterns below. Together, a 6425 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6426 // (or (and (shl x, 1), 0xAAAAAAAA), 6427 // (and (srl x, 1), 0x55555555)) 6428 struct RISCVBitmanipPat { 6429 SDValue Op; 6430 unsigned ShAmt; 6431 bool IsSHL; 6432 6433 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6434 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6435 } 6436 }; 6437 6438 // Matches patterns of the form 6439 // (and (shl x, C2), (C1 << C2)) 6440 // (and (srl x, C2), C1) 6441 // (shl (and x, C1), C2) 6442 // (srl (and x, (C1 << C2)), C2) 6443 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6444 // The expected masks for each shift amount are specified in BitmanipMasks where 6445 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6446 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6447 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6448 // XLen is 64. 6449 static Optional<RISCVBitmanipPat> 6450 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6451 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6452 "Unexpected number of masks"); 6453 Optional<uint64_t> Mask; 6454 // Optionally consume a mask around the shift operation. 6455 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6456 Mask = Op.getConstantOperandVal(1); 6457 Op = Op.getOperand(0); 6458 } 6459 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6460 return None; 6461 bool IsSHL = Op.getOpcode() == ISD::SHL; 6462 6463 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6464 return None; 6465 uint64_t ShAmt = Op.getConstantOperandVal(1); 6466 6467 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6468 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6469 return None; 6470 // If we don't have enough masks for 64 bit, then we must be trying to 6471 // match SHFL so we're only allowed to shift 1/4 of the width. 6472 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6473 return None; 6474 6475 SDValue Src = Op.getOperand(0); 6476 6477 // The expected mask is shifted left when the AND is found around SHL 6478 // patterns. 6479 // ((x >> 1) & 0x55555555) 6480 // ((x << 1) & 0xAAAAAAAA) 6481 bool SHLExpMask = IsSHL; 6482 6483 if (!Mask) { 6484 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6485 // the mask is all ones: consume that now. 6486 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6487 Mask = Src.getConstantOperandVal(1); 6488 Src = Src.getOperand(0); 6489 // The expected mask is now in fact shifted left for SRL, so reverse the 6490 // decision. 6491 // ((x & 0xAAAAAAAA) >> 1) 6492 // ((x & 0x55555555) << 1) 6493 SHLExpMask = !SHLExpMask; 6494 } else { 6495 // Use a default shifted mask of all-ones if there's no AND, truncated 6496 // down to the expected width. This simplifies the logic later on. 6497 Mask = maskTrailingOnes<uint64_t>(Width); 6498 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6499 } 6500 } 6501 6502 unsigned MaskIdx = Log2_32(ShAmt); 6503 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6504 6505 if (SHLExpMask) 6506 ExpMask <<= ShAmt; 6507 6508 if (Mask != ExpMask) 6509 return None; 6510 6511 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6512 } 6513 6514 // Matches any of the following bit-manipulation patterns: 6515 // (and (shl x, 1), (0x55555555 << 1)) 6516 // (and (srl x, 1), 0x55555555) 6517 // (shl (and x, 0x55555555), 1) 6518 // (srl (and x, (0x55555555 << 1)), 1) 6519 // where the shift amount and mask may vary thus: 6520 // [1] = 0x55555555 / 0xAAAAAAAA 6521 // [2] = 0x33333333 / 0xCCCCCCCC 6522 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6523 // [8] = 0x00FF00FF / 0xFF00FF00 6524 // [16] = 0x0000FFFF / 0xFFFFFFFF 6525 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6526 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6527 // These are the unshifted masks which we use to match bit-manipulation 6528 // patterns. They may be shifted left in certain circumstances. 6529 static const uint64_t BitmanipMasks[] = { 6530 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6531 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6532 6533 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6534 } 6535 6536 // Match the following pattern as a GREVI(W) operation 6537 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6538 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6539 const RISCVSubtarget &Subtarget) { 6540 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6541 EVT VT = Op.getValueType(); 6542 6543 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6544 auto LHS = matchGREVIPat(Op.getOperand(0)); 6545 auto RHS = matchGREVIPat(Op.getOperand(1)); 6546 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6547 SDLoc DL(Op); 6548 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6549 DAG.getConstant(LHS->ShAmt, DL, VT)); 6550 } 6551 } 6552 return SDValue(); 6553 } 6554 6555 // Matches any the following pattern as a GORCI(W) operation 6556 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6557 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6558 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6559 // Note that with the variant of 3., 6560 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6561 // the inner pattern will first be matched as GREVI and then the outer 6562 // pattern will be matched to GORC via the first rule above. 6563 // 4. (or (rotl/rotr x, bitwidth/2), x) 6564 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6565 const RISCVSubtarget &Subtarget) { 6566 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6567 EVT VT = Op.getValueType(); 6568 6569 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6570 SDLoc DL(Op); 6571 SDValue Op0 = Op.getOperand(0); 6572 SDValue Op1 = Op.getOperand(1); 6573 6574 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6575 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6576 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6577 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6578 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6579 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6580 if ((Reverse.getOpcode() == ISD::ROTL || 6581 Reverse.getOpcode() == ISD::ROTR) && 6582 Reverse.getOperand(0) == X && 6583 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6584 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6585 if (RotAmt == (VT.getSizeInBits() / 2)) 6586 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6587 DAG.getConstant(RotAmt, DL, VT)); 6588 } 6589 return SDValue(); 6590 }; 6591 6592 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6593 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6594 return V; 6595 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6596 return V; 6597 6598 // OR is commutable so canonicalize its OR operand to the left 6599 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6600 std::swap(Op0, Op1); 6601 if (Op0.getOpcode() != ISD::OR) 6602 return SDValue(); 6603 SDValue OrOp0 = Op0.getOperand(0); 6604 SDValue OrOp1 = Op0.getOperand(1); 6605 auto LHS = matchGREVIPat(OrOp0); 6606 // OR is commutable so swap the operands and try again: x might have been 6607 // on the left 6608 if (!LHS) { 6609 std::swap(OrOp0, OrOp1); 6610 LHS = matchGREVIPat(OrOp0); 6611 } 6612 auto RHS = matchGREVIPat(Op1); 6613 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6614 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6615 DAG.getConstant(LHS->ShAmt, DL, VT)); 6616 } 6617 } 6618 return SDValue(); 6619 } 6620 6621 // Matches any of the following bit-manipulation patterns: 6622 // (and (shl x, 1), (0x22222222 << 1)) 6623 // (and (srl x, 1), 0x22222222) 6624 // (shl (and x, 0x22222222), 1) 6625 // (srl (and x, (0x22222222 << 1)), 1) 6626 // where the shift amount and mask may vary thus: 6627 // [1] = 0x22222222 / 0x44444444 6628 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6629 // [4] = 0x00F000F0 / 0x0F000F00 6630 // [8] = 0x0000FF00 / 0x00FF0000 6631 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6632 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6633 // These are the unshifted masks which we use to match bit-manipulation 6634 // patterns. They may be shifted left in certain circumstances. 6635 static const uint64_t BitmanipMasks[] = { 6636 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6637 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6638 6639 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6640 } 6641 6642 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6643 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6644 const RISCVSubtarget &Subtarget) { 6645 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6646 EVT VT = Op.getValueType(); 6647 6648 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6649 return SDValue(); 6650 6651 SDValue Op0 = Op.getOperand(0); 6652 SDValue Op1 = Op.getOperand(1); 6653 6654 // Or is commutable so canonicalize the second OR to the LHS. 6655 if (Op0.getOpcode() != ISD::OR) 6656 std::swap(Op0, Op1); 6657 if (Op0.getOpcode() != ISD::OR) 6658 return SDValue(); 6659 6660 // We found an inner OR, so our operands are the operands of the inner OR 6661 // and the other operand of the outer OR. 6662 SDValue A = Op0.getOperand(0); 6663 SDValue B = Op0.getOperand(1); 6664 SDValue C = Op1; 6665 6666 auto Match1 = matchSHFLPat(A); 6667 auto Match2 = matchSHFLPat(B); 6668 6669 // If neither matched, we failed. 6670 if (!Match1 && !Match2) 6671 return SDValue(); 6672 6673 // We had at least one match. if one failed, try the remaining C operand. 6674 if (!Match1) { 6675 std::swap(A, C); 6676 Match1 = matchSHFLPat(A); 6677 if (!Match1) 6678 return SDValue(); 6679 } else if (!Match2) { 6680 std::swap(B, C); 6681 Match2 = matchSHFLPat(B); 6682 if (!Match2) 6683 return SDValue(); 6684 } 6685 assert(Match1 && Match2); 6686 6687 // Make sure our matches pair up. 6688 if (!Match1->formsPairWith(*Match2)) 6689 return SDValue(); 6690 6691 // All the remains is to make sure C is an AND with the same input, that masks 6692 // out the bits that are being shuffled. 6693 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6694 C.getOperand(0) != Match1->Op) 6695 return SDValue(); 6696 6697 uint64_t Mask = C.getConstantOperandVal(1); 6698 6699 static const uint64_t BitmanipMasks[] = { 6700 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6701 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6702 }; 6703 6704 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6705 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6706 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6707 6708 if (Mask != ExpMask) 6709 return SDValue(); 6710 6711 SDLoc DL(Op); 6712 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6713 DAG.getConstant(Match1->ShAmt, DL, VT)); 6714 } 6715 6716 // Optimize (add (shl x, c0), (shl y, c1)) -> 6717 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6718 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6719 const RISCVSubtarget &Subtarget) { 6720 // Perform this optimization only in the zba extension. 6721 if (!Subtarget.hasStdExtZba()) 6722 return SDValue(); 6723 6724 // Skip for vector types and larger types. 6725 EVT VT = N->getValueType(0); 6726 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6727 return SDValue(); 6728 6729 // The two operand nodes must be SHL and have no other use. 6730 SDValue N0 = N->getOperand(0); 6731 SDValue N1 = N->getOperand(1); 6732 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6733 !N0->hasOneUse() || !N1->hasOneUse()) 6734 return SDValue(); 6735 6736 // Check c0 and c1. 6737 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6738 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6739 if (!N0C || !N1C) 6740 return SDValue(); 6741 int64_t C0 = N0C->getSExtValue(); 6742 int64_t C1 = N1C->getSExtValue(); 6743 if (C0 <= 0 || C1 <= 0) 6744 return SDValue(); 6745 6746 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6747 int64_t Bits = std::min(C0, C1); 6748 int64_t Diff = std::abs(C0 - C1); 6749 if (Diff != 1 && Diff != 2 && Diff != 3) 6750 return SDValue(); 6751 6752 // Build nodes. 6753 SDLoc DL(N); 6754 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6755 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6756 SDValue NA0 = 6757 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6758 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6759 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6760 } 6761 6762 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6763 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6764 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6765 // not undo itself, but they are redundant. 6766 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6767 SDValue Src = N->getOperand(0); 6768 6769 if (Src.getOpcode() != N->getOpcode()) 6770 return SDValue(); 6771 6772 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6773 !isa<ConstantSDNode>(Src.getOperand(1))) 6774 return SDValue(); 6775 6776 unsigned ShAmt1 = N->getConstantOperandVal(1); 6777 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6778 Src = Src.getOperand(0); 6779 6780 unsigned CombinedShAmt; 6781 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6782 CombinedShAmt = ShAmt1 | ShAmt2; 6783 else 6784 CombinedShAmt = ShAmt1 ^ ShAmt2; 6785 6786 if (CombinedShAmt == 0) 6787 return Src; 6788 6789 SDLoc DL(N); 6790 return DAG.getNode( 6791 N->getOpcode(), DL, N->getValueType(0), Src, 6792 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6793 } 6794 6795 // Combine a constant select operand into its use: 6796 // 6797 // (and (select cond, -1, c), x) 6798 // -> (select cond, x, (and x, c)) [AllOnes=1] 6799 // (or (select cond, 0, c), x) 6800 // -> (select cond, x, (or x, c)) [AllOnes=0] 6801 // (xor (select cond, 0, c), x) 6802 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6803 // (add (select cond, 0, c), x) 6804 // -> (select cond, x, (add x, c)) [AllOnes=0] 6805 // (sub x, (select cond, 0, c)) 6806 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6807 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6808 SelectionDAG &DAG, bool AllOnes) { 6809 EVT VT = N->getValueType(0); 6810 6811 // Skip vectors. 6812 if (VT.isVector()) 6813 return SDValue(); 6814 6815 if ((Slct.getOpcode() != ISD::SELECT && 6816 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6817 !Slct.hasOneUse()) 6818 return SDValue(); 6819 6820 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6821 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6822 }; 6823 6824 bool SwapSelectOps; 6825 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6826 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6827 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6828 SDValue NonConstantVal; 6829 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6830 SwapSelectOps = false; 6831 NonConstantVal = FalseVal; 6832 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6833 SwapSelectOps = true; 6834 NonConstantVal = TrueVal; 6835 } else 6836 return SDValue(); 6837 6838 // Slct is now know to be the desired identity constant when CC is true. 6839 TrueVal = OtherOp; 6840 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6841 // Unless SwapSelectOps says the condition should be false. 6842 if (SwapSelectOps) 6843 std::swap(TrueVal, FalseVal); 6844 6845 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6846 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6847 {Slct.getOperand(0), Slct.getOperand(1), 6848 Slct.getOperand(2), TrueVal, FalseVal}); 6849 6850 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6851 {Slct.getOperand(0), TrueVal, FalseVal}); 6852 } 6853 6854 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6855 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6856 bool AllOnes) { 6857 SDValue N0 = N->getOperand(0); 6858 SDValue N1 = N->getOperand(1); 6859 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6860 return Result; 6861 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6862 return Result; 6863 return SDValue(); 6864 } 6865 6866 // Transform (add (mul x, c0), c1) -> 6867 // (add (mul (add x, c1/c0), c0), c1%c0). 6868 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 6869 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 6870 // to an infinite loop in DAGCombine if transformed. 6871 // Or transform (add (mul x, c0), c1) -> 6872 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 6873 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 6874 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 6875 // lead to an infinite loop in DAGCombine if transformed. 6876 // Or transform (add (mul x, c0), c1) -> 6877 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 6878 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 6879 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 6880 // lead to an infinite loop in DAGCombine if transformed. 6881 // Or transform (add (mul x, c0), c1) -> 6882 // (mul (add x, c1/c0), c0). 6883 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6884 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6885 const RISCVSubtarget &Subtarget) { 6886 // Skip for vector types and larger types. 6887 EVT VT = N->getValueType(0); 6888 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6889 return SDValue(); 6890 // The first operand node must be a MUL and has no other use. 6891 SDValue N0 = N->getOperand(0); 6892 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6893 return SDValue(); 6894 // Check if c0 and c1 match above conditions. 6895 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6896 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6897 if (!N0C || !N1C) 6898 return SDValue(); 6899 int64_t C0 = N0C->getSExtValue(); 6900 int64_t C1 = N1C->getSExtValue(); 6901 int64_t CA, CB; 6902 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 6903 return SDValue(); 6904 // Search for proper CA (non-zero) and CB that both are simm12. 6905 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 6906 !isInt<12>(C0 * (C1 / C0))) { 6907 CA = C1 / C0; 6908 CB = C1 % C0; 6909 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 6910 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 6911 CA = C1 / C0 + 1; 6912 CB = C1 % C0 - C0; 6913 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 6914 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 6915 CA = C1 / C0 - 1; 6916 CB = C1 % C0 + C0; 6917 } else 6918 return SDValue(); 6919 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6920 SDLoc DL(N); 6921 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6922 DAG.getConstant(CA, DL, VT)); 6923 SDValue New1 = 6924 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6925 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 6926 } 6927 6928 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6929 const RISCVSubtarget &Subtarget) { 6930 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6931 return V; 6932 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6933 return V; 6934 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6935 // (select lhs, rhs, cc, x, (add x, y)) 6936 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6937 } 6938 6939 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6940 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6941 // (select lhs, rhs, cc, x, (sub x, y)) 6942 SDValue N0 = N->getOperand(0); 6943 SDValue N1 = N->getOperand(1); 6944 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6945 } 6946 6947 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6948 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6949 // (select lhs, rhs, cc, x, (and x, y)) 6950 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6951 } 6952 6953 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6954 const RISCVSubtarget &Subtarget) { 6955 if (Subtarget.hasStdExtZbp()) { 6956 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6957 return GREV; 6958 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6959 return GORC; 6960 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6961 return SHFL; 6962 } 6963 6964 // fold (or (select cond, 0, y), x) -> 6965 // (select cond, x, (or x, y)) 6966 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6967 } 6968 6969 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6970 // fold (xor (select cond, 0, y), x) -> 6971 // (select cond, x, (xor x, y)) 6972 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6973 } 6974 6975 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6976 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6977 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6978 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6979 // ADDW/SUBW/MULW. 6980 static SDValue performANY_EXTENDCombine(SDNode *N, 6981 TargetLowering::DAGCombinerInfo &DCI, 6982 const RISCVSubtarget &Subtarget) { 6983 if (!Subtarget.is64Bit()) 6984 return SDValue(); 6985 6986 SelectionDAG &DAG = DCI.DAG; 6987 6988 SDValue Src = N->getOperand(0); 6989 EVT VT = N->getValueType(0); 6990 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6991 return SDValue(); 6992 6993 // The opcode must be one that can implicitly sign_extend. 6994 // FIXME: Additional opcodes. 6995 switch (Src.getOpcode()) { 6996 default: 6997 return SDValue(); 6998 case ISD::MUL: 6999 if (!Subtarget.hasStdExtM()) 7000 return SDValue(); 7001 LLVM_FALLTHROUGH; 7002 case ISD::ADD: 7003 case ISD::SUB: 7004 break; 7005 } 7006 7007 // Only handle cases where the result is used by a CopyToReg. That likely 7008 // means the value is a liveout of the basic block. This helps prevent 7009 // infinite combine loops like PR51206. 7010 if (none_of(N->uses(), 7011 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7012 return SDValue(); 7013 7014 SmallVector<SDNode *, 4> SetCCs; 7015 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7016 UE = Src.getNode()->use_end(); 7017 UI != UE; ++UI) { 7018 SDNode *User = *UI; 7019 if (User == N) 7020 continue; 7021 if (UI.getUse().getResNo() != Src.getResNo()) 7022 continue; 7023 // All i32 setccs are legalized by sign extending operands. 7024 if (User->getOpcode() == ISD::SETCC) { 7025 SetCCs.push_back(User); 7026 continue; 7027 } 7028 // We don't know if we can extend this user. 7029 break; 7030 } 7031 7032 // If we don't have any SetCCs, this isn't worthwhile. 7033 if (SetCCs.empty()) 7034 return SDValue(); 7035 7036 SDLoc DL(N); 7037 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7038 DCI.CombineTo(N, SExt); 7039 7040 // Promote all the setccs. 7041 for (SDNode *SetCC : SetCCs) { 7042 SmallVector<SDValue, 4> Ops; 7043 7044 for (unsigned j = 0; j != 2; ++j) { 7045 SDValue SOp = SetCC->getOperand(j); 7046 if (SOp == Src) 7047 Ops.push_back(SExt); 7048 else 7049 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7050 } 7051 7052 Ops.push_back(SetCC->getOperand(2)); 7053 DCI.CombineTo(SetCC, 7054 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7055 } 7056 return SDValue(N, 0); 7057 } 7058 7059 // Try to form VWMUL or VWMULU. 7060 // FIXME: Support VWMULSU. 7061 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 7062 SelectionDAG &DAG) { 7063 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7064 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7065 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7066 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7067 return SDValue(); 7068 7069 SDValue Mask = N->getOperand(2); 7070 SDValue VL = N->getOperand(3); 7071 7072 // Make sure the mask and VL match. 7073 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7074 return SDValue(); 7075 7076 MVT VT = N->getSimpleValueType(0); 7077 7078 // Determine the narrow size for a widening multiply. 7079 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7080 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7081 VT.getVectorElementCount()); 7082 7083 SDLoc DL(N); 7084 7085 // See if the other operand is the same opcode. 7086 if (Op0.getOpcode() == Op1.getOpcode()) { 7087 if (!Op1.hasOneUse()) 7088 return SDValue(); 7089 7090 // Make sure the mask and VL match. 7091 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7092 return SDValue(); 7093 7094 Op1 = Op1.getOperand(0); 7095 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7096 // The operand is a splat of a scalar. 7097 7098 // The VL must be the same. 7099 if (Op1.getOperand(1) != VL) 7100 return SDValue(); 7101 7102 // Get the scalar value. 7103 Op1 = Op1.getOperand(0); 7104 7105 // See if have enough sign bits or zero bits in the scalar to use a 7106 // widening multiply by splatting to smaller element size. 7107 unsigned EltBits = VT.getScalarSizeInBits(); 7108 unsigned ScalarBits = Op1.getValueSizeInBits(); 7109 // Make sure we're getting all element bits from the scalar register. 7110 // FIXME: Support implicit sign extension of vmv.v.x? 7111 if (ScalarBits < EltBits) 7112 return SDValue(); 7113 7114 if (IsSignExt) { 7115 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 7116 return SDValue(); 7117 } else { 7118 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7119 if (!DAG.MaskedValueIsZero(Op1, Mask)) 7120 return SDValue(); 7121 } 7122 7123 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 7124 } else 7125 return SDValue(); 7126 7127 Op0 = Op0.getOperand(0); 7128 7129 // Re-introduce narrower extends if needed. 7130 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7131 if (Op0.getValueType() != NarrowVT) 7132 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7133 if (Op1.getValueType() != NarrowVT) 7134 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7135 7136 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7137 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7138 } 7139 7140 // Fold 7141 // (fp_to_int (froundeven X)) -> fcvt X, rne 7142 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7143 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7144 // (fp_to_int (fceil X)) -> fcvt X, rup 7145 // (fp_to_int (fround X)) -> fcvt X, rmm 7146 // FIXME: We should also do this for fp_to_int_sat. 7147 static SDValue performFP_TO_INTCombine(SDNode *N, 7148 TargetLowering::DAGCombinerInfo &DCI, 7149 const RISCVSubtarget &Subtarget) { 7150 SelectionDAG &DAG = DCI.DAG; 7151 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7152 MVT XLenVT = Subtarget.getXLenVT(); 7153 7154 // Only handle XLen or i32 types. Other types narrower than XLen will 7155 // eventually be legalized to XLenVT. 7156 EVT VT = N->getValueType(0); 7157 if (VT != MVT::i32 && VT != XLenVT) 7158 return SDValue(); 7159 7160 SDValue Src = N->getOperand(0); 7161 7162 // Ensure the FP type is also legal. 7163 if (!TLI.isTypeLegal(Src.getValueType())) 7164 return SDValue(); 7165 7166 // Don't do this for f16 with Zfhmin and not Zfh. 7167 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7168 return SDValue(); 7169 7170 RISCVFPRndMode::RoundingMode FRM; 7171 switch (Src->getOpcode()) { 7172 default: 7173 return SDValue(); 7174 case ISD::FROUNDEVEN: FRM = RISCVFPRndMode::RNE; break; 7175 case ISD::FTRUNC: FRM = RISCVFPRndMode::RTZ; break; 7176 case ISD::FFLOOR: FRM = RISCVFPRndMode::RDN; break; 7177 case ISD::FCEIL: FRM = RISCVFPRndMode::RUP; break; 7178 case ISD::FROUND: FRM = RISCVFPRndMode::RMM; break; 7179 } 7180 7181 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7182 7183 unsigned Opc; 7184 if (VT == XLenVT) 7185 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7186 else 7187 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7188 7189 SDLoc DL(N); 7190 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7191 DAG.getTargetConstant(FRM, DL, XLenVT)); 7192 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7193 } 7194 7195 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7196 DAGCombinerInfo &DCI) const { 7197 SelectionDAG &DAG = DCI.DAG; 7198 7199 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7200 // bits are demanded. N will be added to the Worklist if it was not deleted. 7201 // Caller should return SDValue(N, 0) if this returns true. 7202 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7203 SDValue Op = N->getOperand(OpNo); 7204 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7205 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7206 return false; 7207 7208 if (N->getOpcode() != ISD::DELETED_NODE) 7209 DCI.AddToWorklist(N); 7210 return true; 7211 }; 7212 7213 switch (N->getOpcode()) { 7214 default: 7215 break; 7216 case RISCVISD::SplitF64: { 7217 SDValue Op0 = N->getOperand(0); 7218 // If the input to SplitF64 is just BuildPairF64 then the operation is 7219 // redundant. Instead, use BuildPairF64's operands directly. 7220 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7221 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7222 7223 SDLoc DL(N); 7224 7225 // It's cheaper to materialise two 32-bit integers than to load a double 7226 // from the constant pool and transfer it to integer registers through the 7227 // stack. 7228 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7229 APInt V = C->getValueAPF().bitcastToAPInt(); 7230 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 7231 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 7232 return DCI.CombineTo(N, Lo, Hi); 7233 } 7234 7235 // This is a target-specific version of a DAGCombine performed in 7236 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7237 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7238 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7239 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7240 !Op0.getNode()->hasOneUse()) 7241 break; 7242 SDValue NewSplitF64 = 7243 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 7244 Op0.getOperand(0)); 7245 SDValue Lo = NewSplitF64.getValue(0); 7246 SDValue Hi = NewSplitF64.getValue(1); 7247 APInt SignBit = APInt::getSignMask(32); 7248 if (Op0.getOpcode() == ISD::FNEG) { 7249 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 7250 DAG.getConstant(SignBit, DL, MVT::i32)); 7251 return DCI.CombineTo(N, Lo, NewHi); 7252 } 7253 assert(Op0.getOpcode() == ISD::FABS); 7254 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 7255 DAG.getConstant(~SignBit, DL, MVT::i32)); 7256 return DCI.CombineTo(N, Lo, NewHi); 7257 } 7258 case RISCVISD::SLLW: 7259 case RISCVISD::SRAW: 7260 case RISCVISD::SRLW: 7261 case RISCVISD::ROLW: 7262 case RISCVISD::RORW: { 7263 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7264 if (SimplifyDemandedLowBitsHelper(0, 32) || 7265 SimplifyDemandedLowBitsHelper(1, 5)) 7266 return SDValue(N, 0); 7267 break; 7268 } 7269 case RISCVISD::CLZW: 7270 case RISCVISD::CTZW: { 7271 // Only the lower 32 bits of the first operand are read 7272 if (SimplifyDemandedLowBitsHelper(0, 32)) 7273 return SDValue(N, 0); 7274 break; 7275 } 7276 case RISCVISD::FSL: 7277 case RISCVISD::FSR: { 7278 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 7279 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 7280 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7281 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 7282 return SDValue(N, 0); 7283 break; 7284 } 7285 case RISCVISD::FSLW: 7286 case RISCVISD::FSRW: { 7287 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 7288 // read. 7289 if (SimplifyDemandedLowBitsHelper(0, 32) || 7290 SimplifyDemandedLowBitsHelper(1, 32) || 7291 SimplifyDemandedLowBitsHelper(2, 6)) 7292 return SDValue(N, 0); 7293 break; 7294 } 7295 case RISCVISD::GREV: 7296 case RISCVISD::GORC: { 7297 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 7298 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7299 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7300 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 7301 return SDValue(N, 0); 7302 7303 return combineGREVI_GORCI(N, DAG); 7304 } 7305 case RISCVISD::GREVW: 7306 case RISCVISD::GORCW: { 7307 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7308 if (SimplifyDemandedLowBitsHelper(0, 32) || 7309 SimplifyDemandedLowBitsHelper(1, 5)) 7310 return SDValue(N, 0); 7311 7312 return combineGREVI_GORCI(N, DAG); 7313 } 7314 case RISCVISD::SHFL: 7315 case RISCVISD::UNSHFL: { 7316 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 7317 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7318 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7319 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 7320 return SDValue(N, 0); 7321 7322 break; 7323 } 7324 case RISCVISD::SHFLW: 7325 case RISCVISD::UNSHFLW: { 7326 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 7327 SDValue LHS = N->getOperand(0); 7328 SDValue RHS = N->getOperand(1); 7329 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 7330 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 7331 if (SimplifyDemandedLowBitsHelper(0, 32) || 7332 SimplifyDemandedLowBitsHelper(1, 4)) 7333 return SDValue(N, 0); 7334 7335 break; 7336 } 7337 case RISCVISD::BCOMPRESSW: 7338 case RISCVISD::BDECOMPRESSW: { 7339 // Only the lower 32 bits of LHS and RHS are read. 7340 if (SimplifyDemandedLowBitsHelper(0, 32) || 7341 SimplifyDemandedLowBitsHelper(1, 32)) 7342 return SDValue(N, 0); 7343 7344 break; 7345 } 7346 case RISCVISD::FMV_X_ANYEXTH: 7347 case RISCVISD::FMV_X_ANYEXTW_RV64: { 7348 SDLoc DL(N); 7349 SDValue Op0 = N->getOperand(0); 7350 MVT VT = N->getSimpleValueType(0); 7351 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 7352 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 7353 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 7354 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 7355 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 7356 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7357 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 7358 assert(Op0.getOperand(0).getValueType() == VT && 7359 "Unexpected value type!"); 7360 return Op0.getOperand(0); 7361 } 7362 7363 // This is a target-specific version of a DAGCombine performed in 7364 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7365 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7366 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7367 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7368 !Op0.getNode()->hasOneUse()) 7369 break; 7370 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 7371 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 7372 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7373 if (Op0.getOpcode() == ISD::FNEG) 7374 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7375 DAG.getConstant(SignBit, DL, VT)); 7376 7377 assert(Op0.getOpcode() == ISD::FABS); 7378 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7379 DAG.getConstant(~SignBit, DL, VT)); 7380 } 7381 case ISD::ADD: 7382 return performADDCombine(N, DAG, Subtarget); 7383 case ISD::SUB: 7384 return performSUBCombine(N, DAG); 7385 case ISD::AND: 7386 return performANDCombine(N, DAG); 7387 case ISD::OR: 7388 return performORCombine(N, DAG, Subtarget); 7389 case ISD::XOR: 7390 return performXORCombine(N, DAG); 7391 case ISD::ANY_EXTEND: 7392 return performANY_EXTENDCombine(N, DCI, Subtarget); 7393 case ISD::ZERO_EXTEND: 7394 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7395 // type legalization. This is safe because fp_to_uint produces poison if 7396 // it overflows. 7397 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 7398 SDValue Src = N->getOperand(0); 7399 if (Src.getOpcode() == ISD::FP_TO_UINT && 7400 isTypeLegal(Src.getOperand(0).getValueType())) 7401 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7402 Src.getOperand(0)); 7403 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 7404 isTypeLegal(Src.getOperand(1).getValueType())) { 7405 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7406 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 7407 Src.getOperand(0), Src.getOperand(1)); 7408 DCI.CombineTo(N, Res); 7409 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 7410 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 7411 return SDValue(N, 0); // Return N so it doesn't get rechecked. 7412 } 7413 } 7414 return SDValue(); 7415 case RISCVISD::SELECT_CC: { 7416 // Transform 7417 SDValue LHS = N->getOperand(0); 7418 SDValue RHS = N->getOperand(1); 7419 SDValue TrueV = N->getOperand(3); 7420 SDValue FalseV = N->getOperand(4); 7421 7422 // If the True and False values are the same, we don't need a select_cc. 7423 if (TrueV == FalseV) 7424 return TrueV; 7425 7426 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7427 if (!ISD::isIntEqualitySetCC(CCVal)) 7428 break; 7429 7430 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7431 // (select_cc X, Y, lt, trueV, falseV) 7432 // Sometimes the setcc is introduced after select_cc has been formed. 7433 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7434 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7435 // If we're looking for eq 0 instead of ne 0, we need to invert the 7436 // condition. 7437 bool Invert = CCVal == ISD::SETEQ; 7438 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7439 if (Invert) 7440 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7441 7442 SDLoc DL(N); 7443 RHS = LHS.getOperand(1); 7444 LHS = LHS.getOperand(0); 7445 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7446 7447 SDValue TargetCC = DAG.getCondCode(CCVal); 7448 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7449 {LHS, RHS, TargetCC, TrueV, FalseV}); 7450 } 7451 7452 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7453 // (select_cc X, Y, eq/ne, trueV, falseV) 7454 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7455 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7456 {LHS.getOperand(0), LHS.getOperand(1), 7457 N->getOperand(2), TrueV, FalseV}); 7458 // (select_cc X, 1, setne, trueV, falseV) -> 7459 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7460 // This can occur when legalizing some floating point comparisons. 7461 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7462 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7463 SDLoc DL(N); 7464 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7465 SDValue TargetCC = DAG.getCondCode(CCVal); 7466 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7467 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7468 {LHS, RHS, TargetCC, TrueV, FalseV}); 7469 } 7470 7471 break; 7472 } 7473 case RISCVISD::BR_CC: { 7474 SDValue LHS = N->getOperand(1); 7475 SDValue RHS = N->getOperand(2); 7476 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7477 if (!ISD::isIntEqualitySetCC(CCVal)) 7478 break; 7479 7480 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7481 // (br_cc X, Y, lt, dest) 7482 // Sometimes the setcc is introduced after br_cc has been formed. 7483 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7484 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7485 // If we're looking for eq 0 instead of ne 0, we need to invert the 7486 // condition. 7487 bool Invert = CCVal == ISD::SETEQ; 7488 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7489 if (Invert) 7490 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7491 7492 SDLoc DL(N); 7493 RHS = LHS.getOperand(1); 7494 LHS = LHS.getOperand(0); 7495 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7496 7497 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7498 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7499 N->getOperand(4)); 7500 } 7501 7502 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7503 // (br_cc X, Y, eq/ne, trueV, falseV) 7504 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7505 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7506 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7507 N->getOperand(3), N->getOperand(4)); 7508 7509 // (br_cc X, 1, setne, br_cc) -> 7510 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7511 // This can occur when legalizing some floating point comparisons. 7512 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7513 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7514 SDLoc DL(N); 7515 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7516 SDValue TargetCC = DAG.getCondCode(CCVal); 7517 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7518 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7519 N->getOperand(0), LHS, RHS, TargetCC, 7520 N->getOperand(4)); 7521 } 7522 break; 7523 } 7524 case ISD::FP_TO_SINT: 7525 case ISD::FP_TO_UINT: 7526 return performFP_TO_INTCombine(N, DCI, Subtarget); 7527 case ISD::FCOPYSIGN: { 7528 EVT VT = N->getValueType(0); 7529 if (!VT.isVector()) 7530 break; 7531 // There is a form of VFSGNJ which injects the negated sign of its second 7532 // operand. Try and bubble any FNEG up after the extend/round to produce 7533 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7534 // TRUNC=1. 7535 SDValue In2 = N->getOperand(1); 7536 // Avoid cases where the extend/round has multiple uses, as duplicating 7537 // those is typically more expensive than removing a fneg. 7538 if (!In2.hasOneUse()) 7539 break; 7540 if (In2.getOpcode() != ISD::FP_EXTEND && 7541 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7542 break; 7543 In2 = In2.getOperand(0); 7544 if (In2.getOpcode() != ISD::FNEG) 7545 break; 7546 SDLoc DL(N); 7547 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7548 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7549 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7550 } 7551 case ISD::MGATHER: 7552 case ISD::MSCATTER: 7553 case ISD::VP_GATHER: 7554 case ISD::VP_SCATTER: { 7555 if (!DCI.isBeforeLegalize()) 7556 break; 7557 SDValue Index, ScaleOp; 7558 bool IsIndexScaled = false; 7559 bool IsIndexSigned = false; 7560 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7561 Index = VPGSN->getIndex(); 7562 ScaleOp = VPGSN->getScale(); 7563 IsIndexScaled = VPGSN->isIndexScaled(); 7564 IsIndexSigned = VPGSN->isIndexSigned(); 7565 } else { 7566 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7567 Index = MGSN->getIndex(); 7568 ScaleOp = MGSN->getScale(); 7569 IsIndexScaled = MGSN->isIndexScaled(); 7570 IsIndexSigned = MGSN->isIndexSigned(); 7571 } 7572 EVT IndexVT = Index.getValueType(); 7573 MVT XLenVT = Subtarget.getXLenVT(); 7574 // RISCV indexed loads only support the "unsigned unscaled" addressing 7575 // mode, so anything else must be manually legalized. 7576 bool NeedsIdxLegalization = 7577 IsIndexScaled || 7578 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7579 if (!NeedsIdxLegalization) 7580 break; 7581 7582 SDLoc DL(N); 7583 7584 // Any index legalization should first promote to XLenVT, so we don't lose 7585 // bits when scaling. This may create an illegal index type so we let 7586 // LLVM's legalization take care of the splitting. 7587 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7588 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7589 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7590 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7591 DL, IndexVT, Index); 7592 } 7593 7594 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7595 if (IsIndexScaled && Scale != 1) { 7596 // Manually scale the indices by the element size. 7597 // TODO: Sanitize the scale operand here? 7598 // TODO: For VP nodes, should we use VP_SHL here? 7599 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7600 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7601 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7602 } 7603 7604 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7605 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7606 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7607 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7608 VPGN->getScale(), VPGN->getMask(), 7609 VPGN->getVectorLength()}, 7610 VPGN->getMemOperand(), NewIndexTy); 7611 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7612 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7613 {VPSN->getChain(), VPSN->getValue(), 7614 VPSN->getBasePtr(), Index, VPSN->getScale(), 7615 VPSN->getMask(), VPSN->getVectorLength()}, 7616 VPSN->getMemOperand(), NewIndexTy); 7617 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7618 return DAG.getMaskedGather( 7619 N->getVTList(), MGN->getMemoryVT(), DL, 7620 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7621 MGN->getBasePtr(), Index, MGN->getScale()}, 7622 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7623 const auto *MSN = cast<MaskedScatterSDNode>(N); 7624 return DAG.getMaskedScatter( 7625 N->getVTList(), MSN->getMemoryVT(), DL, 7626 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7627 Index, MSN->getScale()}, 7628 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7629 } 7630 case RISCVISD::SRA_VL: 7631 case RISCVISD::SRL_VL: 7632 case RISCVISD::SHL_VL: { 7633 SDValue ShAmt = N->getOperand(1); 7634 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7635 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7636 SDLoc DL(N); 7637 SDValue VL = N->getOperand(3); 7638 EVT VT = N->getValueType(0); 7639 ShAmt = 7640 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7641 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7642 N->getOperand(2), N->getOperand(3)); 7643 } 7644 break; 7645 } 7646 case ISD::SRA: 7647 case ISD::SRL: 7648 case ISD::SHL: { 7649 SDValue ShAmt = N->getOperand(1); 7650 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7651 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7652 SDLoc DL(N); 7653 EVT VT = N->getValueType(0); 7654 ShAmt = 7655 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7656 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7657 } 7658 break; 7659 } 7660 case RISCVISD::MUL_VL: { 7661 SDValue Op0 = N->getOperand(0); 7662 SDValue Op1 = N->getOperand(1); 7663 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7664 return V; 7665 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7666 return V; 7667 return SDValue(); 7668 } 7669 case ISD::STORE: { 7670 auto *Store = cast<StoreSDNode>(N); 7671 SDValue Val = Store->getValue(); 7672 // Combine store of vmv.x.s to vse with VL of 1. 7673 // FIXME: Support FP. 7674 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7675 SDValue Src = Val.getOperand(0); 7676 EVT VecVT = Src.getValueType(); 7677 EVT MemVT = Store->getMemoryVT(); 7678 // The memory VT and the element type must match. 7679 if (VecVT.getVectorElementType() == MemVT) { 7680 SDLoc DL(N); 7681 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7682 return DAG.getStoreVP( 7683 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 7684 DAG.getConstant(1, DL, MaskVT), 7685 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 7686 Store->getMemOperand(), Store->getAddressingMode(), 7687 Store->isTruncatingStore(), /*IsCompress*/ false); 7688 } 7689 } 7690 7691 break; 7692 } 7693 } 7694 7695 return SDValue(); 7696 } 7697 7698 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7699 const SDNode *N, CombineLevel Level) const { 7700 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7701 // materialised in fewer instructions than `(OP _, c1)`: 7702 // 7703 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7704 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7705 SDValue N0 = N->getOperand(0); 7706 EVT Ty = N0.getValueType(); 7707 if (Ty.isScalarInteger() && 7708 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7709 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7710 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7711 if (C1 && C2) { 7712 const APInt &C1Int = C1->getAPIntValue(); 7713 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7714 7715 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7716 // and the combine should happen, to potentially allow further combines 7717 // later. 7718 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7719 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7720 return true; 7721 7722 // We can materialise `c1` in an add immediate, so it's "free", and the 7723 // combine should be prevented. 7724 if (C1Int.getMinSignedBits() <= 64 && 7725 isLegalAddImmediate(C1Int.getSExtValue())) 7726 return false; 7727 7728 // Neither constant will fit into an immediate, so find materialisation 7729 // costs. 7730 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7731 Subtarget.getFeatureBits(), 7732 /*CompressionCost*/true); 7733 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7734 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7735 /*CompressionCost*/true); 7736 7737 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7738 // combine should be prevented. 7739 if (C1Cost < ShiftedC1Cost) 7740 return false; 7741 } 7742 } 7743 return true; 7744 } 7745 7746 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7747 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7748 TargetLoweringOpt &TLO) const { 7749 // Delay this optimization as late as possible. 7750 if (!TLO.LegalOps) 7751 return false; 7752 7753 EVT VT = Op.getValueType(); 7754 if (VT.isVector()) 7755 return false; 7756 7757 // Only handle AND for now. 7758 if (Op.getOpcode() != ISD::AND) 7759 return false; 7760 7761 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7762 if (!C) 7763 return false; 7764 7765 const APInt &Mask = C->getAPIntValue(); 7766 7767 // Clear all non-demanded bits initially. 7768 APInt ShrunkMask = Mask & DemandedBits; 7769 7770 // Try to make a smaller immediate by setting undemanded bits. 7771 7772 APInt ExpandedMask = Mask | ~DemandedBits; 7773 7774 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7775 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7776 }; 7777 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7778 if (NewMask == Mask) 7779 return true; 7780 SDLoc DL(Op); 7781 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7782 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7783 return TLO.CombineTo(Op, NewOp); 7784 }; 7785 7786 // If the shrunk mask fits in sign extended 12 bits, let the target 7787 // independent code apply it. 7788 if (ShrunkMask.isSignedIntN(12)) 7789 return false; 7790 7791 // Preserve (and X, 0xffff) when zext.h is supported. 7792 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7793 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7794 if (IsLegalMask(NewMask)) 7795 return UseMask(NewMask); 7796 } 7797 7798 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7799 if (VT == MVT::i64) { 7800 APInt NewMask = APInt(64, 0xffffffff); 7801 if (IsLegalMask(NewMask)) 7802 return UseMask(NewMask); 7803 } 7804 7805 // For the remaining optimizations, we need to be able to make a negative 7806 // number through a combination of mask and undemanded bits. 7807 if (!ExpandedMask.isNegative()) 7808 return false; 7809 7810 // What is the fewest number of bits we need to represent the negative number. 7811 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7812 7813 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7814 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7815 APInt NewMask = ShrunkMask; 7816 if (MinSignedBits <= 12) 7817 NewMask.setBitsFrom(11); 7818 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7819 NewMask.setBitsFrom(31); 7820 else 7821 return false; 7822 7823 // Check that our new mask is a subset of the demanded mask. 7824 assert(IsLegalMask(NewMask)); 7825 return UseMask(NewMask); 7826 } 7827 7828 static void computeGREV(APInt &Src, unsigned ShAmt) { 7829 ShAmt &= Src.getBitWidth() - 1; 7830 uint64_t x = Src.getZExtValue(); 7831 if (ShAmt & 1) 7832 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7833 if (ShAmt & 2) 7834 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7835 if (ShAmt & 4) 7836 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7837 if (ShAmt & 8) 7838 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7839 if (ShAmt & 16) 7840 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7841 if (ShAmt & 32) 7842 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7843 Src = x; 7844 } 7845 7846 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7847 KnownBits &Known, 7848 const APInt &DemandedElts, 7849 const SelectionDAG &DAG, 7850 unsigned Depth) const { 7851 unsigned BitWidth = Known.getBitWidth(); 7852 unsigned Opc = Op.getOpcode(); 7853 assert((Opc >= ISD::BUILTIN_OP_END || 7854 Opc == ISD::INTRINSIC_WO_CHAIN || 7855 Opc == ISD::INTRINSIC_W_CHAIN || 7856 Opc == ISD::INTRINSIC_VOID) && 7857 "Should use MaskedValueIsZero if you don't know whether Op" 7858 " is a target node!"); 7859 7860 Known.resetAll(); 7861 switch (Opc) { 7862 default: break; 7863 case RISCVISD::SELECT_CC: { 7864 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7865 // If we don't know any bits, early out. 7866 if (Known.isUnknown()) 7867 break; 7868 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7869 7870 // Only known if known in both the LHS and RHS. 7871 Known = KnownBits::commonBits(Known, Known2); 7872 break; 7873 } 7874 case RISCVISD::REMUW: { 7875 KnownBits Known2; 7876 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7877 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7878 // We only care about the lower 32 bits. 7879 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7880 // Restore the original width by sign extending. 7881 Known = Known.sext(BitWidth); 7882 break; 7883 } 7884 case RISCVISD::DIVUW: { 7885 KnownBits Known2; 7886 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7887 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7888 // We only care about the lower 32 bits. 7889 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7890 // Restore the original width by sign extending. 7891 Known = Known.sext(BitWidth); 7892 break; 7893 } 7894 case RISCVISD::CTZW: { 7895 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7896 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7897 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7898 Known.Zero.setBitsFrom(LowBits); 7899 break; 7900 } 7901 case RISCVISD::CLZW: { 7902 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7903 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7904 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7905 Known.Zero.setBitsFrom(LowBits); 7906 break; 7907 } 7908 case RISCVISD::GREV: 7909 case RISCVISD::GREVW: { 7910 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7911 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7912 if (Opc == RISCVISD::GREVW) 7913 Known = Known.trunc(32); 7914 unsigned ShAmt = C->getZExtValue(); 7915 computeGREV(Known.Zero, ShAmt); 7916 computeGREV(Known.One, ShAmt); 7917 if (Opc == RISCVISD::GREVW) 7918 Known = Known.sext(BitWidth); 7919 } 7920 break; 7921 } 7922 case RISCVISD::READ_VLENB: 7923 // We assume VLENB is at least 16 bytes. 7924 Known.Zero.setLowBits(4); 7925 // We assume VLENB is no more than 65536 / 8 bytes. 7926 Known.Zero.setBitsFrom(14); 7927 break; 7928 case ISD::INTRINSIC_W_CHAIN: { 7929 unsigned IntNo = Op.getConstantOperandVal(1); 7930 switch (IntNo) { 7931 default: 7932 // We can't do anything for most intrinsics. 7933 break; 7934 case Intrinsic::riscv_vsetvli: 7935 case Intrinsic::riscv_vsetvlimax: 7936 // Assume that VL output is positive and would fit in an int32_t. 7937 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7938 if (BitWidth >= 32) 7939 Known.Zero.setBitsFrom(31); 7940 break; 7941 } 7942 break; 7943 } 7944 } 7945 } 7946 7947 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7948 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7949 unsigned Depth) const { 7950 switch (Op.getOpcode()) { 7951 default: 7952 break; 7953 case RISCVISD::SELECT_CC: { 7954 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7955 if (Tmp == 1) return 1; // Early out. 7956 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7957 return std::min(Tmp, Tmp2); 7958 } 7959 case RISCVISD::SLLW: 7960 case RISCVISD::SRAW: 7961 case RISCVISD::SRLW: 7962 case RISCVISD::DIVW: 7963 case RISCVISD::DIVUW: 7964 case RISCVISD::REMUW: 7965 case RISCVISD::ROLW: 7966 case RISCVISD::RORW: 7967 case RISCVISD::GREVW: 7968 case RISCVISD::GORCW: 7969 case RISCVISD::FSLW: 7970 case RISCVISD::FSRW: 7971 case RISCVISD::SHFLW: 7972 case RISCVISD::UNSHFLW: 7973 case RISCVISD::BCOMPRESSW: 7974 case RISCVISD::BDECOMPRESSW: 7975 case RISCVISD::BFPW: 7976 case RISCVISD::FCVT_W_RV64: 7977 case RISCVISD::FCVT_WU_RV64: 7978 case RISCVISD::STRICT_FCVT_W_RV64: 7979 case RISCVISD::STRICT_FCVT_WU_RV64: 7980 // TODO: As the result is sign-extended, this is conservatively correct. A 7981 // more precise answer could be calculated for SRAW depending on known 7982 // bits in the shift amount. 7983 return 33; 7984 case RISCVISD::SHFL: 7985 case RISCVISD::UNSHFL: { 7986 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7987 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7988 // will stay within the upper 32 bits. If there were more than 32 sign bits 7989 // before there will be at least 33 sign bits after. 7990 if (Op.getValueType() == MVT::i64 && 7991 isa<ConstantSDNode>(Op.getOperand(1)) && 7992 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7993 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7994 if (Tmp > 32) 7995 return 33; 7996 } 7997 break; 7998 } 7999 case RISCVISD::VMV_X_S: 8000 // The number of sign bits of the scalar result is computed by obtaining the 8001 // element type of the input vector operand, subtracting its width from the 8002 // XLEN, and then adding one (sign bit within the element type). If the 8003 // element type is wider than XLen, the least-significant XLEN bits are 8004 // taken. 8005 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 8006 return 1; 8007 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 8008 } 8009 8010 return 1; 8011 } 8012 8013 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8014 MachineBasicBlock *BB) { 8015 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8016 8017 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8018 // Should the count have wrapped while it was being read, we need to try 8019 // again. 8020 // ... 8021 // read: 8022 // rdcycleh x3 # load high word of cycle 8023 // rdcycle x2 # load low word of cycle 8024 // rdcycleh x4 # load high word of cycle 8025 // bne x3, x4, read # check if high word reads match, otherwise try again 8026 // ... 8027 8028 MachineFunction &MF = *BB->getParent(); 8029 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8030 MachineFunction::iterator It = ++BB->getIterator(); 8031 8032 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8033 MF.insert(It, LoopMBB); 8034 8035 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8036 MF.insert(It, DoneMBB); 8037 8038 // Transfer the remainder of BB and its successor edges to DoneMBB. 8039 DoneMBB->splice(DoneMBB->begin(), BB, 8040 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8041 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8042 8043 BB->addSuccessor(LoopMBB); 8044 8045 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8046 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8047 Register LoReg = MI.getOperand(0).getReg(); 8048 Register HiReg = MI.getOperand(1).getReg(); 8049 DebugLoc DL = MI.getDebugLoc(); 8050 8051 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8052 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8053 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8054 .addReg(RISCV::X0); 8055 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8056 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8057 .addReg(RISCV::X0); 8058 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8059 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8060 .addReg(RISCV::X0); 8061 8062 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8063 .addReg(HiReg) 8064 .addReg(ReadAgainReg) 8065 .addMBB(LoopMBB); 8066 8067 LoopMBB->addSuccessor(LoopMBB); 8068 LoopMBB->addSuccessor(DoneMBB); 8069 8070 MI.eraseFromParent(); 8071 8072 return DoneMBB; 8073 } 8074 8075 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8076 MachineBasicBlock *BB) { 8077 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8078 8079 MachineFunction &MF = *BB->getParent(); 8080 DebugLoc DL = MI.getDebugLoc(); 8081 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8082 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8083 Register LoReg = MI.getOperand(0).getReg(); 8084 Register HiReg = MI.getOperand(1).getReg(); 8085 Register SrcReg = MI.getOperand(2).getReg(); 8086 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8087 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8088 8089 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8090 RI); 8091 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8092 MachineMemOperand *MMOLo = 8093 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8094 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8095 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8096 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8097 .addFrameIndex(FI) 8098 .addImm(0) 8099 .addMemOperand(MMOLo); 8100 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8101 .addFrameIndex(FI) 8102 .addImm(4) 8103 .addMemOperand(MMOHi); 8104 MI.eraseFromParent(); // The pseudo instruction is gone now. 8105 return BB; 8106 } 8107 8108 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8109 MachineBasicBlock *BB) { 8110 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8111 "Unexpected instruction"); 8112 8113 MachineFunction &MF = *BB->getParent(); 8114 DebugLoc DL = MI.getDebugLoc(); 8115 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8116 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8117 Register DstReg = MI.getOperand(0).getReg(); 8118 Register LoReg = MI.getOperand(1).getReg(); 8119 Register HiReg = MI.getOperand(2).getReg(); 8120 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8121 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8122 8123 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8124 MachineMemOperand *MMOLo = 8125 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8126 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8127 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8128 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8129 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8130 .addFrameIndex(FI) 8131 .addImm(0) 8132 .addMemOperand(MMOLo); 8133 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8134 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8135 .addFrameIndex(FI) 8136 .addImm(4) 8137 .addMemOperand(MMOHi); 8138 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8139 MI.eraseFromParent(); // The pseudo instruction is gone now. 8140 return BB; 8141 } 8142 8143 static bool isSelectPseudo(MachineInstr &MI) { 8144 switch (MI.getOpcode()) { 8145 default: 8146 return false; 8147 case RISCV::Select_GPR_Using_CC_GPR: 8148 case RISCV::Select_FPR16_Using_CC_GPR: 8149 case RISCV::Select_FPR32_Using_CC_GPR: 8150 case RISCV::Select_FPR64_Using_CC_GPR: 8151 return true; 8152 } 8153 } 8154 8155 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8156 unsigned RelOpcode, unsigned EqOpcode, 8157 const RISCVSubtarget &Subtarget) { 8158 DebugLoc DL = MI.getDebugLoc(); 8159 Register DstReg = MI.getOperand(0).getReg(); 8160 Register Src1Reg = MI.getOperand(1).getReg(); 8161 Register Src2Reg = MI.getOperand(2).getReg(); 8162 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8163 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8164 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8165 8166 // Save the current FFLAGS. 8167 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8168 8169 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8170 .addReg(Src1Reg) 8171 .addReg(Src2Reg); 8172 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8173 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8174 8175 // Restore the FFLAGS. 8176 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 8177 .addReg(SavedFFlags, RegState::Kill); 8178 8179 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 8180 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 8181 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 8182 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 8183 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8184 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 8185 8186 // Erase the pseudoinstruction. 8187 MI.eraseFromParent(); 8188 return BB; 8189 } 8190 8191 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 8192 MachineBasicBlock *BB, 8193 const RISCVSubtarget &Subtarget) { 8194 // To "insert" Select_* instructions, we actually have to insert the triangle 8195 // control-flow pattern. The incoming instructions know the destination vreg 8196 // to set, the condition code register to branch on, the true/false values to 8197 // select between, and the condcode to use to select the appropriate branch. 8198 // 8199 // We produce the following control flow: 8200 // HeadMBB 8201 // | \ 8202 // | IfFalseMBB 8203 // | / 8204 // TailMBB 8205 // 8206 // When we find a sequence of selects we attempt to optimize their emission 8207 // by sharing the control flow. Currently we only handle cases where we have 8208 // multiple selects with the exact same condition (same LHS, RHS and CC). 8209 // The selects may be interleaved with other instructions if the other 8210 // instructions meet some requirements we deem safe: 8211 // - They are debug instructions. Otherwise, 8212 // - They do not have side-effects, do not access memory and their inputs do 8213 // not depend on the results of the select pseudo-instructions. 8214 // The TrueV/FalseV operands of the selects cannot depend on the result of 8215 // previous selects in the sequence. 8216 // These conditions could be further relaxed. See the X86 target for a 8217 // related approach and more information. 8218 Register LHS = MI.getOperand(1).getReg(); 8219 Register RHS = MI.getOperand(2).getReg(); 8220 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 8221 8222 SmallVector<MachineInstr *, 4> SelectDebugValues; 8223 SmallSet<Register, 4> SelectDests; 8224 SelectDests.insert(MI.getOperand(0).getReg()); 8225 8226 MachineInstr *LastSelectPseudo = &MI; 8227 8228 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 8229 SequenceMBBI != E; ++SequenceMBBI) { 8230 if (SequenceMBBI->isDebugInstr()) 8231 continue; 8232 else if (isSelectPseudo(*SequenceMBBI)) { 8233 if (SequenceMBBI->getOperand(1).getReg() != LHS || 8234 SequenceMBBI->getOperand(2).getReg() != RHS || 8235 SequenceMBBI->getOperand(3).getImm() != CC || 8236 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 8237 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 8238 break; 8239 LastSelectPseudo = &*SequenceMBBI; 8240 SequenceMBBI->collectDebugValues(SelectDebugValues); 8241 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 8242 } else { 8243 if (SequenceMBBI->hasUnmodeledSideEffects() || 8244 SequenceMBBI->mayLoadOrStore()) 8245 break; 8246 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 8247 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 8248 })) 8249 break; 8250 } 8251 } 8252 8253 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 8254 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8255 DebugLoc DL = MI.getDebugLoc(); 8256 MachineFunction::iterator I = ++BB->getIterator(); 8257 8258 MachineBasicBlock *HeadMBB = BB; 8259 MachineFunction *F = BB->getParent(); 8260 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 8261 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 8262 8263 F->insert(I, IfFalseMBB); 8264 F->insert(I, TailMBB); 8265 8266 // Transfer debug instructions associated with the selects to TailMBB. 8267 for (MachineInstr *DebugInstr : SelectDebugValues) { 8268 TailMBB->push_back(DebugInstr->removeFromParent()); 8269 } 8270 8271 // Move all instructions after the sequence to TailMBB. 8272 TailMBB->splice(TailMBB->end(), HeadMBB, 8273 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 8274 // Update machine-CFG edges by transferring all successors of the current 8275 // block to the new block which will contain the Phi nodes for the selects. 8276 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 8277 // Set the successors for HeadMBB. 8278 HeadMBB->addSuccessor(IfFalseMBB); 8279 HeadMBB->addSuccessor(TailMBB); 8280 8281 // Insert appropriate branch. 8282 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 8283 .addReg(LHS) 8284 .addReg(RHS) 8285 .addMBB(TailMBB); 8286 8287 // IfFalseMBB just falls through to TailMBB. 8288 IfFalseMBB->addSuccessor(TailMBB); 8289 8290 // Create PHIs for all of the select pseudo-instructions. 8291 auto SelectMBBI = MI.getIterator(); 8292 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 8293 auto InsertionPoint = TailMBB->begin(); 8294 while (SelectMBBI != SelectEnd) { 8295 auto Next = std::next(SelectMBBI); 8296 if (isSelectPseudo(*SelectMBBI)) { 8297 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 8298 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 8299 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 8300 .addReg(SelectMBBI->getOperand(4).getReg()) 8301 .addMBB(HeadMBB) 8302 .addReg(SelectMBBI->getOperand(5).getReg()) 8303 .addMBB(IfFalseMBB); 8304 SelectMBBI->eraseFromParent(); 8305 } 8306 SelectMBBI = Next; 8307 } 8308 8309 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8310 return TailMBB; 8311 } 8312 8313 MachineBasicBlock * 8314 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8315 MachineBasicBlock *BB) const { 8316 switch (MI.getOpcode()) { 8317 default: 8318 llvm_unreachable("Unexpected instr type to insert"); 8319 case RISCV::ReadCycleWide: 8320 assert(!Subtarget.is64Bit() && 8321 "ReadCycleWrite is only to be used on riscv32"); 8322 return emitReadCycleWidePseudo(MI, BB); 8323 case RISCV::Select_GPR_Using_CC_GPR: 8324 case RISCV::Select_FPR16_Using_CC_GPR: 8325 case RISCV::Select_FPR32_Using_CC_GPR: 8326 case RISCV::Select_FPR64_Using_CC_GPR: 8327 return emitSelectPseudo(MI, BB, Subtarget); 8328 case RISCV::BuildPairF64Pseudo: 8329 return emitBuildPairF64Pseudo(MI, BB); 8330 case RISCV::SplitF64Pseudo: 8331 return emitSplitF64Pseudo(MI, BB); 8332 case RISCV::PseudoQuietFLE_H: 8333 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 8334 case RISCV::PseudoQuietFLT_H: 8335 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 8336 case RISCV::PseudoQuietFLE_S: 8337 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 8338 case RISCV::PseudoQuietFLT_S: 8339 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 8340 case RISCV::PseudoQuietFLE_D: 8341 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 8342 case RISCV::PseudoQuietFLT_D: 8343 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 8344 } 8345 } 8346 8347 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8348 SDNode *Node) const { 8349 // Add FRM dependency to any instructions with dynamic rounding mode. 8350 unsigned Opc = MI.getOpcode(); 8351 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 8352 if (Idx < 0) 8353 return; 8354 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 8355 return; 8356 // If the instruction already reads FRM, don't add another read. 8357 if (MI.readsRegister(RISCV::FRM)) 8358 return; 8359 MI.addOperand( 8360 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 8361 } 8362 8363 // Calling Convention Implementation. 8364 // The expectations for frontend ABI lowering vary from target to target. 8365 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 8366 // details, but this is a longer term goal. For now, we simply try to keep the 8367 // role of the frontend as simple and well-defined as possible. The rules can 8368 // be summarised as: 8369 // * Never split up large scalar arguments. We handle them here. 8370 // * If a hardfloat calling convention is being used, and the struct may be 8371 // passed in a pair of registers (fp+fp, int+fp), and both registers are 8372 // available, then pass as two separate arguments. If either the GPRs or FPRs 8373 // are exhausted, then pass according to the rule below. 8374 // * If a struct could never be passed in registers or directly in a stack 8375 // slot (as it is larger than 2*XLEN and the floating point rules don't 8376 // apply), then pass it using a pointer with the byval attribute. 8377 // * If a struct is less than 2*XLEN, then coerce to either a two-element 8378 // word-sized array or a 2*XLEN scalar (depending on alignment). 8379 // * The frontend can determine whether a struct is returned by reference or 8380 // not based on its size and fields. If it will be returned by reference, the 8381 // frontend must modify the prototype so a pointer with the sret annotation is 8382 // passed as the first argument. This is not necessary for large scalar 8383 // returns. 8384 // * Struct return values and varargs should be coerced to structs containing 8385 // register-size fields in the same situations they would be for fixed 8386 // arguments. 8387 8388 static const MCPhysReg ArgGPRs[] = { 8389 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 8390 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 8391 }; 8392 static const MCPhysReg ArgFPR16s[] = { 8393 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 8394 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 8395 }; 8396 static const MCPhysReg ArgFPR32s[] = { 8397 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 8398 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 8399 }; 8400 static const MCPhysReg ArgFPR64s[] = { 8401 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 8402 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 8403 }; 8404 // This is an interim calling convention and it may be changed in the future. 8405 static const MCPhysReg ArgVRs[] = { 8406 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 8407 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 8408 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 8409 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 8410 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 8411 RISCV::V20M2, RISCV::V22M2}; 8412 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 8413 RISCV::V20M4}; 8414 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 8415 8416 // Pass a 2*XLEN argument that has been split into two XLEN values through 8417 // registers or the stack as necessary. 8418 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 8419 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 8420 MVT ValVT2, MVT LocVT2, 8421 ISD::ArgFlagsTy ArgFlags2) { 8422 unsigned XLenInBytes = XLen / 8; 8423 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8424 // At least one half can be passed via register. 8425 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 8426 VA1.getLocVT(), CCValAssign::Full)); 8427 } else { 8428 // Both halves must be passed on the stack, with proper alignment. 8429 Align StackAlign = 8430 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 8431 State.addLoc( 8432 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 8433 State.AllocateStack(XLenInBytes, StackAlign), 8434 VA1.getLocVT(), CCValAssign::Full)); 8435 State.addLoc(CCValAssign::getMem( 8436 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8437 LocVT2, CCValAssign::Full)); 8438 return false; 8439 } 8440 8441 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8442 // The second half can also be passed via register. 8443 State.addLoc( 8444 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 8445 } else { 8446 // The second half is passed via the stack, without additional alignment. 8447 State.addLoc(CCValAssign::getMem( 8448 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8449 LocVT2, CCValAssign::Full)); 8450 } 8451 8452 return false; 8453 } 8454 8455 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8456 Optional<unsigned> FirstMaskArgument, 8457 CCState &State, const RISCVTargetLowering &TLI) { 8458 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8459 if (RC == &RISCV::VRRegClass) { 8460 // Assign the first mask argument to V0. 8461 // This is an interim calling convention and it may be changed in the 8462 // future. 8463 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8464 return State.AllocateReg(RISCV::V0); 8465 return State.AllocateReg(ArgVRs); 8466 } 8467 if (RC == &RISCV::VRM2RegClass) 8468 return State.AllocateReg(ArgVRM2s); 8469 if (RC == &RISCV::VRM4RegClass) 8470 return State.AllocateReg(ArgVRM4s); 8471 if (RC == &RISCV::VRM8RegClass) 8472 return State.AllocateReg(ArgVRM8s); 8473 llvm_unreachable("Unhandled register class for ValueType"); 8474 } 8475 8476 // Implements the RISC-V calling convention. Returns true upon failure. 8477 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8478 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8479 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8480 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8481 Optional<unsigned> FirstMaskArgument) { 8482 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8483 assert(XLen == 32 || XLen == 64); 8484 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8485 8486 // Any return value split in to more than two values can't be returned 8487 // directly. Vectors are returned via the available vector registers. 8488 if (!LocVT.isVector() && IsRet && ValNo > 1) 8489 return true; 8490 8491 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8492 // variadic argument, or if no F16/F32 argument registers are available. 8493 bool UseGPRForF16_F32 = true; 8494 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8495 // variadic argument, or if no F64 argument registers are available. 8496 bool UseGPRForF64 = true; 8497 8498 switch (ABI) { 8499 default: 8500 llvm_unreachable("Unexpected ABI"); 8501 case RISCVABI::ABI_ILP32: 8502 case RISCVABI::ABI_LP64: 8503 break; 8504 case RISCVABI::ABI_ILP32F: 8505 case RISCVABI::ABI_LP64F: 8506 UseGPRForF16_F32 = !IsFixed; 8507 break; 8508 case RISCVABI::ABI_ILP32D: 8509 case RISCVABI::ABI_LP64D: 8510 UseGPRForF16_F32 = !IsFixed; 8511 UseGPRForF64 = !IsFixed; 8512 break; 8513 } 8514 8515 // FPR16, FPR32, and FPR64 alias each other. 8516 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 8517 UseGPRForF16_F32 = true; 8518 UseGPRForF64 = true; 8519 } 8520 8521 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 8522 // similar local variables rather than directly checking against the target 8523 // ABI. 8524 8525 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 8526 LocVT = XLenVT; 8527 LocInfo = CCValAssign::BCvt; 8528 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 8529 LocVT = MVT::i64; 8530 LocInfo = CCValAssign::BCvt; 8531 } 8532 8533 // If this is a variadic argument, the RISC-V calling convention requires 8534 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 8535 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 8536 // be used regardless of whether the original argument was split during 8537 // legalisation or not. The argument will not be passed by registers if the 8538 // original type is larger than 2*XLEN, so the register alignment rule does 8539 // not apply. 8540 unsigned TwoXLenInBytes = (2 * XLen) / 8; 8541 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 8542 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 8543 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8544 // Skip 'odd' register if necessary. 8545 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8546 State.AllocateReg(ArgGPRs); 8547 } 8548 8549 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8550 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8551 State.getPendingArgFlags(); 8552 8553 assert(PendingLocs.size() == PendingArgFlags.size() && 8554 "PendingLocs and PendingArgFlags out of sync"); 8555 8556 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8557 // registers are exhausted. 8558 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8559 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8560 "Can't lower f64 if it is split"); 8561 // Depending on available argument GPRS, f64 may be passed in a pair of 8562 // GPRs, split between a GPR and the stack, or passed completely on the 8563 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8564 // cases. 8565 Register Reg = State.AllocateReg(ArgGPRs); 8566 LocVT = MVT::i32; 8567 if (!Reg) { 8568 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8569 State.addLoc( 8570 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8571 return false; 8572 } 8573 if (!State.AllocateReg(ArgGPRs)) 8574 State.AllocateStack(4, Align(4)); 8575 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8576 return false; 8577 } 8578 8579 // Fixed-length vectors are located in the corresponding scalable-vector 8580 // container types. 8581 if (ValVT.isFixedLengthVector()) 8582 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8583 8584 // Split arguments might be passed indirectly, so keep track of the pending 8585 // values. Split vectors are passed via a mix of registers and indirectly, so 8586 // treat them as we would any other argument. 8587 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8588 LocVT = XLenVT; 8589 LocInfo = CCValAssign::Indirect; 8590 PendingLocs.push_back( 8591 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8592 PendingArgFlags.push_back(ArgFlags); 8593 if (!ArgFlags.isSplitEnd()) { 8594 return false; 8595 } 8596 } 8597 8598 // If the split argument only had two elements, it should be passed directly 8599 // in registers or on the stack. 8600 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8601 PendingLocs.size() <= 2) { 8602 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8603 // Apply the normal calling convention rules to the first half of the 8604 // split argument. 8605 CCValAssign VA = PendingLocs[0]; 8606 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8607 PendingLocs.clear(); 8608 PendingArgFlags.clear(); 8609 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8610 ArgFlags); 8611 } 8612 8613 // Allocate to a register if possible, or else a stack slot. 8614 Register Reg; 8615 unsigned StoreSizeBytes = XLen / 8; 8616 Align StackAlign = Align(XLen / 8); 8617 8618 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8619 Reg = State.AllocateReg(ArgFPR16s); 8620 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8621 Reg = State.AllocateReg(ArgFPR32s); 8622 else if (ValVT == MVT::f64 && !UseGPRForF64) 8623 Reg = State.AllocateReg(ArgFPR64s); 8624 else if (ValVT.isVector()) { 8625 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8626 if (!Reg) { 8627 // For return values, the vector must be passed fully via registers or 8628 // via the stack. 8629 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8630 // but we're using all of them. 8631 if (IsRet) 8632 return true; 8633 // Try using a GPR to pass the address 8634 if ((Reg = State.AllocateReg(ArgGPRs))) { 8635 LocVT = XLenVT; 8636 LocInfo = CCValAssign::Indirect; 8637 } else if (ValVT.isScalableVector()) { 8638 LocVT = XLenVT; 8639 LocInfo = CCValAssign::Indirect; 8640 } else { 8641 // Pass fixed-length vectors on the stack. 8642 LocVT = ValVT; 8643 StoreSizeBytes = ValVT.getStoreSize(); 8644 // Align vectors to their element sizes, being careful for vXi1 8645 // vectors. 8646 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8647 } 8648 } 8649 } else { 8650 Reg = State.AllocateReg(ArgGPRs); 8651 } 8652 8653 unsigned StackOffset = 8654 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8655 8656 // If we reach this point and PendingLocs is non-empty, we must be at the 8657 // end of a split argument that must be passed indirectly. 8658 if (!PendingLocs.empty()) { 8659 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8660 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8661 8662 for (auto &It : PendingLocs) { 8663 if (Reg) 8664 It.convertToReg(Reg); 8665 else 8666 It.convertToMem(StackOffset); 8667 State.addLoc(It); 8668 } 8669 PendingLocs.clear(); 8670 PendingArgFlags.clear(); 8671 return false; 8672 } 8673 8674 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8675 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8676 "Expected an XLenVT or vector types at this stage"); 8677 8678 if (Reg) { 8679 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8680 return false; 8681 } 8682 8683 // When a floating-point value is passed on the stack, no bit-conversion is 8684 // needed. 8685 if (ValVT.isFloatingPoint()) { 8686 LocVT = ValVT; 8687 LocInfo = CCValAssign::Full; 8688 } 8689 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8690 return false; 8691 } 8692 8693 template <typename ArgTy> 8694 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8695 for (const auto &ArgIdx : enumerate(Args)) { 8696 MVT ArgVT = ArgIdx.value().VT; 8697 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8698 return ArgIdx.index(); 8699 } 8700 return None; 8701 } 8702 8703 void RISCVTargetLowering::analyzeInputArgs( 8704 MachineFunction &MF, CCState &CCInfo, 8705 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8706 RISCVCCAssignFn Fn) const { 8707 unsigned NumArgs = Ins.size(); 8708 FunctionType *FType = MF.getFunction().getFunctionType(); 8709 8710 Optional<unsigned> FirstMaskArgument; 8711 if (Subtarget.hasVInstructions()) 8712 FirstMaskArgument = preAssignMask(Ins); 8713 8714 for (unsigned i = 0; i != NumArgs; ++i) { 8715 MVT ArgVT = Ins[i].VT; 8716 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8717 8718 Type *ArgTy = nullptr; 8719 if (IsRet) 8720 ArgTy = FType->getReturnType(); 8721 else if (Ins[i].isOrigArg()) 8722 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8723 8724 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8725 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8726 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8727 FirstMaskArgument)) { 8728 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8729 << EVT(ArgVT).getEVTString() << '\n'); 8730 llvm_unreachable(nullptr); 8731 } 8732 } 8733 } 8734 8735 void RISCVTargetLowering::analyzeOutputArgs( 8736 MachineFunction &MF, CCState &CCInfo, 8737 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8738 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8739 unsigned NumArgs = Outs.size(); 8740 8741 Optional<unsigned> FirstMaskArgument; 8742 if (Subtarget.hasVInstructions()) 8743 FirstMaskArgument = preAssignMask(Outs); 8744 8745 for (unsigned i = 0; i != NumArgs; i++) { 8746 MVT ArgVT = Outs[i].VT; 8747 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8748 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8749 8750 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8751 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8752 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8753 FirstMaskArgument)) { 8754 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8755 << EVT(ArgVT).getEVTString() << "\n"); 8756 llvm_unreachable(nullptr); 8757 } 8758 } 8759 } 8760 8761 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8762 // values. 8763 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8764 const CCValAssign &VA, const SDLoc &DL, 8765 const RISCVSubtarget &Subtarget) { 8766 switch (VA.getLocInfo()) { 8767 default: 8768 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8769 case CCValAssign::Full: 8770 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8771 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8772 break; 8773 case CCValAssign::BCvt: 8774 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8775 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8776 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8777 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8778 else 8779 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8780 break; 8781 } 8782 return Val; 8783 } 8784 8785 // The caller is responsible for loading the full value if the argument is 8786 // passed with CCValAssign::Indirect. 8787 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8788 const CCValAssign &VA, const SDLoc &DL, 8789 const RISCVTargetLowering &TLI) { 8790 MachineFunction &MF = DAG.getMachineFunction(); 8791 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8792 EVT LocVT = VA.getLocVT(); 8793 SDValue Val; 8794 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8795 Register VReg = RegInfo.createVirtualRegister(RC); 8796 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8797 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8798 8799 if (VA.getLocInfo() == CCValAssign::Indirect) 8800 return Val; 8801 8802 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8803 } 8804 8805 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8806 const CCValAssign &VA, const SDLoc &DL, 8807 const RISCVSubtarget &Subtarget) { 8808 EVT LocVT = VA.getLocVT(); 8809 8810 switch (VA.getLocInfo()) { 8811 default: 8812 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8813 case CCValAssign::Full: 8814 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8815 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8816 break; 8817 case CCValAssign::BCvt: 8818 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8819 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8820 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8821 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8822 else 8823 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8824 break; 8825 } 8826 return Val; 8827 } 8828 8829 // The caller is responsible for loading the full value if the argument is 8830 // passed with CCValAssign::Indirect. 8831 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8832 const CCValAssign &VA, const SDLoc &DL) { 8833 MachineFunction &MF = DAG.getMachineFunction(); 8834 MachineFrameInfo &MFI = MF.getFrameInfo(); 8835 EVT LocVT = VA.getLocVT(); 8836 EVT ValVT = VA.getValVT(); 8837 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8838 if (ValVT.isScalableVector()) { 8839 // When the value is a scalable vector, we save the pointer which points to 8840 // the scalable vector value in the stack. The ValVT will be the pointer 8841 // type, instead of the scalable vector type. 8842 ValVT = LocVT; 8843 } 8844 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8845 /*IsImmutable=*/true); 8846 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8847 SDValue Val; 8848 8849 ISD::LoadExtType ExtType; 8850 switch (VA.getLocInfo()) { 8851 default: 8852 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8853 case CCValAssign::Full: 8854 case CCValAssign::Indirect: 8855 case CCValAssign::BCvt: 8856 ExtType = ISD::NON_EXTLOAD; 8857 break; 8858 } 8859 Val = DAG.getExtLoad( 8860 ExtType, DL, LocVT, Chain, FIN, 8861 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8862 return Val; 8863 } 8864 8865 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8866 const CCValAssign &VA, const SDLoc &DL) { 8867 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8868 "Unexpected VA"); 8869 MachineFunction &MF = DAG.getMachineFunction(); 8870 MachineFrameInfo &MFI = MF.getFrameInfo(); 8871 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8872 8873 if (VA.isMemLoc()) { 8874 // f64 is passed on the stack. 8875 int FI = 8876 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 8877 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8878 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8879 MachinePointerInfo::getFixedStack(MF, FI)); 8880 } 8881 8882 assert(VA.isRegLoc() && "Expected register VA assignment"); 8883 8884 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8885 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8886 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8887 SDValue Hi; 8888 if (VA.getLocReg() == RISCV::X17) { 8889 // Second half of f64 is passed on the stack. 8890 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 8891 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8892 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8893 MachinePointerInfo::getFixedStack(MF, FI)); 8894 } else { 8895 // Second half of f64 is passed in another GPR. 8896 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8897 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8898 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8899 } 8900 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8901 } 8902 8903 // FastCC has less than 1% performance improvement for some particular 8904 // benchmark. But theoretically, it may has benenfit for some cases. 8905 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8906 unsigned ValNo, MVT ValVT, MVT LocVT, 8907 CCValAssign::LocInfo LocInfo, 8908 ISD::ArgFlagsTy ArgFlags, CCState &State, 8909 bool IsFixed, bool IsRet, Type *OrigTy, 8910 const RISCVTargetLowering &TLI, 8911 Optional<unsigned> FirstMaskArgument) { 8912 8913 // X5 and X6 might be used for save-restore libcall. 8914 static const MCPhysReg GPRList[] = { 8915 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8916 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8917 RISCV::X29, RISCV::X30, RISCV::X31}; 8918 8919 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8920 if (unsigned Reg = State.AllocateReg(GPRList)) { 8921 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8922 return false; 8923 } 8924 } 8925 8926 if (LocVT == MVT::f16) { 8927 static const MCPhysReg FPR16List[] = { 8928 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8929 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8930 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8931 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8932 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8933 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8934 return false; 8935 } 8936 } 8937 8938 if (LocVT == MVT::f32) { 8939 static const MCPhysReg FPR32List[] = { 8940 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8941 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8942 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8943 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8944 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8945 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8946 return false; 8947 } 8948 } 8949 8950 if (LocVT == MVT::f64) { 8951 static const MCPhysReg FPR64List[] = { 8952 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8953 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8954 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8955 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8956 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8957 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8958 return false; 8959 } 8960 } 8961 8962 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8963 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8964 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8965 return false; 8966 } 8967 8968 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8969 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8970 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8971 return false; 8972 } 8973 8974 if (LocVT.isVector()) { 8975 if (unsigned Reg = 8976 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8977 // Fixed-length vectors are located in the corresponding scalable-vector 8978 // container types. 8979 if (ValVT.isFixedLengthVector()) 8980 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8981 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8982 } else { 8983 // Try and pass the address via a "fast" GPR. 8984 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8985 LocInfo = CCValAssign::Indirect; 8986 LocVT = TLI.getSubtarget().getXLenVT(); 8987 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8988 } else if (ValVT.isFixedLengthVector()) { 8989 auto StackAlign = 8990 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8991 unsigned StackOffset = 8992 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8993 State.addLoc( 8994 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8995 } else { 8996 // Can't pass scalable vectors on the stack. 8997 return true; 8998 } 8999 } 9000 9001 return false; 9002 } 9003 9004 return true; // CC didn't match. 9005 } 9006 9007 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9008 CCValAssign::LocInfo LocInfo, 9009 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9010 9011 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9012 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9013 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9014 static const MCPhysReg GPRList[] = { 9015 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9016 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9017 if (unsigned Reg = State.AllocateReg(GPRList)) { 9018 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9019 return false; 9020 } 9021 } 9022 9023 if (LocVT == MVT::f32) { 9024 // Pass in STG registers: F1, ..., F6 9025 // fs0 ... fs5 9026 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9027 RISCV::F18_F, RISCV::F19_F, 9028 RISCV::F20_F, RISCV::F21_F}; 9029 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9030 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9031 return false; 9032 } 9033 } 9034 9035 if (LocVT == MVT::f64) { 9036 // Pass in STG registers: D1, ..., D6 9037 // fs6 ... fs11 9038 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9039 RISCV::F24_D, RISCV::F25_D, 9040 RISCV::F26_D, RISCV::F27_D}; 9041 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9042 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9043 return false; 9044 } 9045 } 9046 9047 report_fatal_error("No registers left in GHC calling convention"); 9048 return true; 9049 } 9050 9051 // Transform physical registers into virtual registers. 9052 SDValue RISCVTargetLowering::LowerFormalArguments( 9053 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9054 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9055 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9056 9057 MachineFunction &MF = DAG.getMachineFunction(); 9058 9059 switch (CallConv) { 9060 default: 9061 report_fatal_error("Unsupported calling convention"); 9062 case CallingConv::C: 9063 case CallingConv::Fast: 9064 break; 9065 case CallingConv::GHC: 9066 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9067 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9068 report_fatal_error( 9069 "GHC calling convention requires the F and D instruction set extensions"); 9070 } 9071 9072 const Function &Func = MF.getFunction(); 9073 if (Func.hasFnAttribute("interrupt")) { 9074 if (!Func.arg_empty()) 9075 report_fatal_error( 9076 "Functions with the interrupt attribute cannot have arguments!"); 9077 9078 StringRef Kind = 9079 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9080 9081 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9082 report_fatal_error( 9083 "Function interrupt attribute argument not supported!"); 9084 } 9085 9086 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9087 MVT XLenVT = Subtarget.getXLenVT(); 9088 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9089 // Used with vargs to acumulate store chains. 9090 std::vector<SDValue> OutChains; 9091 9092 // Assign locations to all of the incoming arguments. 9093 SmallVector<CCValAssign, 16> ArgLocs; 9094 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9095 9096 if (CallConv == CallingConv::GHC) 9097 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9098 else 9099 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9100 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9101 : CC_RISCV); 9102 9103 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9104 CCValAssign &VA = ArgLocs[i]; 9105 SDValue ArgValue; 9106 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9107 // case. 9108 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9109 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9110 else if (VA.isRegLoc()) 9111 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9112 else 9113 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9114 9115 if (VA.getLocInfo() == CCValAssign::Indirect) { 9116 // If the original argument was split and passed by reference (e.g. i128 9117 // on RV32), we need to load all parts of it here (using the same 9118 // address). Vectors may be partly split to registers and partly to the 9119 // stack, in which case the base address is partly offset and subsequent 9120 // stores are relative to that. 9121 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9122 MachinePointerInfo())); 9123 unsigned ArgIndex = Ins[i].OrigArgIndex; 9124 unsigned ArgPartOffset = Ins[i].PartOffset; 9125 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9126 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9127 CCValAssign &PartVA = ArgLocs[i + 1]; 9128 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9129 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9130 if (PartVA.getValVT().isScalableVector()) 9131 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9132 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9133 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9134 MachinePointerInfo())); 9135 ++i; 9136 } 9137 continue; 9138 } 9139 InVals.push_back(ArgValue); 9140 } 9141 9142 if (IsVarArg) { 9143 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9144 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9145 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9146 MachineFrameInfo &MFI = MF.getFrameInfo(); 9147 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9148 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9149 9150 // Offset of the first variable argument from stack pointer, and size of 9151 // the vararg save area. For now, the varargs save area is either zero or 9152 // large enough to hold a0-a7. 9153 int VaArgOffset, VarArgsSaveSize; 9154 9155 // If all registers are allocated, then all varargs must be passed on the 9156 // stack and we don't need to save any argregs. 9157 if (ArgRegs.size() == Idx) { 9158 VaArgOffset = CCInfo.getNextStackOffset(); 9159 VarArgsSaveSize = 0; 9160 } else { 9161 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9162 VaArgOffset = -VarArgsSaveSize; 9163 } 9164 9165 // Record the frame index of the first variable argument 9166 // which is a value necessary to VASTART. 9167 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9168 RVFI->setVarArgsFrameIndex(FI); 9169 9170 // If saving an odd number of registers then create an extra stack slot to 9171 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9172 // offsets to even-numbered registered remain 2*XLEN-aligned. 9173 if (Idx % 2) { 9174 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 9175 VarArgsSaveSize += XLenInBytes; 9176 } 9177 9178 // Copy the integer registers that may have been used for passing varargs 9179 // to the vararg save area. 9180 for (unsigned I = Idx; I < ArgRegs.size(); 9181 ++I, VaArgOffset += XLenInBytes) { 9182 const Register Reg = RegInfo.createVirtualRegister(RC); 9183 RegInfo.addLiveIn(ArgRegs[I], Reg); 9184 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 9185 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9186 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9187 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 9188 MachinePointerInfo::getFixedStack(MF, FI)); 9189 cast<StoreSDNode>(Store.getNode()) 9190 ->getMemOperand() 9191 ->setValue((Value *)nullptr); 9192 OutChains.push_back(Store); 9193 } 9194 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 9195 } 9196 9197 // All stores are grouped in one node to allow the matching between 9198 // the size of Ins and InVals. This only happens for vararg functions. 9199 if (!OutChains.empty()) { 9200 OutChains.push_back(Chain); 9201 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 9202 } 9203 9204 return Chain; 9205 } 9206 9207 /// isEligibleForTailCallOptimization - Check whether the call is eligible 9208 /// for tail call optimization. 9209 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 9210 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 9211 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 9212 const SmallVector<CCValAssign, 16> &ArgLocs) const { 9213 9214 auto &Callee = CLI.Callee; 9215 auto CalleeCC = CLI.CallConv; 9216 auto &Outs = CLI.Outs; 9217 auto &Caller = MF.getFunction(); 9218 auto CallerCC = Caller.getCallingConv(); 9219 9220 // Exception-handling functions need a special set of instructions to 9221 // indicate a return to the hardware. Tail-calling another function would 9222 // probably break this. 9223 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 9224 // should be expanded as new function attributes are introduced. 9225 if (Caller.hasFnAttribute("interrupt")) 9226 return false; 9227 9228 // Do not tail call opt if the stack is used to pass parameters. 9229 if (CCInfo.getNextStackOffset() != 0) 9230 return false; 9231 9232 // Do not tail call opt if any parameters need to be passed indirectly. 9233 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 9234 // passed indirectly. So the address of the value will be passed in a 9235 // register, or if not available, then the address is put on the stack. In 9236 // order to pass indirectly, space on the stack often needs to be allocated 9237 // in order to store the value. In this case the CCInfo.getNextStackOffset() 9238 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 9239 // are passed CCValAssign::Indirect. 9240 for (auto &VA : ArgLocs) 9241 if (VA.getLocInfo() == CCValAssign::Indirect) 9242 return false; 9243 9244 // Do not tail call opt if either caller or callee uses struct return 9245 // semantics. 9246 auto IsCallerStructRet = Caller.hasStructRetAttr(); 9247 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 9248 if (IsCallerStructRet || IsCalleeStructRet) 9249 return false; 9250 9251 // Externally-defined functions with weak linkage should not be 9252 // tail-called. The behaviour of branch instructions in this situation (as 9253 // used for tail calls) is implementation-defined, so we cannot rely on the 9254 // linker replacing the tail call with a return. 9255 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 9256 const GlobalValue *GV = G->getGlobal(); 9257 if (GV->hasExternalWeakLinkage()) 9258 return false; 9259 } 9260 9261 // The callee has to preserve all registers the caller needs to preserve. 9262 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9263 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 9264 if (CalleeCC != CallerCC) { 9265 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 9266 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 9267 return false; 9268 } 9269 9270 // Byval parameters hand the function a pointer directly into the stack area 9271 // we want to reuse during a tail call. Working around this *is* possible 9272 // but less efficient and uglier in LowerCall. 9273 for (auto &Arg : Outs) 9274 if (Arg.Flags.isByVal()) 9275 return false; 9276 9277 return true; 9278 } 9279 9280 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 9281 return DAG.getDataLayout().getPrefTypeAlign( 9282 VT.getTypeForEVT(*DAG.getContext())); 9283 } 9284 9285 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 9286 // and output parameter nodes. 9287 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 9288 SmallVectorImpl<SDValue> &InVals) const { 9289 SelectionDAG &DAG = CLI.DAG; 9290 SDLoc &DL = CLI.DL; 9291 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 9292 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 9293 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 9294 SDValue Chain = CLI.Chain; 9295 SDValue Callee = CLI.Callee; 9296 bool &IsTailCall = CLI.IsTailCall; 9297 CallingConv::ID CallConv = CLI.CallConv; 9298 bool IsVarArg = CLI.IsVarArg; 9299 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9300 MVT XLenVT = Subtarget.getXLenVT(); 9301 9302 MachineFunction &MF = DAG.getMachineFunction(); 9303 9304 // Analyze the operands of the call, assigning locations to each operand. 9305 SmallVector<CCValAssign, 16> ArgLocs; 9306 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9307 9308 if (CallConv == CallingConv::GHC) 9309 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 9310 else 9311 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 9312 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9313 : CC_RISCV); 9314 9315 // Check if it's really possible to do a tail call. 9316 if (IsTailCall) 9317 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 9318 9319 if (IsTailCall) 9320 ++NumTailCalls; 9321 else if (CLI.CB && CLI.CB->isMustTailCall()) 9322 report_fatal_error("failed to perform tail call elimination on a call " 9323 "site marked musttail"); 9324 9325 // Get a count of how many bytes are to be pushed on the stack. 9326 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 9327 9328 // Create local copies for byval args 9329 SmallVector<SDValue, 8> ByValArgs; 9330 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9331 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9332 if (!Flags.isByVal()) 9333 continue; 9334 9335 SDValue Arg = OutVals[i]; 9336 unsigned Size = Flags.getByValSize(); 9337 Align Alignment = Flags.getNonZeroByValAlign(); 9338 9339 int FI = 9340 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 9341 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9342 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 9343 9344 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 9345 /*IsVolatile=*/false, 9346 /*AlwaysInline=*/false, IsTailCall, 9347 MachinePointerInfo(), MachinePointerInfo()); 9348 ByValArgs.push_back(FIPtr); 9349 } 9350 9351 if (!IsTailCall) 9352 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 9353 9354 // Copy argument values to their designated locations. 9355 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 9356 SmallVector<SDValue, 8> MemOpChains; 9357 SDValue StackPtr; 9358 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 9359 CCValAssign &VA = ArgLocs[i]; 9360 SDValue ArgValue = OutVals[i]; 9361 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9362 9363 // Handle passing f64 on RV32D with a soft float ABI as a special case. 9364 bool IsF64OnRV32DSoftABI = 9365 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 9366 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 9367 SDValue SplitF64 = DAG.getNode( 9368 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 9369 SDValue Lo = SplitF64.getValue(0); 9370 SDValue Hi = SplitF64.getValue(1); 9371 9372 Register RegLo = VA.getLocReg(); 9373 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 9374 9375 if (RegLo == RISCV::X17) { 9376 // Second half of f64 is passed on the stack. 9377 // Work out the address of the stack slot. 9378 if (!StackPtr.getNode()) 9379 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9380 // Emit the store. 9381 MemOpChains.push_back( 9382 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 9383 } else { 9384 // Second half of f64 is passed in another GPR. 9385 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9386 Register RegHigh = RegLo + 1; 9387 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 9388 } 9389 continue; 9390 } 9391 9392 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 9393 // as any other MemLoc. 9394 9395 // Promote the value if needed. 9396 // For now, only handle fully promoted and indirect arguments. 9397 if (VA.getLocInfo() == CCValAssign::Indirect) { 9398 // Store the argument in a stack slot and pass its address. 9399 Align StackAlign = 9400 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 9401 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 9402 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 9403 // If the original argument was split (e.g. i128), we need 9404 // to store the required parts of it here (and pass just one address). 9405 // Vectors may be partly split to registers and partly to the stack, in 9406 // which case the base address is partly offset and subsequent stores are 9407 // relative to that. 9408 unsigned ArgIndex = Outs[i].OrigArgIndex; 9409 unsigned ArgPartOffset = Outs[i].PartOffset; 9410 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9411 // Calculate the total size to store. We don't have access to what we're 9412 // actually storing other than performing the loop and collecting the 9413 // info. 9414 SmallVector<std::pair<SDValue, SDValue>> Parts; 9415 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 9416 SDValue PartValue = OutVals[i + 1]; 9417 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 9418 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9419 EVT PartVT = PartValue.getValueType(); 9420 if (PartVT.isScalableVector()) 9421 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9422 StoredSize += PartVT.getStoreSize(); 9423 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 9424 Parts.push_back(std::make_pair(PartValue, Offset)); 9425 ++i; 9426 } 9427 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 9428 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 9429 MemOpChains.push_back( 9430 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 9431 MachinePointerInfo::getFixedStack(MF, FI))); 9432 for (const auto &Part : Parts) { 9433 SDValue PartValue = Part.first; 9434 SDValue PartOffset = Part.second; 9435 SDValue Address = 9436 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 9437 MemOpChains.push_back( 9438 DAG.getStore(Chain, DL, PartValue, Address, 9439 MachinePointerInfo::getFixedStack(MF, FI))); 9440 } 9441 ArgValue = SpillSlot; 9442 } else { 9443 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 9444 } 9445 9446 // Use local copy if it is a byval arg. 9447 if (Flags.isByVal()) 9448 ArgValue = ByValArgs[j++]; 9449 9450 if (VA.isRegLoc()) { 9451 // Queue up the argument copies and emit them at the end. 9452 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 9453 } else { 9454 assert(VA.isMemLoc() && "Argument not register or memory"); 9455 assert(!IsTailCall && "Tail call not allowed if stack is used " 9456 "for passing parameters"); 9457 9458 // Work out the address of the stack slot. 9459 if (!StackPtr.getNode()) 9460 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9461 SDValue Address = 9462 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9463 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9464 9465 // Emit the store. 9466 MemOpChains.push_back( 9467 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9468 } 9469 } 9470 9471 // Join the stores, which are independent of one another. 9472 if (!MemOpChains.empty()) 9473 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9474 9475 SDValue Glue; 9476 9477 // Build a sequence of copy-to-reg nodes, chained and glued together. 9478 for (auto &Reg : RegsToPass) { 9479 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9480 Glue = Chain.getValue(1); 9481 } 9482 9483 // Validate that none of the argument registers have been marked as 9484 // reserved, if so report an error. Do the same for the return address if this 9485 // is not a tailcall. 9486 validateCCReservedRegs(RegsToPass, MF); 9487 if (!IsTailCall && 9488 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9489 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9490 MF.getFunction(), 9491 "Return address register required, but has been reserved."}); 9492 9493 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9494 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9495 // split it and then direct call can be matched by PseudoCALL. 9496 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 9497 const GlobalValue *GV = S->getGlobal(); 9498 9499 unsigned OpFlags = RISCVII::MO_CALL; 9500 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 9501 OpFlags = RISCVII::MO_PLT; 9502 9503 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 9504 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 9505 unsigned OpFlags = RISCVII::MO_CALL; 9506 9507 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 9508 nullptr)) 9509 OpFlags = RISCVII::MO_PLT; 9510 9511 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 9512 } 9513 9514 // The first call operand is the chain and the second is the target address. 9515 SmallVector<SDValue, 8> Ops; 9516 Ops.push_back(Chain); 9517 Ops.push_back(Callee); 9518 9519 // Add argument registers to the end of the list so that they are 9520 // known live into the call. 9521 for (auto &Reg : RegsToPass) 9522 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 9523 9524 if (!IsTailCall) { 9525 // Add a register mask operand representing the call-preserved registers. 9526 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9527 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 9528 assert(Mask && "Missing call preserved mask for calling convention"); 9529 Ops.push_back(DAG.getRegisterMask(Mask)); 9530 } 9531 9532 // Glue the call to the argument copies, if any. 9533 if (Glue.getNode()) 9534 Ops.push_back(Glue); 9535 9536 // Emit the call. 9537 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9538 9539 if (IsTailCall) { 9540 MF.getFrameInfo().setHasTailCall(); 9541 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 9542 } 9543 9544 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 9545 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 9546 Glue = Chain.getValue(1); 9547 9548 // Mark the end of the call, which is glued to the call itself. 9549 Chain = DAG.getCALLSEQ_END(Chain, 9550 DAG.getConstant(NumBytes, DL, PtrVT, true), 9551 DAG.getConstant(0, DL, PtrVT, true), 9552 Glue, DL); 9553 Glue = Chain.getValue(1); 9554 9555 // Assign locations to each value returned by this call. 9556 SmallVector<CCValAssign, 16> RVLocs; 9557 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9558 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9559 9560 // Copy all of the result registers out of their specified physreg. 9561 for (auto &VA : RVLocs) { 9562 // Copy the value out 9563 SDValue RetValue = 9564 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9565 // Glue the RetValue to the end of the call sequence 9566 Chain = RetValue.getValue(1); 9567 Glue = RetValue.getValue(2); 9568 9569 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9570 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9571 SDValue RetValue2 = 9572 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9573 Chain = RetValue2.getValue(1); 9574 Glue = RetValue2.getValue(2); 9575 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9576 RetValue2); 9577 } 9578 9579 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9580 9581 InVals.push_back(RetValue); 9582 } 9583 9584 return Chain; 9585 } 9586 9587 bool RISCVTargetLowering::CanLowerReturn( 9588 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9589 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9590 SmallVector<CCValAssign, 16> RVLocs; 9591 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9592 9593 Optional<unsigned> FirstMaskArgument; 9594 if (Subtarget.hasVInstructions()) 9595 FirstMaskArgument = preAssignMask(Outs); 9596 9597 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9598 MVT VT = Outs[i].VT; 9599 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9600 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9601 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9602 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9603 *this, FirstMaskArgument)) 9604 return false; 9605 } 9606 return true; 9607 } 9608 9609 SDValue 9610 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9611 bool IsVarArg, 9612 const SmallVectorImpl<ISD::OutputArg> &Outs, 9613 const SmallVectorImpl<SDValue> &OutVals, 9614 const SDLoc &DL, SelectionDAG &DAG) const { 9615 const MachineFunction &MF = DAG.getMachineFunction(); 9616 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9617 9618 // Stores the assignment of the return value to a location. 9619 SmallVector<CCValAssign, 16> RVLocs; 9620 9621 // Info about the registers and stack slot. 9622 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9623 *DAG.getContext()); 9624 9625 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9626 nullptr, CC_RISCV); 9627 9628 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9629 report_fatal_error("GHC functions return void only"); 9630 9631 SDValue Glue; 9632 SmallVector<SDValue, 4> RetOps(1, Chain); 9633 9634 // Copy the result values into the output registers. 9635 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9636 SDValue Val = OutVals[i]; 9637 CCValAssign &VA = RVLocs[i]; 9638 assert(VA.isRegLoc() && "Can only return in registers!"); 9639 9640 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9641 // Handle returning f64 on RV32D with a soft float ABI. 9642 assert(VA.isRegLoc() && "Expected return via registers"); 9643 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9644 DAG.getVTList(MVT::i32, MVT::i32), Val); 9645 SDValue Lo = SplitF64.getValue(0); 9646 SDValue Hi = SplitF64.getValue(1); 9647 Register RegLo = VA.getLocReg(); 9648 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9649 Register RegHi = RegLo + 1; 9650 9651 if (STI.isRegisterReservedByUser(RegLo) || 9652 STI.isRegisterReservedByUser(RegHi)) 9653 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9654 MF.getFunction(), 9655 "Return value register required, but has been reserved."}); 9656 9657 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9658 Glue = Chain.getValue(1); 9659 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9660 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9661 Glue = Chain.getValue(1); 9662 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9663 } else { 9664 // Handle a 'normal' return. 9665 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9666 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9667 9668 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9669 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9670 MF.getFunction(), 9671 "Return value register required, but has been reserved."}); 9672 9673 // Guarantee that all emitted copies are stuck together. 9674 Glue = Chain.getValue(1); 9675 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9676 } 9677 } 9678 9679 RetOps[0] = Chain; // Update chain. 9680 9681 // Add the glue node if we have it. 9682 if (Glue.getNode()) { 9683 RetOps.push_back(Glue); 9684 } 9685 9686 unsigned RetOpc = RISCVISD::RET_FLAG; 9687 // Interrupt service routines use different return instructions. 9688 const Function &Func = DAG.getMachineFunction().getFunction(); 9689 if (Func.hasFnAttribute("interrupt")) { 9690 if (!Func.getReturnType()->isVoidTy()) 9691 report_fatal_error( 9692 "Functions with the interrupt attribute must have void return type!"); 9693 9694 MachineFunction &MF = DAG.getMachineFunction(); 9695 StringRef Kind = 9696 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9697 9698 if (Kind == "user") 9699 RetOpc = RISCVISD::URET_FLAG; 9700 else if (Kind == "supervisor") 9701 RetOpc = RISCVISD::SRET_FLAG; 9702 else 9703 RetOpc = RISCVISD::MRET_FLAG; 9704 } 9705 9706 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9707 } 9708 9709 void RISCVTargetLowering::validateCCReservedRegs( 9710 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9711 MachineFunction &MF) const { 9712 const Function &F = MF.getFunction(); 9713 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9714 9715 if (llvm::any_of(Regs, [&STI](auto Reg) { 9716 return STI.isRegisterReservedByUser(Reg.first); 9717 })) 9718 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9719 F, "Argument register required, but has been reserved."}); 9720 } 9721 9722 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9723 return CI->isTailCall(); 9724 } 9725 9726 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9727 #define NODE_NAME_CASE(NODE) \ 9728 case RISCVISD::NODE: \ 9729 return "RISCVISD::" #NODE; 9730 // clang-format off 9731 switch ((RISCVISD::NodeType)Opcode) { 9732 case RISCVISD::FIRST_NUMBER: 9733 break; 9734 NODE_NAME_CASE(RET_FLAG) 9735 NODE_NAME_CASE(URET_FLAG) 9736 NODE_NAME_CASE(SRET_FLAG) 9737 NODE_NAME_CASE(MRET_FLAG) 9738 NODE_NAME_CASE(CALL) 9739 NODE_NAME_CASE(SELECT_CC) 9740 NODE_NAME_CASE(BR_CC) 9741 NODE_NAME_CASE(BuildPairF64) 9742 NODE_NAME_CASE(SplitF64) 9743 NODE_NAME_CASE(TAIL) 9744 NODE_NAME_CASE(MULHSU) 9745 NODE_NAME_CASE(SLLW) 9746 NODE_NAME_CASE(SRAW) 9747 NODE_NAME_CASE(SRLW) 9748 NODE_NAME_CASE(DIVW) 9749 NODE_NAME_CASE(DIVUW) 9750 NODE_NAME_CASE(REMUW) 9751 NODE_NAME_CASE(ROLW) 9752 NODE_NAME_CASE(RORW) 9753 NODE_NAME_CASE(CLZW) 9754 NODE_NAME_CASE(CTZW) 9755 NODE_NAME_CASE(FSLW) 9756 NODE_NAME_CASE(FSRW) 9757 NODE_NAME_CASE(FSL) 9758 NODE_NAME_CASE(FSR) 9759 NODE_NAME_CASE(FMV_H_X) 9760 NODE_NAME_CASE(FMV_X_ANYEXTH) 9761 NODE_NAME_CASE(FMV_W_X_RV64) 9762 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9763 NODE_NAME_CASE(FCVT_X) 9764 NODE_NAME_CASE(FCVT_XU) 9765 NODE_NAME_CASE(FCVT_W_RV64) 9766 NODE_NAME_CASE(FCVT_WU_RV64) 9767 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 9768 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 9769 NODE_NAME_CASE(READ_CYCLE_WIDE) 9770 NODE_NAME_CASE(GREV) 9771 NODE_NAME_CASE(GREVW) 9772 NODE_NAME_CASE(GORC) 9773 NODE_NAME_CASE(GORCW) 9774 NODE_NAME_CASE(SHFL) 9775 NODE_NAME_CASE(SHFLW) 9776 NODE_NAME_CASE(UNSHFL) 9777 NODE_NAME_CASE(UNSHFLW) 9778 NODE_NAME_CASE(BFP) 9779 NODE_NAME_CASE(BFPW) 9780 NODE_NAME_CASE(BCOMPRESS) 9781 NODE_NAME_CASE(BCOMPRESSW) 9782 NODE_NAME_CASE(BDECOMPRESS) 9783 NODE_NAME_CASE(BDECOMPRESSW) 9784 NODE_NAME_CASE(VMV_V_X_VL) 9785 NODE_NAME_CASE(VFMV_V_F_VL) 9786 NODE_NAME_CASE(VMV_X_S) 9787 NODE_NAME_CASE(VMV_S_X_VL) 9788 NODE_NAME_CASE(VFMV_S_F_VL) 9789 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9790 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9791 NODE_NAME_CASE(READ_VLENB) 9792 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9793 NODE_NAME_CASE(VSLIDEUP_VL) 9794 NODE_NAME_CASE(VSLIDE1UP_VL) 9795 NODE_NAME_CASE(VSLIDEDOWN_VL) 9796 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9797 NODE_NAME_CASE(VID_VL) 9798 NODE_NAME_CASE(VFNCVT_ROD_VL) 9799 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9800 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9801 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9802 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9803 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9804 NODE_NAME_CASE(VECREDUCE_AND_VL) 9805 NODE_NAME_CASE(VECREDUCE_OR_VL) 9806 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9807 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9808 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9809 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9810 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9811 NODE_NAME_CASE(ADD_VL) 9812 NODE_NAME_CASE(AND_VL) 9813 NODE_NAME_CASE(MUL_VL) 9814 NODE_NAME_CASE(OR_VL) 9815 NODE_NAME_CASE(SDIV_VL) 9816 NODE_NAME_CASE(SHL_VL) 9817 NODE_NAME_CASE(SREM_VL) 9818 NODE_NAME_CASE(SRA_VL) 9819 NODE_NAME_CASE(SRL_VL) 9820 NODE_NAME_CASE(SUB_VL) 9821 NODE_NAME_CASE(UDIV_VL) 9822 NODE_NAME_CASE(UREM_VL) 9823 NODE_NAME_CASE(XOR_VL) 9824 NODE_NAME_CASE(SADDSAT_VL) 9825 NODE_NAME_CASE(UADDSAT_VL) 9826 NODE_NAME_CASE(SSUBSAT_VL) 9827 NODE_NAME_CASE(USUBSAT_VL) 9828 NODE_NAME_CASE(FADD_VL) 9829 NODE_NAME_CASE(FSUB_VL) 9830 NODE_NAME_CASE(FMUL_VL) 9831 NODE_NAME_CASE(FDIV_VL) 9832 NODE_NAME_CASE(FNEG_VL) 9833 NODE_NAME_CASE(FABS_VL) 9834 NODE_NAME_CASE(FSQRT_VL) 9835 NODE_NAME_CASE(FMA_VL) 9836 NODE_NAME_CASE(FCOPYSIGN_VL) 9837 NODE_NAME_CASE(SMIN_VL) 9838 NODE_NAME_CASE(SMAX_VL) 9839 NODE_NAME_CASE(UMIN_VL) 9840 NODE_NAME_CASE(UMAX_VL) 9841 NODE_NAME_CASE(FMINNUM_VL) 9842 NODE_NAME_CASE(FMAXNUM_VL) 9843 NODE_NAME_CASE(MULHS_VL) 9844 NODE_NAME_CASE(MULHU_VL) 9845 NODE_NAME_CASE(FP_TO_SINT_VL) 9846 NODE_NAME_CASE(FP_TO_UINT_VL) 9847 NODE_NAME_CASE(SINT_TO_FP_VL) 9848 NODE_NAME_CASE(UINT_TO_FP_VL) 9849 NODE_NAME_CASE(FP_EXTEND_VL) 9850 NODE_NAME_CASE(FP_ROUND_VL) 9851 NODE_NAME_CASE(VWMUL_VL) 9852 NODE_NAME_CASE(VWMULU_VL) 9853 NODE_NAME_CASE(SETCC_VL) 9854 NODE_NAME_CASE(VSELECT_VL) 9855 NODE_NAME_CASE(VMAND_VL) 9856 NODE_NAME_CASE(VMOR_VL) 9857 NODE_NAME_CASE(VMXOR_VL) 9858 NODE_NAME_CASE(VMCLR_VL) 9859 NODE_NAME_CASE(VMSET_VL) 9860 NODE_NAME_CASE(VRGATHER_VX_VL) 9861 NODE_NAME_CASE(VRGATHER_VV_VL) 9862 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9863 NODE_NAME_CASE(VSEXT_VL) 9864 NODE_NAME_CASE(VZEXT_VL) 9865 NODE_NAME_CASE(VCPOP_VL) 9866 NODE_NAME_CASE(VLE_VL) 9867 NODE_NAME_CASE(VSE_VL) 9868 NODE_NAME_CASE(READ_CSR) 9869 NODE_NAME_CASE(WRITE_CSR) 9870 NODE_NAME_CASE(SWAP_CSR) 9871 } 9872 // clang-format on 9873 return nullptr; 9874 #undef NODE_NAME_CASE 9875 } 9876 9877 /// getConstraintType - Given a constraint letter, return the type of 9878 /// constraint it is for this target. 9879 RISCVTargetLowering::ConstraintType 9880 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9881 if (Constraint.size() == 1) { 9882 switch (Constraint[0]) { 9883 default: 9884 break; 9885 case 'f': 9886 return C_RegisterClass; 9887 case 'I': 9888 case 'J': 9889 case 'K': 9890 return C_Immediate; 9891 case 'A': 9892 return C_Memory; 9893 case 'S': // A symbolic address 9894 return C_Other; 9895 } 9896 } else { 9897 if (Constraint == "vr" || Constraint == "vm") 9898 return C_RegisterClass; 9899 } 9900 return TargetLowering::getConstraintType(Constraint); 9901 } 9902 9903 std::pair<unsigned, const TargetRegisterClass *> 9904 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9905 StringRef Constraint, 9906 MVT VT) const { 9907 // First, see if this is a constraint that directly corresponds to a 9908 // RISCV register class. 9909 if (Constraint.size() == 1) { 9910 switch (Constraint[0]) { 9911 case 'r': 9912 // TODO: Support fixed vectors up to XLen for P extension? 9913 if (VT.isVector()) 9914 break; 9915 return std::make_pair(0U, &RISCV::GPRRegClass); 9916 case 'f': 9917 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9918 return std::make_pair(0U, &RISCV::FPR16RegClass); 9919 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9920 return std::make_pair(0U, &RISCV::FPR32RegClass); 9921 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9922 return std::make_pair(0U, &RISCV::FPR64RegClass); 9923 break; 9924 default: 9925 break; 9926 } 9927 } else if (Constraint == "vr") { 9928 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9929 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9930 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9931 return std::make_pair(0U, RC); 9932 } 9933 } else if (Constraint == "vm") { 9934 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 9935 return std::make_pair(0U, &RISCV::VMV0RegClass); 9936 } 9937 9938 // Clang will correctly decode the usage of register name aliases into their 9939 // official names. However, other frontends like `rustc` do not. This allows 9940 // users of these frontends to use the ABI names for registers in LLVM-style 9941 // register constraints. 9942 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9943 .Case("{zero}", RISCV::X0) 9944 .Case("{ra}", RISCV::X1) 9945 .Case("{sp}", RISCV::X2) 9946 .Case("{gp}", RISCV::X3) 9947 .Case("{tp}", RISCV::X4) 9948 .Case("{t0}", RISCV::X5) 9949 .Case("{t1}", RISCV::X6) 9950 .Case("{t2}", RISCV::X7) 9951 .Cases("{s0}", "{fp}", RISCV::X8) 9952 .Case("{s1}", RISCV::X9) 9953 .Case("{a0}", RISCV::X10) 9954 .Case("{a1}", RISCV::X11) 9955 .Case("{a2}", RISCV::X12) 9956 .Case("{a3}", RISCV::X13) 9957 .Case("{a4}", RISCV::X14) 9958 .Case("{a5}", RISCV::X15) 9959 .Case("{a6}", RISCV::X16) 9960 .Case("{a7}", RISCV::X17) 9961 .Case("{s2}", RISCV::X18) 9962 .Case("{s3}", RISCV::X19) 9963 .Case("{s4}", RISCV::X20) 9964 .Case("{s5}", RISCV::X21) 9965 .Case("{s6}", RISCV::X22) 9966 .Case("{s7}", RISCV::X23) 9967 .Case("{s8}", RISCV::X24) 9968 .Case("{s9}", RISCV::X25) 9969 .Case("{s10}", RISCV::X26) 9970 .Case("{s11}", RISCV::X27) 9971 .Case("{t3}", RISCV::X28) 9972 .Case("{t4}", RISCV::X29) 9973 .Case("{t5}", RISCV::X30) 9974 .Case("{t6}", RISCV::X31) 9975 .Default(RISCV::NoRegister); 9976 if (XRegFromAlias != RISCV::NoRegister) 9977 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9978 9979 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9980 // TableGen record rather than the AsmName to choose registers for InlineAsm 9981 // constraints, plus we want to match those names to the widest floating point 9982 // register type available, manually select floating point registers here. 9983 // 9984 // The second case is the ABI name of the register, so that frontends can also 9985 // use the ABI names in register constraint lists. 9986 if (Subtarget.hasStdExtF()) { 9987 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9988 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9989 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9990 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9991 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9992 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9993 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9994 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9995 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9996 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9997 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9998 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9999 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10000 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10001 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10002 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10003 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10004 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10005 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10006 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10007 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10008 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10009 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10010 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10011 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10012 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10013 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10014 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10015 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10016 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10017 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10018 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10019 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10020 .Default(RISCV::NoRegister); 10021 if (FReg != RISCV::NoRegister) { 10022 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10023 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10024 unsigned RegNo = FReg - RISCV::F0_F; 10025 unsigned DReg = RISCV::F0_D + RegNo; 10026 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10027 } 10028 if (VT == MVT::f32 || VT == MVT::Other) 10029 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10030 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10031 unsigned RegNo = FReg - RISCV::F0_F; 10032 unsigned HReg = RISCV::F0_H + RegNo; 10033 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10034 } 10035 } 10036 } 10037 10038 if (Subtarget.hasVInstructions()) { 10039 Register VReg = StringSwitch<Register>(Constraint.lower()) 10040 .Case("{v0}", RISCV::V0) 10041 .Case("{v1}", RISCV::V1) 10042 .Case("{v2}", RISCV::V2) 10043 .Case("{v3}", RISCV::V3) 10044 .Case("{v4}", RISCV::V4) 10045 .Case("{v5}", RISCV::V5) 10046 .Case("{v6}", RISCV::V6) 10047 .Case("{v7}", RISCV::V7) 10048 .Case("{v8}", RISCV::V8) 10049 .Case("{v9}", RISCV::V9) 10050 .Case("{v10}", RISCV::V10) 10051 .Case("{v11}", RISCV::V11) 10052 .Case("{v12}", RISCV::V12) 10053 .Case("{v13}", RISCV::V13) 10054 .Case("{v14}", RISCV::V14) 10055 .Case("{v15}", RISCV::V15) 10056 .Case("{v16}", RISCV::V16) 10057 .Case("{v17}", RISCV::V17) 10058 .Case("{v18}", RISCV::V18) 10059 .Case("{v19}", RISCV::V19) 10060 .Case("{v20}", RISCV::V20) 10061 .Case("{v21}", RISCV::V21) 10062 .Case("{v22}", RISCV::V22) 10063 .Case("{v23}", RISCV::V23) 10064 .Case("{v24}", RISCV::V24) 10065 .Case("{v25}", RISCV::V25) 10066 .Case("{v26}", RISCV::V26) 10067 .Case("{v27}", RISCV::V27) 10068 .Case("{v28}", RISCV::V28) 10069 .Case("{v29}", RISCV::V29) 10070 .Case("{v30}", RISCV::V30) 10071 .Case("{v31}", RISCV::V31) 10072 .Default(RISCV::NoRegister); 10073 if (VReg != RISCV::NoRegister) { 10074 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10075 return std::make_pair(VReg, &RISCV::VMRegClass); 10076 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10077 return std::make_pair(VReg, &RISCV::VRRegClass); 10078 for (const auto *RC : 10079 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10080 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10081 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10082 return std::make_pair(VReg, RC); 10083 } 10084 } 10085 } 10086 } 10087 10088 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10089 } 10090 10091 unsigned 10092 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10093 // Currently only support length 1 constraints. 10094 if (ConstraintCode.size() == 1) { 10095 switch (ConstraintCode[0]) { 10096 case 'A': 10097 return InlineAsm::Constraint_A; 10098 default: 10099 break; 10100 } 10101 } 10102 10103 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10104 } 10105 10106 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10107 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10108 SelectionDAG &DAG) const { 10109 // Currently only support length 1 constraints. 10110 if (Constraint.length() == 1) { 10111 switch (Constraint[0]) { 10112 case 'I': 10113 // Validate & create a 12-bit signed immediate operand. 10114 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10115 uint64_t CVal = C->getSExtValue(); 10116 if (isInt<12>(CVal)) 10117 Ops.push_back( 10118 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10119 } 10120 return; 10121 case 'J': 10122 // Validate & create an integer zero operand. 10123 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10124 if (C->getZExtValue() == 0) 10125 Ops.push_back( 10126 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10127 return; 10128 case 'K': 10129 // Validate & create a 5-bit unsigned immediate operand. 10130 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10131 uint64_t CVal = C->getZExtValue(); 10132 if (isUInt<5>(CVal)) 10133 Ops.push_back( 10134 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10135 } 10136 return; 10137 case 'S': 10138 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10139 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10140 GA->getValueType(0))); 10141 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10142 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10143 BA->getValueType(0))); 10144 } 10145 return; 10146 default: 10147 break; 10148 } 10149 } 10150 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10151 } 10152 10153 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10154 Instruction *Inst, 10155 AtomicOrdering Ord) const { 10156 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10157 return Builder.CreateFence(Ord); 10158 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10159 return Builder.CreateFence(AtomicOrdering::Release); 10160 return nullptr; 10161 } 10162 10163 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10164 Instruction *Inst, 10165 AtomicOrdering Ord) const { 10166 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 10167 return Builder.CreateFence(AtomicOrdering::Acquire); 10168 return nullptr; 10169 } 10170 10171 TargetLowering::AtomicExpansionKind 10172 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10173 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 10174 // point operations can't be used in an lr/sc sequence without breaking the 10175 // forward-progress guarantee. 10176 if (AI->isFloatingPointOperation()) 10177 return AtomicExpansionKind::CmpXChg; 10178 10179 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10180 if (Size == 8 || Size == 16) 10181 return AtomicExpansionKind::MaskedIntrinsic; 10182 return AtomicExpansionKind::None; 10183 } 10184 10185 static Intrinsic::ID 10186 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 10187 if (XLen == 32) { 10188 switch (BinOp) { 10189 default: 10190 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10191 case AtomicRMWInst::Xchg: 10192 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 10193 case AtomicRMWInst::Add: 10194 return Intrinsic::riscv_masked_atomicrmw_add_i32; 10195 case AtomicRMWInst::Sub: 10196 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 10197 case AtomicRMWInst::Nand: 10198 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 10199 case AtomicRMWInst::Max: 10200 return Intrinsic::riscv_masked_atomicrmw_max_i32; 10201 case AtomicRMWInst::Min: 10202 return Intrinsic::riscv_masked_atomicrmw_min_i32; 10203 case AtomicRMWInst::UMax: 10204 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 10205 case AtomicRMWInst::UMin: 10206 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 10207 } 10208 } 10209 10210 if (XLen == 64) { 10211 switch (BinOp) { 10212 default: 10213 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10214 case AtomicRMWInst::Xchg: 10215 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 10216 case AtomicRMWInst::Add: 10217 return Intrinsic::riscv_masked_atomicrmw_add_i64; 10218 case AtomicRMWInst::Sub: 10219 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 10220 case AtomicRMWInst::Nand: 10221 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 10222 case AtomicRMWInst::Max: 10223 return Intrinsic::riscv_masked_atomicrmw_max_i64; 10224 case AtomicRMWInst::Min: 10225 return Intrinsic::riscv_masked_atomicrmw_min_i64; 10226 case AtomicRMWInst::UMax: 10227 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 10228 case AtomicRMWInst::UMin: 10229 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 10230 } 10231 } 10232 10233 llvm_unreachable("Unexpected XLen\n"); 10234 } 10235 10236 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 10237 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 10238 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 10239 unsigned XLen = Subtarget.getXLen(); 10240 Value *Ordering = 10241 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 10242 Type *Tys[] = {AlignedAddr->getType()}; 10243 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 10244 AI->getModule(), 10245 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 10246 10247 if (XLen == 64) { 10248 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 10249 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10250 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 10251 } 10252 10253 Value *Result; 10254 10255 // Must pass the shift amount needed to sign extend the loaded value prior 10256 // to performing a signed comparison for min/max. ShiftAmt is the number of 10257 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 10258 // is the number of bits to left+right shift the value in order to 10259 // sign-extend. 10260 if (AI->getOperation() == AtomicRMWInst::Min || 10261 AI->getOperation() == AtomicRMWInst::Max) { 10262 const DataLayout &DL = AI->getModule()->getDataLayout(); 10263 unsigned ValWidth = 10264 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 10265 Value *SextShamt = 10266 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 10267 Result = Builder.CreateCall(LrwOpScwLoop, 10268 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 10269 } else { 10270 Result = 10271 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 10272 } 10273 10274 if (XLen == 64) 10275 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10276 return Result; 10277 } 10278 10279 TargetLowering::AtomicExpansionKind 10280 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 10281 AtomicCmpXchgInst *CI) const { 10282 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 10283 if (Size == 8 || Size == 16) 10284 return AtomicExpansionKind::MaskedIntrinsic; 10285 return AtomicExpansionKind::None; 10286 } 10287 10288 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 10289 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 10290 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 10291 unsigned XLen = Subtarget.getXLen(); 10292 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 10293 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 10294 if (XLen == 64) { 10295 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 10296 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 10297 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10298 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 10299 } 10300 Type *Tys[] = {AlignedAddr->getType()}; 10301 Function *MaskedCmpXchg = 10302 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 10303 Value *Result = Builder.CreateCall( 10304 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 10305 if (XLen == 64) 10306 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10307 return Result; 10308 } 10309 10310 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 10311 return false; 10312 } 10313 10314 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 10315 EVT VT) const { 10316 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 10317 return false; 10318 10319 switch (FPVT.getSimpleVT().SimpleTy) { 10320 case MVT::f16: 10321 return Subtarget.hasStdExtZfh(); 10322 case MVT::f32: 10323 return Subtarget.hasStdExtF(); 10324 case MVT::f64: 10325 return Subtarget.hasStdExtD(); 10326 default: 10327 return false; 10328 } 10329 } 10330 10331 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 10332 // If we are using the small code model, we can reduce size of jump table 10333 // entry to 4 bytes. 10334 if (Subtarget.is64Bit() && !isPositionIndependent() && 10335 getTargetMachine().getCodeModel() == CodeModel::Small) { 10336 return MachineJumpTableInfo::EK_Custom32; 10337 } 10338 return TargetLowering::getJumpTableEncoding(); 10339 } 10340 10341 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 10342 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 10343 unsigned uid, MCContext &Ctx) const { 10344 assert(Subtarget.is64Bit() && !isPositionIndependent() && 10345 getTargetMachine().getCodeModel() == CodeModel::Small); 10346 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 10347 } 10348 10349 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 10350 EVT VT) const { 10351 VT = VT.getScalarType(); 10352 10353 if (!VT.isSimple()) 10354 return false; 10355 10356 switch (VT.getSimpleVT().SimpleTy) { 10357 case MVT::f16: 10358 return Subtarget.hasStdExtZfh(); 10359 case MVT::f32: 10360 return Subtarget.hasStdExtF(); 10361 case MVT::f64: 10362 return Subtarget.hasStdExtD(); 10363 default: 10364 break; 10365 } 10366 10367 return false; 10368 } 10369 10370 Register RISCVTargetLowering::getExceptionPointerRegister( 10371 const Constant *PersonalityFn) const { 10372 return RISCV::X10; 10373 } 10374 10375 Register RISCVTargetLowering::getExceptionSelectorRegister( 10376 const Constant *PersonalityFn) const { 10377 return RISCV::X11; 10378 } 10379 10380 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 10381 // Return false to suppress the unnecessary extensions if the LibCall 10382 // arguments or return value is f32 type for LP64 ABI. 10383 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 10384 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 10385 return false; 10386 10387 return true; 10388 } 10389 10390 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 10391 if (Subtarget.is64Bit() && Type == MVT::i32) 10392 return true; 10393 10394 return IsSigned; 10395 } 10396 10397 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 10398 SDValue C) const { 10399 // Check integral scalar types. 10400 if (VT.isScalarInteger()) { 10401 // Omit the optimization if the sub target has the M extension and the data 10402 // size exceeds XLen. 10403 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 10404 return false; 10405 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 10406 // Break the MUL to a SLLI and an ADD/SUB. 10407 const APInt &Imm = ConstNode->getAPIntValue(); 10408 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 10409 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 10410 return true; 10411 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 10412 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 10413 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 10414 (Imm - 8).isPowerOf2())) 10415 return true; 10416 // Omit the following optimization if the sub target has the M extension 10417 // and the data size >= XLen. 10418 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 10419 return false; 10420 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 10421 // a pair of LUI/ADDI. 10422 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 10423 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 10424 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 10425 (1 - ImmS).isPowerOf2()) 10426 return true; 10427 } 10428 } 10429 } 10430 10431 return false; 10432 } 10433 10434 bool RISCVTargetLowering::isMulAddWithConstProfitable( 10435 const SDValue &AddNode, const SDValue &ConstNode) const { 10436 // Let the DAGCombiner decide for vectors. 10437 EVT VT = AddNode.getValueType(); 10438 if (VT.isVector()) 10439 return true; 10440 10441 // Let the DAGCombiner decide for larger types. 10442 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 10443 return true; 10444 10445 // It is worse if c1 is simm12 while c1*c2 is not. 10446 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 10447 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 10448 const APInt &C1 = C1Node->getAPIntValue(); 10449 const APInt &C2 = C2Node->getAPIntValue(); 10450 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 10451 return false; 10452 10453 // Default to true and let the DAGCombiner decide. 10454 return true; 10455 } 10456 10457 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 10458 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 10459 bool *Fast) const { 10460 if (!VT.isVector()) 10461 return false; 10462 10463 EVT ElemVT = VT.getVectorElementType(); 10464 if (Alignment >= ElemVT.getStoreSize()) { 10465 if (Fast) 10466 *Fast = true; 10467 return true; 10468 } 10469 10470 return false; 10471 } 10472 10473 bool RISCVTargetLowering::splitValueIntoRegisterParts( 10474 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 10475 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 10476 bool IsABIRegCopy = CC.hasValue(); 10477 EVT ValueVT = Val.getValueType(); 10478 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10479 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 10480 // and cast to f32. 10481 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 10482 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 10483 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 10484 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 10485 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 10486 Parts[0] = Val; 10487 return true; 10488 } 10489 10490 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10491 LLVMContext &Context = *DAG.getContext(); 10492 EVT ValueEltVT = ValueVT.getVectorElementType(); 10493 EVT PartEltVT = PartVT.getVectorElementType(); 10494 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10495 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10496 if (PartVTBitSize % ValueVTBitSize == 0) { 10497 assert(PartVTBitSize >= ValueVTBitSize); 10498 // If the element types are different, bitcast to the same element type of 10499 // PartVT first. 10500 // Give an example here, we want copy a <vscale x 1 x i8> value to 10501 // <vscale x 4 x i16>. 10502 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 10503 // subvector, then we can bitcast to <vscale x 4 x i16>. 10504 if (ValueEltVT != PartEltVT) { 10505 if (PartVTBitSize > ValueVTBitSize) { 10506 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10507 assert(Count != 0 && "The number of element should not be zero."); 10508 EVT SameEltTypeVT = 10509 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10510 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 10511 DAG.getUNDEF(SameEltTypeVT), Val, 10512 DAG.getVectorIdxConstant(0, DL)); 10513 } 10514 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 10515 } else { 10516 Val = 10517 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 10518 Val, DAG.getVectorIdxConstant(0, DL)); 10519 } 10520 Parts[0] = Val; 10521 return true; 10522 } 10523 } 10524 return false; 10525 } 10526 10527 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 10528 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 10529 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 10530 bool IsABIRegCopy = CC.hasValue(); 10531 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10532 SDValue Val = Parts[0]; 10533 10534 // Cast the f32 to i32, truncate to i16, and cast back to f16. 10535 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 10536 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 10537 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 10538 return Val; 10539 } 10540 10541 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10542 LLVMContext &Context = *DAG.getContext(); 10543 SDValue Val = Parts[0]; 10544 EVT ValueEltVT = ValueVT.getVectorElementType(); 10545 EVT PartEltVT = PartVT.getVectorElementType(); 10546 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10547 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10548 if (PartVTBitSize % ValueVTBitSize == 0) { 10549 assert(PartVTBitSize >= ValueVTBitSize); 10550 EVT SameEltTypeVT = ValueVT; 10551 // If the element types are different, convert it to the same element type 10552 // of PartVT. 10553 // Give an example here, we want copy a <vscale x 1 x i8> value from 10554 // <vscale x 4 x i16>. 10555 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 10556 // then we can extract <vscale x 1 x i8>. 10557 if (ValueEltVT != PartEltVT) { 10558 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10559 assert(Count != 0 && "The number of element should not be zero."); 10560 SameEltTypeVT = 10561 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10562 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 10563 } 10564 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 10565 DAG.getVectorIdxConstant(0, DL)); 10566 return Val; 10567 } 10568 } 10569 return SDValue(); 10570 } 10571 10572 SDValue 10573 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 10574 SelectionDAG &DAG, 10575 SmallVectorImpl<SDNode *> &Created) const { 10576 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 10577 if (isIntDivCheap(N->getValueType(0), Attr)) 10578 return SDValue(N, 0); // Lower SDIV as SDIV 10579 10580 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 10581 "Unexpected divisor!"); 10582 10583 // Conditional move is needed, so do the transformation iff Zbt is enabled. 10584 if (!Subtarget.hasStdExtZbt()) 10585 return SDValue(); 10586 10587 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 10588 // Besides, more critical path instructions will be generated when dividing 10589 // by 2. So we keep using the original DAGs for these cases. 10590 unsigned Lg2 = Divisor.countTrailingZeros(); 10591 if (Lg2 == 1 || Lg2 >= 12) 10592 return SDValue(); 10593 10594 // fold (sdiv X, pow2) 10595 EVT VT = N->getValueType(0); 10596 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 10597 return SDValue(); 10598 10599 SDLoc DL(N); 10600 SDValue N0 = N->getOperand(0); 10601 SDValue Zero = DAG.getConstant(0, DL, VT); 10602 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 10603 10604 // Add (N0 < 0) ? Pow2 - 1 : 0; 10605 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 10606 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 10607 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 10608 10609 Created.push_back(Cmp.getNode()); 10610 Created.push_back(Add.getNode()); 10611 Created.push_back(Sel.getNode()); 10612 10613 // Divide by pow2. 10614 SDValue SRA = 10615 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 10616 10617 // If we're dividing by a positive value, we're done. Otherwise, we must 10618 // negate the result. 10619 if (Divisor.isNonNegative()) 10620 return SRA; 10621 10622 Created.push_back(SRA.getNode()); 10623 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 10624 } 10625 10626 #define GET_REGISTER_MATCHER 10627 #include "RISCVGenAsmMatcher.inc" 10628 10629 Register 10630 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 10631 const MachineFunction &MF) const { 10632 Register Reg = MatchRegisterAltName(RegName); 10633 if (Reg == RISCV::NoRegister) 10634 Reg = MatchRegisterName(RegName); 10635 if (Reg == RISCV::NoRegister) 10636 report_fatal_error( 10637 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 10638 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 10639 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 10640 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 10641 StringRef(RegName) + "\".")); 10642 return Reg; 10643 } 10644 10645 namespace llvm { 10646 namespace RISCVVIntrinsicsTable { 10647 10648 #define GET_RISCVVIntrinsicsTable_IMPL 10649 #include "RISCVGenSearchableTables.inc" 10650 10651 } // namespace RISCVVIntrinsicsTable 10652 10653 } // namespace llvm 10654