1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 29 #include "llvm/CodeGen/ValueTypes.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/DiagnosticPrinter.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/IntrinsicsRISCV.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/KnownBits.h" 38 #include "llvm/Support/MathExtras.h" 39 #include "llvm/Support/raw_ostream.h" 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "riscv-lower" 44 45 STATISTIC(NumTailCalls, "Number of tail calls"); 46 47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 48 const RISCVSubtarget &STI) 49 : TargetLowering(TM), Subtarget(STI) { 50 51 if (Subtarget.isRV32E()) 52 report_fatal_error("Codegen not yet implemented for RV32E"); 53 54 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 55 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 56 57 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 58 !Subtarget.hasStdExtF()) { 59 errs() << "Hard-float 'f' ABI can't be used for a target that " 60 "doesn't support the F instruction set extension (ignoring " 61 "target-abi)\n"; 62 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 63 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 64 !Subtarget.hasStdExtD()) { 65 errs() << "Hard-float 'd' ABI can't be used for a target that " 66 "doesn't support the D instruction set extension (ignoring " 67 "target-abi)\n"; 68 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 69 } 70 71 switch (ABI) { 72 default: 73 report_fatal_error("Don't know how to lower this ABI"); 74 case RISCVABI::ABI_ILP32: 75 case RISCVABI::ABI_ILP32F: 76 case RISCVABI::ABI_ILP32D: 77 case RISCVABI::ABI_LP64: 78 case RISCVABI::ABI_LP64F: 79 case RISCVABI::ABI_LP64D: 80 break; 81 } 82 83 MVT XLenVT = Subtarget.getXLenVT(); 84 85 // Set up the register classes. 86 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 87 88 if (Subtarget.hasStdExtZfh()) 89 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 90 if (Subtarget.hasStdExtF()) 91 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 92 if (Subtarget.hasStdExtD()) 93 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 94 95 static const MVT::SimpleValueType BoolVecVTs[] = { 96 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 97 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 98 static const MVT::SimpleValueType IntVecVTs[] = { 99 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 100 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 101 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 102 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 103 MVT::nxv4i64, MVT::nxv8i64}; 104 static const MVT::SimpleValueType F16VecVTs[] = { 105 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 106 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 107 static const MVT::SimpleValueType F32VecVTs[] = { 108 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 109 static const MVT::SimpleValueType F64VecVTs[] = { 110 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 111 112 if (Subtarget.hasVInstructions()) { 113 auto addRegClassForRVV = [this](MVT VT) { 114 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 115 assert(Size <= 512 && isPowerOf2_32(Size)); 116 const TargetRegisterClass *RC; 117 if (Size <= 64) 118 RC = &RISCV::VRRegClass; 119 else if (Size == 128) 120 RC = &RISCV::VRM2RegClass; 121 else if (Size == 256) 122 RC = &RISCV::VRM4RegClass; 123 else 124 RC = &RISCV::VRM8RegClass; 125 126 addRegisterClass(VT, RC); 127 }; 128 129 for (MVT VT : BoolVecVTs) 130 addRegClassForRVV(VT); 131 for (MVT VT : IntVecVTs) { 132 if (VT.getVectorElementType() == MVT::i64 && 133 !Subtarget.hasVInstructionsI64()) 134 continue; 135 addRegClassForRVV(VT); 136 } 137 138 if (Subtarget.hasVInstructionsF16()) 139 for (MVT VT : F16VecVTs) 140 addRegClassForRVV(VT); 141 142 if (Subtarget.hasVInstructionsF32()) 143 for (MVT VT : F32VecVTs) 144 addRegClassForRVV(VT); 145 146 if (Subtarget.hasVInstructionsF64()) 147 for (MVT VT : F64VecVTs) 148 addRegClassForRVV(VT); 149 150 if (Subtarget.useRVVForFixedLengthVectors()) { 151 auto addRegClassForFixedVectors = [this](MVT VT) { 152 MVT ContainerVT = getContainerForFixedLengthVector(VT); 153 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 154 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 155 addRegisterClass(VT, TRI.getRegClass(RCID)); 156 }; 157 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 158 if (useRVVForFixedLengthVectorVT(VT)) 159 addRegClassForFixedVectors(VT); 160 161 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 162 if (useRVVForFixedLengthVectorVT(VT)) 163 addRegClassForFixedVectors(VT); 164 } 165 } 166 167 // Compute derived properties from the register classes. 168 computeRegisterProperties(STI.getRegisterInfo()); 169 170 setStackPointerRegisterToSaveRestore(RISCV::X2); 171 172 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 173 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 174 175 // TODO: add all necessary setOperationAction calls. 176 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 177 178 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 179 setOperationAction(ISD::BR_CC, XLenVT, Expand); 180 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 181 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 182 183 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 184 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 185 186 setOperationAction(ISD::VASTART, MVT::Other, Custom); 187 setOperationAction(ISD::VAARG, MVT::Other, Expand); 188 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 189 setOperationAction(ISD::VAEND, MVT::Other, Expand); 190 191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 192 if (!Subtarget.hasStdExtZbb()) { 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 195 } 196 197 if (Subtarget.is64Bit()) { 198 setOperationAction(ISD::ADD, MVT::i32, Custom); 199 setOperationAction(ISD::SUB, MVT::i32, Custom); 200 setOperationAction(ISD::SHL, MVT::i32, Custom); 201 setOperationAction(ISD::SRA, MVT::i32, Custom); 202 setOperationAction(ISD::SRL, MVT::i32, Custom); 203 204 setOperationAction(ISD::UADDO, MVT::i32, Custom); 205 setOperationAction(ISD::USUBO, MVT::i32, Custom); 206 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 207 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 208 } else { 209 setLibcallName(RTLIB::SHL_I128, nullptr); 210 setLibcallName(RTLIB::SRL_I128, nullptr); 211 setLibcallName(RTLIB::SRA_I128, nullptr); 212 setLibcallName(RTLIB::MUL_I128, nullptr); 213 setLibcallName(RTLIB::MULO_I64, nullptr); 214 } 215 216 if (!Subtarget.hasStdExtM()) { 217 setOperationAction(ISD::MUL, XLenVT, Expand); 218 setOperationAction(ISD::MULHS, XLenVT, Expand); 219 setOperationAction(ISD::MULHU, XLenVT, Expand); 220 setOperationAction(ISD::SDIV, XLenVT, Expand); 221 setOperationAction(ISD::UDIV, XLenVT, Expand); 222 setOperationAction(ISD::SREM, XLenVT, Expand); 223 setOperationAction(ISD::UREM, XLenVT, Expand); 224 } else { 225 if (Subtarget.is64Bit()) { 226 setOperationAction(ISD::MUL, MVT::i32, Custom); 227 setOperationAction(ISD::MUL, MVT::i128, Custom); 228 229 setOperationAction(ISD::SDIV, MVT::i8, Custom); 230 setOperationAction(ISD::UDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UREM, MVT::i8, Custom); 232 setOperationAction(ISD::SDIV, MVT::i16, Custom); 233 setOperationAction(ISD::UDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UREM, MVT::i16, Custom); 235 setOperationAction(ISD::SDIV, MVT::i32, Custom); 236 setOperationAction(ISD::UDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UREM, MVT::i32, Custom); 238 } else { 239 setOperationAction(ISD::MUL, MVT::i64, Custom); 240 } 241 } 242 243 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 244 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 246 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 247 248 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 249 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 251 252 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 253 if (Subtarget.is64Bit()) { 254 setOperationAction(ISD::ROTL, MVT::i32, Custom); 255 setOperationAction(ISD::ROTR, MVT::i32, Custom); 256 } 257 } else { 258 setOperationAction(ISD::ROTL, XLenVT, Expand); 259 setOperationAction(ISD::ROTR, XLenVT, Expand); 260 } 261 262 if (Subtarget.hasStdExtZbp()) { 263 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 264 // more combining. 265 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 266 setOperationAction(ISD::BSWAP, XLenVT, Custom); 267 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 268 // BSWAP i8 doesn't exist. 269 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 270 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 271 272 if (Subtarget.is64Bit()) { 273 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 274 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 275 } 276 } else { 277 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 278 // pattern match it directly in isel. 279 setOperationAction(ISD::BSWAP, XLenVT, 280 Subtarget.hasStdExtZbb() ? Legal : Expand); 281 } 282 283 if (Subtarget.hasStdExtZbb()) { 284 setOperationAction(ISD::SMIN, XLenVT, Legal); 285 setOperationAction(ISD::SMAX, XLenVT, Legal); 286 setOperationAction(ISD::UMIN, XLenVT, Legal); 287 setOperationAction(ISD::UMAX, XLenVT, Legal); 288 289 if (Subtarget.is64Bit()) { 290 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 291 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 292 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 293 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 294 } 295 } else { 296 setOperationAction(ISD::CTTZ, XLenVT, Expand); 297 setOperationAction(ISD::CTLZ, XLenVT, Expand); 298 setOperationAction(ISD::CTPOP, XLenVT, Expand); 299 } 300 301 if (Subtarget.hasStdExtZbt()) { 302 setOperationAction(ISD::FSHL, XLenVT, Custom); 303 setOperationAction(ISD::FSHR, XLenVT, Custom); 304 setOperationAction(ISD::SELECT, XLenVT, Legal); 305 306 if (Subtarget.is64Bit()) { 307 setOperationAction(ISD::FSHL, MVT::i32, Custom); 308 setOperationAction(ISD::FSHR, MVT::i32, Custom); 309 } 310 } else { 311 setOperationAction(ISD::SELECT, XLenVT, Custom); 312 } 313 314 static const ISD::CondCode FPCCToExpand[] = { 315 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 316 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 317 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 318 319 static const ISD::NodeType FPOpToExpand[] = { 320 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 321 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 322 323 if (Subtarget.hasStdExtZfh()) 324 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 325 326 if (Subtarget.hasStdExtZfh()) { 327 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 328 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 329 setOperationAction(ISD::LRINT, MVT::f16, Legal); 330 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 331 setOperationAction(ISD::LROUND, MVT::f16, Legal); 332 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 333 setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal); 334 setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal); 335 setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal); 336 setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal); 337 setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal); 338 setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal); 339 setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal); 340 setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal); 341 setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal); 342 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 343 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 344 setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal); 345 for (auto CC : FPCCToExpand) 346 setCondCodeAction(CC, MVT::f16, Expand); 347 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 348 setOperationAction(ISD::SELECT, MVT::f16, Custom); 349 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 350 351 setOperationAction(ISD::FREM, MVT::f16, Promote); 352 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 353 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 354 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 355 setOperationAction(ISD::FRINT, MVT::f16, Promote); 356 setOperationAction(ISD::FROUND, MVT::f16, Promote); 357 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 358 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 359 setOperationAction(ISD::FPOW, MVT::f16, Promote); 360 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 361 setOperationAction(ISD::FCOS, MVT::f16, Promote); 362 setOperationAction(ISD::FSIN, MVT::f16, Promote); 363 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 364 setOperationAction(ISD::FEXP, MVT::f16, Promote); 365 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 366 setOperationAction(ISD::FLOG, MVT::f16, Promote); 367 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 368 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 369 370 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 371 // complete support for all operations in LegalizeDAG. 372 373 // We need to custom promote this. 374 if (Subtarget.is64Bit()) 375 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 376 } 377 378 if (Subtarget.hasStdExtF()) { 379 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 380 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 381 setOperationAction(ISD::LRINT, MVT::f32, Legal); 382 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 383 setOperationAction(ISD::LROUND, MVT::f32, Legal); 384 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 385 setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal); 386 setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal); 387 setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal); 388 setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal); 389 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 390 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 391 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 392 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 393 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 394 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 395 for (auto CC : FPCCToExpand) 396 setCondCodeAction(CC, MVT::f32, Expand); 397 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 398 setOperationAction(ISD::SELECT, MVT::f32, Custom); 399 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 400 for (auto Op : FPOpToExpand) 401 setOperationAction(Op, MVT::f32, Expand); 402 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 403 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 404 } 405 406 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 407 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 408 409 if (Subtarget.hasStdExtD()) { 410 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 411 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 412 setOperationAction(ISD::LRINT, MVT::f64, Legal); 413 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 414 setOperationAction(ISD::LROUND, MVT::f64, Legal); 415 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 416 setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal); 417 setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal); 418 setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal); 419 setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal); 420 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 421 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 422 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 423 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 424 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 425 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 426 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 427 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 428 for (auto CC : FPCCToExpand) 429 setCondCodeAction(CC, MVT::f64, Expand); 430 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 431 setOperationAction(ISD::SELECT, MVT::f64, Custom); 432 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 433 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 434 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 435 for (auto Op : FPOpToExpand) 436 setOperationAction(Op, MVT::f64, Expand); 437 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 438 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 439 } 440 441 if (Subtarget.is64Bit()) { 442 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 443 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 444 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 445 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 446 } 447 448 if (Subtarget.hasStdExtF()) { 449 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 450 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 451 452 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 453 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 454 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 455 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 456 457 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 458 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 459 } 460 461 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 462 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 463 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 464 setOperationAction(ISD::JumpTable, XLenVT, Custom); 465 466 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 467 468 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 469 // Unfortunately this can't be determined just from the ISA naming string. 470 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 471 Subtarget.is64Bit() ? Legal : Custom); 472 473 setOperationAction(ISD::TRAP, MVT::Other, Legal); 474 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 475 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 476 if (Subtarget.is64Bit()) 477 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 478 479 if (Subtarget.hasStdExtA()) { 480 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 481 setMinCmpXchgSizeInBits(32); 482 } else { 483 setMaxAtomicSizeInBitsSupported(0); 484 } 485 486 setBooleanContents(ZeroOrOneBooleanContent); 487 488 if (Subtarget.hasVInstructions()) { 489 setBooleanVectorContents(ZeroOrOneBooleanContent); 490 491 setOperationAction(ISD::VSCALE, XLenVT, Custom); 492 493 // RVV intrinsics may have illegal operands. 494 // We also need to custom legalize vmv.x.s. 495 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 496 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 497 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 498 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 499 if (Subtarget.is64Bit()) { 500 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 501 } else { 502 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 503 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 504 } 505 506 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 507 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 508 509 static const unsigned IntegerVPOps[] = { 510 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 511 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 512 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 513 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 514 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 515 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 516 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 517 ISD::VP_SELECT}; 518 519 static const unsigned FloatingPointVPOps[] = { 520 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 521 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 522 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT}; 523 524 if (!Subtarget.is64Bit()) { 525 // We must custom-lower certain vXi64 operations on RV32 due to the vector 526 // element type being illegal. 527 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 528 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 529 530 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 531 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 532 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 533 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 534 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 535 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 536 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 537 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 538 539 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 540 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 541 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 542 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 543 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 544 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 545 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 546 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 547 } 548 549 for (MVT VT : BoolVecVTs) { 550 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 551 552 // Mask VTs are custom-expanded into a series of standard nodes 553 setOperationAction(ISD::TRUNCATE, VT, Custom); 554 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 555 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 556 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 557 558 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 559 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 560 561 setOperationAction(ISD::SELECT, VT, Custom); 562 setOperationAction(ISD::SELECT_CC, VT, Expand); 563 setOperationAction(ISD::VSELECT, VT, Expand); 564 565 setOperationAction(ISD::VP_AND, VT, Custom); 566 setOperationAction(ISD::VP_OR, VT, Custom); 567 setOperationAction(ISD::VP_XOR, VT, Custom); 568 569 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 570 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 571 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 572 573 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 574 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 575 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 576 577 // RVV has native int->float & float->int conversions where the 578 // element type sizes are within one power-of-two of each other. Any 579 // wider distances between type sizes have to be lowered as sequences 580 // which progressively narrow the gap in stages. 581 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 582 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 583 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 584 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 585 586 // Expand all extending loads to types larger than this, and truncating 587 // stores from types larger than this. 588 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 589 setTruncStoreAction(OtherVT, VT, Expand); 590 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 591 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 592 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 593 } 594 } 595 596 for (MVT VT : IntVecVTs) { 597 if (VT.getVectorElementType() == MVT::i64 && 598 !Subtarget.hasVInstructionsI64()) 599 continue; 600 601 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 602 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 603 604 // Vectors implement MULHS/MULHU. 605 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 606 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 607 608 setOperationAction(ISD::SMIN, VT, Legal); 609 setOperationAction(ISD::SMAX, VT, Legal); 610 setOperationAction(ISD::UMIN, VT, Legal); 611 setOperationAction(ISD::UMAX, VT, Legal); 612 613 setOperationAction(ISD::ROTL, VT, Expand); 614 setOperationAction(ISD::ROTR, VT, Expand); 615 616 setOperationAction(ISD::CTTZ, VT, Expand); 617 setOperationAction(ISD::CTLZ, VT, Expand); 618 setOperationAction(ISD::CTPOP, VT, Expand); 619 620 setOperationAction(ISD::BSWAP, VT, Expand); 621 622 // Custom-lower extensions and truncations from/to mask types. 623 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 624 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 625 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 626 627 // RVV has native int->float & float->int conversions where the 628 // element type sizes are within one power-of-two of each other. Any 629 // wider distances between type sizes have to be lowered as sequences 630 // which progressively narrow the gap in stages. 631 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 632 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 633 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 634 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 635 636 setOperationAction(ISD::SADDSAT, VT, Legal); 637 setOperationAction(ISD::UADDSAT, VT, Legal); 638 setOperationAction(ISD::SSUBSAT, VT, Legal); 639 setOperationAction(ISD::USUBSAT, VT, Legal); 640 641 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 642 // nodes which truncate by one power of two at a time. 643 setOperationAction(ISD::TRUNCATE, VT, Custom); 644 645 // Custom-lower insert/extract operations to simplify patterns. 646 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 647 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 648 649 // Custom-lower reduction operations to set up the corresponding custom 650 // nodes' operands. 651 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 652 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 653 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 654 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 655 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 656 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 657 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 658 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 659 660 for (unsigned VPOpc : IntegerVPOps) 661 setOperationAction(VPOpc, VT, Custom); 662 663 setOperationAction(ISD::LOAD, VT, Custom); 664 setOperationAction(ISD::STORE, VT, Custom); 665 666 setOperationAction(ISD::MLOAD, VT, Custom); 667 setOperationAction(ISD::MSTORE, VT, Custom); 668 setOperationAction(ISD::MGATHER, VT, Custom); 669 setOperationAction(ISD::MSCATTER, VT, Custom); 670 671 setOperationAction(ISD::VP_LOAD, VT, Custom); 672 setOperationAction(ISD::VP_STORE, VT, Custom); 673 setOperationAction(ISD::VP_GATHER, VT, Custom); 674 setOperationAction(ISD::VP_SCATTER, VT, Custom); 675 676 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 677 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 678 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 679 680 setOperationAction(ISD::SELECT, VT, Custom); 681 setOperationAction(ISD::SELECT_CC, VT, Expand); 682 683 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 684 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 685 686 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 687 setTruncStoreAction(VT, OtherVT, Expand); 688 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 689 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 690 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 691 } 692 693 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 694 // type that can represent the value exactly. 695 if (VT.getVectorElementType() != MVT::i64) { 696 MVT FloatEltVT = 697 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 698 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 699 if (isTypeLegal(FloatVT)) { 700 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 701 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 702 } 703 } 704 } 705 706 // Expand various CCs to best match the RVV ISA, which natively supports UNE 707 // but no other unordered comparisons, and supports all ordered comparisons 708 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 709 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 710 // and we pattern-match those back to the "original", swapping operands once 711 // more. This way we catch both operations and both "vf" and "fv" forms with 712 // fewer patterns. 713 static const ISD::CondCode VFPCCToExpand[] = { 714 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 715 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 716 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 717 }; 718 719 // Sets common operation actions on RVV floating-point vector types. 720 const auto SetCommonVFPActions = [&](MVT VT) { 721 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 722 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 723 // sizes are within one power-of-two of each other. Therefore conversions 724 // between vXf16 and vXf64 must be lowered as sequences which convert via 725 // vXf32. 726 setOperationAction(ISD::FP_ROUND, VT, Custom); 727 setOperationAction(ISD::FP_EXTEND, VT, Custom); 728 // Custom-lower insert/extract operations to simplify patterns. 729 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 730 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 731 // Expand various condition codes (explained above). 732 for (auto CC : VFPCCToExpand) 733 setCondCodeAction(CC, VT, Expand); 734 735 setOperationAction(ISD::FMINNUM, VT, Legal); 736 setOperationAction(ISD::FMAXNUM, VT, Legal); 737 738 setOperationAction(ISD::FTRUNC, VT, Custom); 739 setOperationAction(ISD::FCEIL, VT, Custom); 740 setOperationAction(ISD::FFLOOR, VT, Custom); 741 742 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 743 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 744 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 745 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 746 747 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 748 749 setOperationAction(ISD::LOAD, VT, Custom); 750 setOperationAction(ISD::STORE, VT, Custom); 751 752 setOperationAction(ISD::MLOAD, VT, Custom); 753 setOperationAction(ISD::MSTORE, VT, Custom); 754 setOperationAction(ISD::MGATHER, VT, Custom); 755 setOperationAction(ISD::MSCATTER, VT, Custom); 756 757 setOperationAction(ISD::VP_LOAD, VT, Custom); 758 setOperationAction(ISD::VP_STORE, VT, Custom); 759 setOperationAction(ISD::VP_GATHER, VT, Custom); 760 setOperationAction(ISD::VP_SCATTER, VT, Custom); 761 762 setOperationAction(ISD::SELECT, VT, Custom); 763 setOperationAction(ISD::SELECT_CC, VT, Expand); 764 765 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 766 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 767 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 768 769 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 770 771 for (unsigned VPOpc : FloatingPointVPOps) 772 setOperationAction(VPOpc, VT, Custom); 773 }; 774 775 // Sets common extload/truncstore actions on RVV floating-point vector 776 // types. 777 const auto SetCommonVFPExtLoadTruncStoreActions = 778 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 779 for (auto SmallVT : SmallerVTs) { 780 setTruncStoreAction(VT, SmallVT, Expand); 781 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 782 } 783 }; 784 785 if (Subtarget.hasVInstructionsF16()) 786 for (MVT VT : F16VecVTs) 787 SetCommonVFPActions(VT); 788 789 for (MVT VT : F32VecVTs) { 790 if (Subtarget.hasVInstructionsF32()) 791 SetCommonVFPActions(VT); 792 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 793 } 794 795 for (MVT VT : F64VecVTs) { 796 if (Subtarget.hasVInstructionsF64()) 797 SetCommonVFPActions(VT); 798 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 799 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 800 } 801 802 if (Subtarget.useRVVForFixedLengthVectors()) { 803 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 804 if (!useRVVForFixedLengthVectorVT(VT)) 805 continue; 806 807 // By default everything must be expanded. 808 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 809 setOperationAction(Op, VT, Expand); 810 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 811 setTruncStoreAction(VT, OtherVT, Expand); 812 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 813 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 814 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 815 } 816 817 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 818 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 819 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 820 821 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 822 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 823 824 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 826 827 setOperationAction(ISD::LOAD, VT, Custom); 828 setOperationAction(ISD::STORE, VT, Custom); 829 830 setOperationAction(ISD::SETCC, VT, Custom); 831 832 setOperationAction(ISD::SELECT, VT, Custom); 833 834 setOperationAction(ISD::TRUNCATE, VT, Custom); 835 836 setOperationAction(ISD::BITCAST, VT, Custom); 837 838 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 839 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 840 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 841 842 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 843 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 844 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 845 846 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 847 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 848 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 849 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 850 851 // Operations below are different for between masks and other vectors. 852 if (VT.getVectorElementType() == MVT::i1) { 853 setOperationAction(ISD::VP_AND, VT, Custom); 854 setOperationAction(ISD::VP_OR, VT, Custom); 855 setOperationAction(ISD::VP_XOR, VT, Custom); 856 setOperationAction(ISD::AND, VT, Custom); 857 setOperationAction(ISD::OR, VT, Custom); 858 setOperationAction(ISD::XOR, VT, Custom); 859 continue; 860 } 861 862 // Use SPLAT_VECTOR to prevent type legalization from destroying the 863 // splats when type legalizing i64 scalar on RV32. 864 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 865 // improvements first. 866 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 867 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 868 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 869 } 870 871 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 872 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 873 874 setOperationAction(ISD::MLOAD, VT, Custom); 875 setOperationAction(ISD::MSTORE, VT, Custom); 876 setOperationAction(ISD::MGATHER, VT, Custom); 877 setOperationAction(ISD::MSCATTER, VT, Custom); 878 879 setOperationAction(ISD::VP_LOAD, VT, Custom); 880 setOperationAction(ISD::VP_STORE, VT, Custom); 881 setOperationAction(ISD::VP_GATHER, VT, Custom); 882 setOperationAction(ISD::VP_SCATTER, VT, Custom); 883 884 setOperationAction(ISD::ADD, VT, Custom); 885 setOperationAction(ISD::MUL, VT, Custom); 886 setOperationAction(ISD::SUB, VT, Custom); 887 setOperationAction(ISD::AND, VT, Custom); 888 setOperationAction(ISD::OR, VT, Custom); 889 setOperationAction(ISD::XOR, VT, Custom); 890 setOperationAction(ISD::SDIV, VT, Custom); 891 setOperationAction(ISD::SREM, VT, Custom); 892 setOperationAction(ISD::UDIV, VT, Custom); 893 setOperationAction(ISD::UREM, VT, Custom); 894 setOperationAction(ISD::SHL, VT, Custom); 895 setOperationAction(ISD::SRA, VT, Custom); 896 setOperationAction(ISD::SRL, VT, Custom); 897 898 setOperationAction(ISD::SMIN, VT, Custom); 899 setOperationAction(ISD::SMAX, VT, Custom); 900 setOperationAction(ISD::UMIN, VT, Custom); 901 setOperationAction(ISD::UMAX, VT, Custom); 902 setOperationAction(ISD::ABS, VT, Custom); 903 904 setOperationAction(ISD::MULHS, VT, Custom); 905 setOperationAction(ISD::MULHU, VT, Custom); 906 907 setOperationAction(ISD::SADDSAT, VT, Custom); 908 setOperationAction(ISD::UADDSAT, VT, Custom); 909 setOperationAction(ISD::SSUBSAT, VT, Custom); 910 setOperationAction(ISD::USUBSAT, VT, Custom); 911 912 setOperationAction(ISD::VSELECT, VT, Custom); 913 setOperationAction(ISD::SELECT_CC, VT, Expand); 914 915 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 916 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 917 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 918 919 // Custom-lower reduction operations to set up the corresponding custom 920 // nodes' operands. 921 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 922 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 923 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 924 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 925 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 926 927 for (unsigned VPOpc : IntegerVPOps) 928 setOperationAction(VPOpc, VT, Custom); 929 930 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 931 // type that can represent the value exactly. 932 if (VT.getVectorElementType() != MVT::i64) { 933 MVT FloatEltVT = 934 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 935 EVT FloatVT = 936 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 937 if (isTypeLegal(FloatVT)) { 938 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 939 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 940 } 941 } 942 } 943 944 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 945 if (!useRVVForFixedLengthVectorVT(VT)) 946 continue; 947 948 // By default everything must be expanded. 949 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 950 setOperationAction(Op, VT, Expand); 951 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 952 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 953 setTruncStoreAction(VT, OtherVT, Expand); 954 } 955 956 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 957 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 958 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 959 960 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 961 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 962 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 963 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 964 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 965 966 setOperationAction(ISD::LOAD, VT, Custom); 967 setOperationAction(ISD::STORE, VT, Custom); 968 setOperationAction(ISD::MLOAD, VT, Custom); 969 setOperationAction(ISD::MSTORE, VT, Custom); 970 setOperationAction(ISD::MGATHER, VT, Custom); 971 setOperationAction(ISD::MSCATTER, VT, Custom); 972 973 setOperationAction(ISD::VP_LOAD, VT, Custom); 974 setOperationAction(ISD::VP_STORE, VT, Custom); 975 setOperationAction(ISD::VP_GATHER, VT, Custom); 976 setOperationAction(ISD::VP_SCATTER, VT, Custom); 977 978 setOperationAction(ISD::FADD, VT, Custom); 979 setOperationAction(ISD::FSUB, VT, Custom); 980 setOperationAction(ISD::FMUL, VT, Custom); 981 setOperationAction(ISD::FDIV, VT, Custom); 982 setOperationAction(ISD::FNEG, VT, Custom); 983 setOperationAction(ISD::FABS, VT, Custom); 984 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 985 setOperationAction(ISD::FSQRT, VT, Custom); 986 setOperationAction(ISD::FMA, VT, Custom); 987 setOperationAction(ISD::FMINNUM, VT, Custom); 988 setOperationAction(ISD::FMAXNUM, VT, Custom); 989 990 setOperationAction(ISD::FP_ROUND, VT, Custom); 991 setOperationAction(ISD::FP_EXTEND, VT, Custom); 992 993 setOperationAction(ISD::FTRUNC, VT, Custom); 994 setOperationAction(ISD::FCEIL, VT, Custom); 995 setOperationAction(ISD::FFLOOR, VT, Custom); 996 997 for (auto CC : VFPCCToExpand) 998 setCondCodeAction(CC, VT, Expand); 999 1000 setOperationAction(ISD::VSELECT, VT, Custom); 1001 setOperationAction(ISD::SELECT, VT, Custom); 1002 setOperationAction(ISD::SELECT_CC, VT, Expand); 1003 1004 setOperationAction(ISD::BITCAST, VT, Custom); 1005 1006 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1007 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1008 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1009 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1010 1011 for (unsigned VPOpc : FloatingPointVPOps) 1012 setOperationAction(VPOpc, VT, Custom); 1013 } 1014 1015 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1016 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1017 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1018 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1019 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1020 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1021 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1022 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1023 } 1024 } 1025 1026 // Function alignments. 1027 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1028 setMinFunctionAlignment(FunctionAlignment); 1029 setPrefFunctionAlignment(FunctionAlignment); 1030 1031 setMinimumJumpTableEntries(5); 1032 1033 // Jumps are expensive, compared to logic 1034 setJumpIsExpensive(); 1035 1036 setTargetDAGCombine(ISD::ADD); 1037 setTargetDAGCombine(ISD::SUB); 1038 setTargetDAGCombine(ISD::AND); 1039 setTargetDAGCombine(ISD::OR); 1040 setTargetDAGCombine(ISD::XOR); 1041 setTargetDAGCombine(ISD::ANY_EXTEND); 1042 setTargetDAGCombine(ISD::ZERO_EXTEND); 1043 if (Subtarget.hasVInstructions()) { 1044 setTargetDAGCombine(ISD::FCOPYSIGN); 1045 setTargetDAGCombine(ISD::MGATHER); 1046 setTargetDAGCombine(ISD::MSCATTER); 1047 setTargetDAGCombine(ISD::VP_GATHER); 1048 setTargetDAGCombine(ISD::VP_SCATTER); 1049 setTargetDAGCombine(ISD::SRA); 1050 setTargetDAGCombine(ISD::SRL); 1051 setTargetDAGCombine(ISD::SHL); 1052 setTargetDAGCombine(ISD::STORE); 1053 } 1054 } 1055 1056 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1057 LLVMContext &Context, 1058 EVT VT) const { 1059 if (!VT.isVector()) 1060 return getPointerTy(DL); 1061 if (Subtarget.hasVInstructions() && 1062 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1063 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1064 return VT.changeVectorElementTypeToInteger(); 1065 } 1066 1067 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1068 return Subtarget.getXLenVT(); 1069 } 1070 1071 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1072 const CallInst &I, 1073 MachineFunction &MF, 1074 unsigned Intrinsic) const { 1075 auto &DL = I.getModule()->getDataLayout(); 1076 switch (Intrinsic) { 1077 default: 1078 return false; 1079 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1080 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1081 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1082 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1083 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1084 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1085 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1086 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1087 case Intrinsic::riscv_masked_cmpxchg_i32: { 1088 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 1089 Info.opc = ISD::INTRINSIC_W_CHAIN; 1090 Info.memVT = MVT::getVT(PtrTy->getElementType()); 1091 Info.ptrVal = I.getArgOperand(0); 1092 Info.offset = 0; 1093 Info.align = Align(4); 1094 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1095 MachineMemOperand::MOVolatile; 1096 return true; 1097 } 1098 case Intrinsic::riscv_masked_strided_load: 1099 Info.opc = ISD::INTRINSIC_W_CHAIN; 1100 Info.ptrVal = I.getArgOperand(1); 1101 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1102 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1103 Info.size = MemoryLocation::UnknownSize; 1104 Info.flags |= MachineMemOperand::MOLoad; 1105 return true; 1106 case Intrinsic::riscv_masked_strided_store: 1107 Info.opc = ISD::INTRINSIC_VOID; 1108 Info.ptrVal = I.getArgOperand(1); 1109 Info.memVT = 1110 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1111 Info.align = Align( 1112 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1113 8); 1114 Info.size = MemoryLocation::UnknownSize; 1115 Info.flags |= MachineMemOperand::MOStore; 1116 return true; 1117 } 1118 } 1119 1120 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1121 const AddrMode &AM, Type *Ty, 1122 unsigned AS, 1123 Instruction *I) const { 1124 // No global is ever allowed as a base. 1125 if (AM.BaseGV) 1126 return false; 1127 1128 // Require a 12-bit signed offset. 1129 if (!isInt<12>(AM.BaseOffs)) 1130 return false; 1131 1132 switch (AM.Scale) { 1133 case 0: // "r+i" or just "i", depending on HasBaseReg. 1134 break; 1135 case 1: 1136 if (!AM.HasBaseReg) // allow "r+i". 1137 break; 1138 return false; // disallow "r+r" or "r+r+i". 1139 default: 1140 return false; 1141 } 1142 1143 return true; 1144 } 1145 1146 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1147 return isInt<12>(Imm); 1148 } 1149 1150 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1151 return isInt<12>(Imm); 1152 } 1153 1154 // On RV32, 64-bit integers are split into their high and low parts and held 1155 // in two different registers, so the trunc is free since the low register can 1156 // just be used. 1157 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1158 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1159 return false; 1160 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1161 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1162 return (SrcBits == 64 && DestBits == 32); 1163 } 1164 1165 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1166 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1167 !SrcVT.isInteger() || !DstVT.isInteger()) 1168 return false; 1169 unsigned SrcBits = SrcVT.getSizeInBits(); 1170 unsigned DestBits = DstVT.getSizeInBits(); 1171 return (SrcBits == 64 && DestBits == 32); 1172 } 1173 1174 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1175 // Zexts are free if they can be combined with a load. 1176 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1177 EVT MemVT = LD->getMemoryVT(); 1178 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 1179 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 1180 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1181 LD->getExtensionType() == ISD::ZEXTLOAD)) 1182 return true; 1183 } 1184 1185 return TargetLowering::isZExtFree(Val, VT2); 1186 } 1187 1188 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1189 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1190 } 1191 1192 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1193 return Subtarget.hasStdExtZbb(); 1194 } 1195 1196 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1197 return Subtarget.hasStdExtZbb(); 1198 } 1199 1200 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1201 EVT VT = Y.getValueType(); 1202 1203 // FIXME: Support vectors once we have tests. 1204 if (VT.isVector()) 1205 return false; 1206 1207 return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y); 1208 } 1209 1210 /// Check if sinking \p I's operands to I's basic block is profitable, because 1211 /// the operands can be folded into a target instruction, e.g. 1212 /// splats of scalars can fold into vector instructions. 1213 bool RISCVTargetLowering::shouldSinkOperands( 1214 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1215 using namespace llvm::PatternMatch; 1216 1217 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1218 return false; 1219 1220 auto IsSinker = [&](Instruction *I, int Operand) { 1221 switch (I->getOpcode()) { 1222 case Instruction::Add: 1223 case Instruction::Sub: 1224 case Instruction::Mul: 1225 case Instruction::And: 1226 case Instruction::Or: 1227 case Instruction::Xor: 1228 case Instruction::FAdd: 1229 case Instruction::FSub: 1230 case Instruction::FMul: 1231 case Instruction::FDiv: 1232 case Instruction::ICmp: 1233 case Instruction::FCmp: 1234 return true; 1235 case Instruction::Shl: 1236 case Instruction::LShr: 1237 case Instruction::AShr: 1238 case Instruction::UDiv: 1239 case Instruction::SDiv: 1240 case Instruction::URem: 1241 case Instruction::SRem: 1242 return Operand == 1; 1243 case Instruction::Call: 1244 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1245 switch (II->getIntrinsicID()) { 1246 case Intrinsic::fma: 1247 return Operand == 0 || Operand == 1; 1248 default: 1249 return false; 1250 } 1251 } 1252 return false; 1253 default: 1254 return false; 1255 } 1256 }; 1257 1258 for (auto OpIdx : enumerate(I->operands())) { 1259 if (!IsSinker(I, OpIdx.index())) 1260 continue; 1261 1262 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1263 // Make sure we are not already sinking this operand 1264 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1265 continue; 1266 1267 // We are looking for a splat that can be sunk. 1268 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1269 m_Undef(), m_ZeroMask()))) 1270 continue; 1271 1272 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1273 // and vector registers 1274 for (Use &U : Op->uses()) { 1275 Instruction *Insn = cast<Instruction>(U.getUser()); 1276 if (!IsSinker(Insn, U.getOperandNo())) 1277 return false; 1278 } 1279 1280 Ops.push_back(&Op->getOperandUse(0)); 1281 Ops.push_back(&OpIdx.value()); 1282 } 1283 return true; 1284 } 1285 1286 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1287 bool ForCodeSize) const { 1288 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1289 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1290 return false; 1291 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1292 return false; 1293 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1294 return false; 1295 if (Imm.isNegZero()) 1296 return false; 1297 return Imm.isZero(); 1298 } 1299 1300 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1301 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1302 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1303 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1304 } 1305 1306 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1307 CallingConv::ID CC, 1308 EVT VT) const { 1309 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1310 // We might still end up using a GPR but that will be decided based on ABI. 1311 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1312 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1313 return MVT::f32; 1314 1315 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1316 } 1317 1318 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1319 CallingConv::ID CC, 1320 EVT VT) const { 1321 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1322 // We might still end up using a GPR but that will be decided based on ABI. 1323 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1324 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1325 return 1; 1326 1327 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1328 } 1329 1330 // Changes the condition code and swaps operands if necessary, so the SetCC 1331 // operation matches one of the comparisons supported directly by branches 1332 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1333 // with 1/-1. 1334 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1335 ISD::CondCode &CC, SelectionDAG &DAG) { 1336 // Convert X > -1 to X >= 0. 1337 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1338 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1339 CC = ISD::SETGE; 1340 return; 1341 } 1342 // Convert X < 1 to 0 >= X. 1343 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1344 RHS = LHS; 1345 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1346 CC = ISD::SETGE; 1347 return; 1348 } 1349 1350 switch (CC) { 1351 default: 1352 break; 1353 case ISD::SETGT: 1354 case ISD::SETLE: 1355 case ISD::SETUGT: 1356 case ISD::SETULE: 1357 CC = ISD::getSetCCSwappedOperands(CC); 1358 std::swap(LHS, RHS); 1359 break; 1360 } 1361 } 1362 1363 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1364 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1365 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1366 if (VT.getVectorElementType() == MVT::i1) 1367 KnownSize *= 8; 1368 1369 switch (KnownSize) { 1370 default: 1371 llvm_unreachable("Invalid LMUL."); 1372 case 8: 1373 return RISCVII::VLMUL::LMUL_F8; 1374 case 16: 1375 return RISCVII::VLMUL::LMUL_F4; 1376 case 32: 1377 return RISCVII::VLMUL::LMUL_F2; 1378 case 64: 1379 return RISCVII::VLMUL::LMUL_1; 1380 case 128: 1381 return RISCVII::VLMUL::LMUL_2; 1382 case 256: 1383 return RISCVII::VLMUL::LMUL_4; 1384 case 512: 1385 return RISCVII::VLMUL::LMUL_8; 1386 } 1387 } 1388 1389 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1390 switch (LMul) { 1391 default: 1392 llvm_unreachable("Invalid LMUL."); 1393 case RISCVII::VLMUL::LMUL_F8: 1394 case RISCVII::VLMUL::LMUL_F4: 1395 case RISCVII::VLMUL::LMUL_F2: 1396 case RISCVII::VLMUL::LMUL_1: 1397 return RISCV::VRRegClassID; 1398 case RISCVII::VLMUL::LMUL_2: 1399 return RISCV::VRM2RegClassID; 1400 case RISCVII::VLMUL::LMUL_4: 1401 return RISCV::VRM4RegClassID; 1402 case RISCVII::VLMUL::LMUL_8: 1403 return RISCV::VRM8RegClassID; 1404 } 1405 } 1406 1407 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1408 RISCVII::VLMUL LMUL = getLMUL(VT); 1409 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1410 LMUL == RISCVII::VLMUL::LMUL_F4 || 1411 LMUL == RISCVII::VLMUL::LMUL_F2 || 1412 LMUL == RISCVII::VLMUL::LMUL_1) { 1413 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1414 "Unexpected subreg numbering"); 1415 return RISCV::sub_vrm1_0 + Index; 1416 } 1417 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1418 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1419 "Unexpected subreg numbering"); 1420 return RISCV::sub_vrm2_0 + Index; 1421 } 1422 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1423 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1424 "Unexpected subreg numbering"); 1425 return RISCV::sub_vrm4_0 + Index; 1426 } 1427 llvm_unreachable("Invalid vector type."); 1428 } 1429 1430 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1431 if (VT.getVectorElementType() == MVT::i1) 1432 return RISCV::VRRegClassID; 1433 return getRegClassIDForLMUL(getLMUL(VT)); 1434 } 1435 1436 // Attempt to decompose a subvector insert/extract between VecVT and 1437 // SubVecVT via subregister indices. Returns the subregister index that 1438 // can perform the subvector insert/extract with the given element index, as 1439 // well as the index corresponding to any leftover subvectors that must be 1440 // further inserted/extracted within the register class for SubVecVT. 1441 std::pair<unsigned, unsigned> 1442 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1443 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1444 const RISCVRegisterInfo *TRI) { 1445 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1446 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1447 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1448 "Register classes not ordered"); 1449 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1450 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1451 // Try to compose a subregister index that takes us from the incoming 1452 // LMUL>1 register class down to the outgoing one. At each step we half 1453 // the LMUL: 1454 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1455 // Note that this is not guaranteed to find a subregister index, such as 1456 // when we are extracting from one VR type to another. 1457 unsigned SubRegIdx = RISCV::NoSubRegister; 1458 for (const unsigned RCID : 1459 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1460 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1461 VecVT = VecVT.getHalfNumVectorElementsVT(); 1462 bool IsHi = 1463 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1464 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1465 getSubregIndexByMVT(VecVT, IsHi)); 1466 if (IsHi) 1467 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1468 } 1469 return {SubRegIdx, InsertExtractIdx}; 1470 } 1471 1472 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1473 // stores for those types. 1474 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1475 return !Subtarget.useRVVForFixedLengthVectors() || 1476 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1477 } 1478 1479 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1480 if (ScalarTy->isPointerTy()) 1481 return true; 1482 1483 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1484 ScalarTy->isIntegerTy(32)) 1485 return true; 1486 1487 if (ScalarTy->isIntegerTy(64)) 1488 return Subtarget.hasVInstructionsI64(); 1489 1490 if (ScalarTy->isHalfTy()) 1491 return Subtarget.hasVInstructionsF16(); 1492 if (ScalarTy->isFloatTy()) 1493 return Subtarget.hasVInstructionsF32(); 1494 if (ScalarTy->isDoubleTy()) 1495 return Subtarget.hasVInstructionsF64(); 1496 1497 return false; 1498 } 1499 1500 static bool useRVVForFixedLengthVectorVT(MVT VT, 1501 const RISCVSubtarget &Subtarget) { 1502 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1503 if (!Subtarget.useRVVForFixedLengthVectors()) 1504 return false; 1505 1506 // We only support a set of vector types with a consistent maximum fixed size 1507 // across all supported vector element types to avoid legalization issues. 1508 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1509 // fixed-length vector type we support is 1024 bytes. 1510 if (VT.getFixedSizeInBits() > 1024 * 8) 1511 return false; 1512 1513 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1514 1515 MVT EltVT = VT.getVectorElementType(); 1516 1517 // Don't use RVV for vectors we cannot scalarize if required. 1518 switch (EltVT.SimpleTy) { 1519 // i1 is supported but has different rules. 1520 default: 1521 return false; 1522 case MVT::i1: 1523 // Masks can only use a single register. 1524 if (VT.getVectorNumElements() > MinVLen) 1525 return false; 1526 MinVLen /= 8; 1527 break; 1528 case MVT::i8: 1529 case MVT::i16: 1530 case MVT::i32: 1531 break; 1532 case MVT::i64: 1533 if (!Subtarget.hasVInstructionsI64()) 1534 return false; 1535 break; 1536 case MVT::f16: 1537 if (!Subtarget.hasVInstructionsF16()) 1538 return false; 1539 break; 1540 case MVT::f32: 1541 if (!Subtarget.hasVInstructionsF32()) 1542 return false; 1543 break; 1544 case MVT::f64: 1545 if (!Subtarget.hasVInstructionsF64()) 1546 return false; 1547 break; 1548 } 1549 1550 // Reject elements larger than ELEN. 1551 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1552 return false; 1553 1554 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1555 // Don't use RVV for types that don't fit. 1556 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1557 return false; 1558 1559 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1560 // the base fixed length RVV support in place. 1561 if (!VT.isPow2VectorType()) 1562 return false; 1563 1564 return true; 1565 } 1566 1567 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1568 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1569 } 1570 1571 // Return the largest legal scalable vector type that matches VT's element type. 1572 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1573 const RISCVSubtarget &Subtarget) { 1574 // This may be called before legal types are setup. 1575 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1576 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1577 "Expected legal fixed length vector!"); 1578 1579 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1580 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1581 1582 MVT EltVT = VT.getVectorElementType(); 1583 switch (EltVT.SimpleTy) { 1584 default: 1585 llvm_unreachable("unexpected element type for RVV container"); 1586 case MVT::i1: 1587 case MVT::i8: 1588 case MVT::i16: 1589 case MVT::i32: 1590 case MVT::i64: 1591 case MVT::f16: 1592 case MVT::f32: 1593 case MVT::f64: { 1594 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1595 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1596 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1597 unsigned NumElts = 1598 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1599 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1600 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1601 return MVT::getScalableVectorVT(EltVT, NumElts); 1602 } 1603 } 1604 } 1605 1606 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1607 const RISCVSubtarget &Subtarget) { 1608 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1609 Subtarget); 1610 } 1611 1612 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1613 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1614 } 1615 1616 // Grow V to consume an entire RVV register. 1617 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1618 const RISCVSubtarget &Subtarget) { 1619 assert(VT.isScalableVector() && 1620 "Expected to convert into a scalable vector!"); 1621 assert(V.getValueType().isFixedLengthVector() && 1622 "Expected a fixed length vector operand!"); 1623 SDLoc DL(V); 1624 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1625 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1626 } 1627 1628 // Shrink V so it's just big enough to maintain a VT's worth of data. 1629 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1630 const RISCVSubtarget &Subtarget) { 1631 assert(VT.isFixedLengthVector() && 1632 "Expected to convert into a fixed length vector!"); 1633 assert(V.getValueType().isScalableVector() && 1634 "Expected a scalable vector operand!"); 1635 SDLoc DL(V); 1636 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1637 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1638 } 1639 1640 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1641 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1642 // the vector type that it is contained in. 1643 static std::pair<SDValue, SDValue> 1644 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1645 const RISCVSubtarget &Subtarget) { 1646 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1647 MVT XLenVT = Subtarget.getXLenVT(); 1648 SDValue VL = VecVT.isFixedLengthVector() 1649 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1650 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1651 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1652 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1653 return {Mask, VL}; 1654 } 1655 1656 // As above but assuming the given type is a scalable vector type. 1657 static std::pair<SDValue, SDValue> 1658 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1659 const RISCVSubtarget &Subtarget) { 1660 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1661 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1662 } 1663 1664 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1665 // of either is (currently) supported. This can get us into an infinite loop 1666 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1667 // as a ..., etc. 1668 // Until either (or both) of these can reliably lower any node, reporting that 1669 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1670 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1671 // which is not desirable. 1672 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1673 EVT VT, unsigned DefinedValues) const { 1674 return false; 1675 } 1676 1677 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1678 // Only splats are currently supported. 1679 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1680 return true; 1681 1682 return false; 1683 } 1684 1685 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) { 1686 // RISCV FP-to-int conversions saturate to the destination register size, but 1687 // don't produce 0 for nan. We can use a conversion instruction and fix the 1688 // nan case with a compare and a select. 1689 SDValue Src = Op.getOperand(0); 1690 1691 EVT DstVT = Op.getValueType(); 1692 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1693 1694 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1695 unsigned Opc; 1696 if (SatVT == DstVT) 1697 Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ; 1698 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1699 Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 1700 else 1701 return SDValue(); 1702 // FIXME: Support other SatVTs by clamping before or after the conversion. 1703 1704 SDLoc DL(Op); 1705 SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src); 1706 1707 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1708 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1709 } 1710 1711 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1712 // and back. Taking care to avoid converting values that are nan or already 1713 // correct. 1714 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1715 // have FRM dependencies modeled yet. 1716 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1717 MVT VT = Op.getSimpleValueType(); 1718 assert(VT.isVector() && "Unexpected type"); 1719 1720 SDLoc DL(Op); 1721 1722 // Freeze the source since we are increasing the number of uses. 1723 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1724 1725 // Truncate to integer and convert back to FP. 1726 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1727 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1728 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1729 1730 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1731 1732 if (Op.getOpcode() == ISD::FCEIL) { 1733 // If the truncated value is the greater than or equal to the original 1734 // value, we've computed the ceil. Otherwise, we went the wrong way and 1735 // need to increase by 1. 1736 // FIXME: This should use a masked operation. Handle here or in isel? 1737 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1738 DAG.getConstantFP(1.0, DL, VT)); 1739 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1740 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1741 } else if (Op.getOpcode() == ISD::FFLOOR) { 1742 // If the truncated value is the less than or equal to the original value, 1743 // we've computed the floor. Otherwise, we went the wrong way and need to 1744 // decrease by 1. 1745 // FIXME: This should use a masked operation. Handle here or in isel? 1746 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1747 DAG.getConstantFP(1.0, DL, VT)); 1748 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1749 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1750 } 1751 1752 // Restore the original sign so that -0.0 is preserved. 1753 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1754 1755 // Determine the largest integer that can be represented exactly. This and 1756 // values larger than it don't have any fractional bits so don't need to 1757 // be converted. 1758 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1759 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1760 APFloat MaxVal = APFloat(FltSem); 1761 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1762 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1763 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1764 1765 // If abs(Src) was larger than MaxVal or nan, keep it. 1766 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1767 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1768 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1769 } 1770 1771 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1772 const RISCVSubtarget &Subtarget) { 1773 MVT VT = Op.getSimpleValueType(); 1774 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1775 1776 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1777 1778 SDLoc DL(Op); 1779 SDValue Mask, VL; 1780 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1781 1782 unsigned Opc = 1783 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1784 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1785 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1786 } 1787 1788 struct VIDSequence { 1789 int64_t StepNumerator; 1790 unsigned StepDenominator; 1791 int64_t Addend; 1792 }; 1793 1794 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1795 // to the (non-zero) step S and start value X. This can be then lowered as the 1796 // RVV sequence (VID * S) + X, for example. 1797 // The step S is represented as an integer numerator divided by a positive 1798 // denominator. Note that the implementation currently only identifies 1799 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1800 // cannot detect 2/3, for example. 1801 // Note that this method will also match potentially unappealing index 1802 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1803 // determine whether this is worth generating code for. 1804 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1805 unsigned NumElts = Op.getNumOperands(); 1806 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1807 if (!Op.getValueType().isInteger()) 1808 return None; 1809 1810 Optional<unsigned> SeqStepDenom; 1811 Optional<int64_t> SeqStepNum, SeqAddend; 1812 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1813 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1814 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1815 // Assume undef elements match the sequence; we just have to be careful 1816 // when interpolating across them. 1817 if (Op.getOperand(Idx).isUndef()) 1818 continue; 1819 // The BUILD_VECTOR must be all constants. 1820 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1821 return None; 1822 1823 uint64_t Val = Op.getConstantOperandVal(Idx) & 1824 maskTrailingOnes<uint64_t>(EltSizeInBits); 1825 1826 if (PrevElt) { 1827 // Calculate the step since the last non-undef element, and ensure 1828 // it's consistent across the entire sequence. 1829 unsigned IdxDiff = Idx - PrevElt->second; 1830 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1831 1832 // A zero-value value difference means that we're somewhere in the middle 1833 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1834 // step change before evaluating the sequence. 1835 if (ValDiff != 0) { 1836 int64_t Remainder = ValDiff % IdxDiff; 1837 // Normalize the step if it's greater than 1. 1838 if (Remainder != ValDiff) { 1839 // The difference must cleanly divide the element span. 1840 if (Remainder != 0) 1841 return None; 1842 ValDiff /= IdxDiff; 1843 IdxDiff = 1; 1844 } 1845 1846 if (!SeqStepNum) 1847 SeqStepNum = ValDiff; 1848 else if (ValDiff != SeqStepNum) 1849 return None; 1850 1851 if (!SeqStepDenom) 1852 SeqStepDenom = IdxDiff; 1853 else if (IdxDiff != *SeqStepDenom) 1854 return None; 1855 } 1856 } 1857 1858 // Record and/or check any addend. 1859 if (SeqStepNum && SeqStepDenom) { 1860 uint64_t ExpectedVal = 1861 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1862 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1863 if (!SeqAddend) 1864 SeqAddend = Addend; 1865 else if (SeqAddend != Addend) 1866 return None; 1867 } 1868 1869 // Record this non-undef element for later. 1870 if (!PrevElt || PrevElt->first != Val) 1871 PrevElt = std::make_pair(Val, Idx); 1872 } 1873 // We need to have logged both a step and an addend for this to count as 1874 // a legal index sequence. 1875 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1876 return None; 1877 1878 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1879 } 1880 1881 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1882 const RISCVSubtarget &Subtarget) { 1883 MVT VT = Op.getSimpleValueType(); 1884 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1885 1886 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1887 1888 SDLoc DL(Op); 1889 SDValue Mask, VL; 1890 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1891 1892 MVT XLenVT = Subtarget.getXLenVT(); 1893 unsigned NumElts = Op.getNumOperands(); 1894 1895 if (VT.getVectorElementType() == MVT::i1) { 1896 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1897 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1898 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1899 } 1900 1901 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1902 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1903 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1904 } 1905 1906 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1907 // scalar integer chunks whose bit-width depends on the number of mask 1908 // bits and XLEN. 1909 // First, determine the most appropriate scalar integer type to use. This 1910 // is at most XLenVT, but may be shrunk to a smaller vector element type 1911 // according to the size of the final vector - use i8 chunks rather than 1912 // XLenVT if we're producing a v8i1. This results in more consistent 1913 // codegen across RV32 and RV64. 1914 unsigned NumViaIntegerBits = 1915 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1916 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1917 // If we have to use more than one INSERT_VECTOR_ELT then this 1918 // optimization is likely to increase code size; avoid peforming it in 1919 // such a case. We can use a load from a constant pool in this case. 1920 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1921 return SDValue(); 1922 // Now we can create our integer vector type. Note that it may be larger 1923 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1924 MVT IntegerViaVecVT = 1925 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1926 divideCeil(NumElts, NumViaIntegerBits)); 1927 1928 uint64_t Bits = 0; 1929 unsigned BitPos = 0, IntegerEltIdx = 0; 1930 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1931 1932 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1933 // Once we accumulate enough bits to fill our scalar type, insert into 1934 // our vector and clear our accumulated data. 1935 if (I != 0 && I % NumViaIntegerBits == 0) { 1936 if (NumViaIntegerBits <= 32) 1937 Bits = SignExtend64(Bits, 32); 1938 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1939 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1940 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1941 Bits = 0; 1942 BitPos = 0; 1943 IntegerEltIdx++; 1944 } 1945 SDValue V = Op.getOperand(I); 1946 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1947 Bits |= ((uint64_t)BitValue << BitPos); 1948 } 1949 1950 // Insert the (remaining) scalar value into position in our integer 1951 // vector type. 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, Elt, 1956 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1957 1958 if (NumElts < NumViaIntegerBits) { 1959 // If we're producing a smaller vector than our minimum legal integer 1960 // type, bitcast to the equivalent (known-legal) mask type, and extract 1961 // our final mask. 1962 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1963 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1964 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1965 DAG.getConstant(0, DL, XLenVT)); 1966 } else { 1967 // Else we must have produced an integer type with the same size as the 1968 // mask type; bitcast for the final result. 1969 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1970 Vec = DAG.getBitcast(VT, Vec); 1971 } 1972 1973 return Vec; 1974 } 1975 1976 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1977 // vector type, we have a legal equivalently-sized i8 type, so we can use 1978 // that. 1979 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 1980 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 1981 1982 SDValue WideVec; 1983 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1984 // For a splat, perform a scalar truncate before creating the wider 1985 // vector. 1986 assert(Splat.getValueType() == XLenVT && 1987 "Unexpected type for i1 splat value"); 1988 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 1989 DAG.getConstant(1, DL, XLenVT)); 1990 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 1991 } else { 1992 SmallVector<SDValue, 8> Ops(Op->op_values()); 1993 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 1994 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 1995 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 1996 } 1997 1998 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 1999 } 2000 2001 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2002 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2003 : RISCVISD::VMV_V_X_VL; 2004 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 2005 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2006 } 2007 2008 // Try and match index sequences, which we can lower to the vid instruction 2009 // with optional modifications. An all-undef vector is matched by 2010 // getSplatValue, above. 2011 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2012 int64_t StepNumerator = SimpleVID->StepNumerator; 2013 unsigned StepDenominator = SimpleVID->StepDenominator; 2014 int64_t Addend = SimpleVID->Addend; 2015 2016 assert(StepNumerator != 0 && "Invalid step"); 2017 bool Negate = false; 2018 int64_t SplatStepVal = StepNumerator; 2019 unsigned StepOpcode = ISD::MUL; 2020 if (StepNumerator != 1) { 2021 if (isPowerOf2_64(std::abs(StepNumerator))) { 2022 Negate = StepNumerator < 0; 2023 StepOpcode = ISD::SHL; 2024 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2025 } 2026 } 2027 2028 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2029 // threshold since it's the immediate value many RVV instructions accept. 2030 // There is no vmul.vi instruction so ensure multiply constant can fit in 2031 // a single addi instruction. 2032 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2033 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2034 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2035 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2036 // Convert right out of the scalable type so we can use standard ISD 2037 // nodes for the rest of the computation. If we used scalable types with 2038 // these, we'd lose the fixed-length vector info and generate worse 2039 // vsetvli code. 2040 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2041 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2042 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2043 SDValue SplatStep = DAG.getSplatVector( 2044 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2045 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2046 } 2047 if (StepDenominator != 1) { 2048 SDValue SplatStep = DAG.getSplatVector( 2049 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2050 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2051 } 2052 if (Addend != 0 || Negate) { 2053 SDValue SplatAddend = 2054 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2055 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2056 } 2057 return VID; 2058 } 2059 } 2060 2061 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2062 // when re-interpreted as a vector with a larger element type. For example, 2063 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2064 // could be instead splat as 2065 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2066 // TODO: This optimization could also work on non-constant splats, but it 2067 // would require bit-manipulation instructions to construct the splat value. 2068 SmallVector<SDValue> Sequence; 2069 unsigned EltBitSize = VT.getScalarSizeInBits(); 2070 const auto *BV = cast<BuildVectorSDNode>(Op); 2071 if (VT.isInteger() && EltBitSize < 64 && 2072 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2073 BV->getRepeatedSequence(Sequence) && 2074 (Sequence.size() * EltBitSize) <= 64) { 2075 unsigned SeqLen = Sequence.size(); 2076 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2077 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2078 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2079 ViaIntVT == MVT::i64) && 2080 "Unexpected sequence type"); 2081 2082 unsigned EltIdx = 0; 2083 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2084 uint64_t SplatValue = 0; 2085 // Construct the amalgamated value which can be splatted as this larger 2086 // vector type. 2087 for (const auto &SeqV : Sequence) { 2088 if (!SeqV.isUndef()) 2089 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2090 << (EltIdx * EltBitSize)); 2091 EltIdx++; 2092 } 2093 2094 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2095 // achieve better constant materializion. 2096 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2097 SplatValue = SignExtend64(SplatValue, 32); 2098 2099 // Since we can't introduce illegal i64 types at this stage, we can only 2100 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2101 // way we can use RVV instructions to splat. 2102 assert((ViaIntVT.bitsLE(XLenVT) || 2103 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2104 "Unexpected bitcast sequence"); 2105 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2106 SDValue ViaVL = 2107 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2108 MVT ViaContainerVT = 2109 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2110 SDValue Splat = 2111 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2112 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2113 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2114 return DAG.getBitcast(VT, Splat); 2115 } 2116 } 2117 2118 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2119 // which constitute a large proportion of the elements. In such cases we can 2120 // splat a vector with the dominant element and make up the shortfall with 2121 // INSERT_VECTOR_ELTs. 2122 // Note that this includes vectors of 2 elements by association. The 2123 // upper-most element is the "dominant" one, allowing us to use a splat to 2124 // "insert" the upper element, and an insert of the lower element at position 2125 // 0, which improves codegen. 2126 SDValue DominantValue; 2127 unsigned MostCommonCount = 0; 2128 DenseMap<SDValue, unsigned> ValueCounts; 2129 unsigned NumUndefElts = 2130 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2131 2132 // Track the number of scalar loads we know we'd be inserting, estimated as 2133 // any non-zero floating-point constant. Other kinds of element are either 2134 // already in registers or are materialized on demand. The threshold at which 2135 // a vector load is more desirable than several scalar materializion and 2136 // vector-insertion instructions is not known. 2137 unsigned NumScalarLoads = 0; 2138 2139 for (SDValue V : Op->op_values()) { 2140 if (V.isUndef()) 2141 continue; 2142 2143 ValueCounts.insert(std::make_pair(V, 0)); 2144 unsigned &Count = ValueCounts[V]; 2145 2146 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2147 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2148 2149 // Is this value dominant? In case of a tie, prefer the highest element as 2150 // it's cheaper to insert near the beginning of a vector than it is at the 2151 // end. 2152 if (++Count >= MostCommonCount) { 2153 DominantValue = V; 2154 MostCommonCount = Count; 2155 } 2156 } 2157 2158 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2159 unsigned NumDefElts = NumElts - NumUndefElts; 2160 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2161 2162 // Don't perform this optimization when optimizing for size, since 2163 // materializing elements and inserting them tends to cause code bloat. 2164 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2165 ((MostCommonCount > DominantValueCountThreshold) || 2166 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2167 // Start by splatting the most common element. 2168 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2169 2170 DenseSet<SDValue> Processed{DominantValue}; 2171 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2172 for (const auto &OpIdx : enumerate(Op->ops())) { 2173 const SDValue &V = OpIdx.value(); 2174 if (V.isUndef() || !Processed.insert(V).second) 2175 continue; 2176 if (ValueCounts[V] == 1) { 2177 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2178 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2179 } else { 2180 // Blend in all instances of this value using a VSELECT, using a 2181 // mask where each bit signals whether that element is the one 2182 // we're after. 2183 SmallVector<SDValue> Ops; 2184 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2185 return DAG.getConstant(V == V1, DL, XLenVT); 2186 }); 2187 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2188 DAG.getBuildVector(SelMaskTy, DL, Ops), 2189 DAG.getSplatBuildVector(VT, DL, V), Vec); 2190 } 2191 } 2192 2193 return Vec; 2194 } 2195 2196 return SDValue(); 2197 } 2198 2199 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2200 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2201 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2202 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2203 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2204 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2205 // node in order to try and match RVV vector/scalar instructions. 2206 if ((LoC >> 31) == HiC) 2207 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2208 } 2209 2210 // Fall back to a stack store and stride x0 vector load. 2211 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2212 } 2213 2214 // Called by type legalization to handle splat of i64 on RV32. 2215 // FIXME: We can optimize this when the type has sign or zero bits in one 2216 // of the halves. 2217 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2218 SDValue VL, SelectionDAG &DAG) { 2219 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2220 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2221 DAG.getConstant(0, DL, MVT::i32)); 2222 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2223 DAG.getConstant(1, DL, MVT::i32)); 2224 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2225 } 2226 2227 // This function lowers a splat of a scalar operand Splat with the vector 2228 // length VL. It ensures the final sequence is type legal, which is useful when 2229 // lowering a splat after type legalization. 2230 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2231 SelectionDAG &DAG, 2232 const RISCVSubtarget &Subtarget) { 2233 if (VT.isFloatingPoint()) 2234 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2235 2236 MVT XLenVT = Subtarget.getXLenVT(); 2237 2238 // Simplest case is that the operand needs to be promoted to XLenVT. 2239 if (Scalar.getValueType().bitsLE(XLenVT)) { 2240 // If the operand is a constant, sign extend to increase our chances 2241 // of being able to use a .vi instruction. ANY_EXTEND would become a 2242 // a zero extend and the simm5 check in isel would fail. 2243 // FIXME: Should we ignore the upper bits in isel instead? 2244 unsigned ExtOpc = 2245 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2246 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2247 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2248 } 2249 2250 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2251 "Unexpected scalar for splat lowering!"); 2252 2253 // Otherwise use the more complicated splatting algorithm. 2254 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2255 } 2256 2257 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2258 const RISCVSubtarget &Subtarget) { 2259 SDValue V1 = Op.getOperand(0); 2260 SDValue V2 = Op.getOperand(1); 2261 SDLoc DL(Op); 2262 MVT XLenVT = Subtarget.getXLenVT(); 2263 MVT VT = Op.getSimpleValueType(); 2264 unsigned NumElts = VT.getVectorNumElements(); 2265 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2266 2267 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2268 2269 SDValue TrueMask, VL; 2270 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2271 2272 if (SVN->isSplat()) { 2273 const int Lane = SVN->getSplatIndex(); 2274 if (Lane >= 0) { 2275 MVT SVT = VT.getVectorElementType(); 2276 2277 // Turn splatted vector load into a strided load with an X0 stride. 2278 SDValue V = V1; 2279 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2280 // with undef. 2281 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2282 int Offset = Lane; 2283 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2284 int OpElements = 2285 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2286 V = V.getOperand(Offset / OpElements); 2287 Offset %= OpElements; 2288 } 2289 2290 // We need to ensure the load isn't atomic or volatile. 2291 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2292 auto *Ld = cast<LoadSDNode>(V); 2293 Offset *= SVT.getStoreSize(); 2294 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2295 TypeSize::Fixed(Offset), DL); 2296 2297 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2298 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2299 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2300 SDValue IntID = 2301 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2302 SDValue Ops[] = {Ld->getChain(), IntID, NewAddr, 2303 DAG.getRegister(RISCV::X0, XLenVT), VL}; 2304 SDValue NewLoad = DAG.getMemIntrinsicNode( 2305 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2306 DAG.getMachineFunction().getMachineMemOperand( 2307 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2308 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2309 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2310 } 2311 2312 // Otherwise use a scalar load and splat. This will give the best 2313 // opportunity to fold a splat into the operation. ISel can turn it into 2314 // the x0 strided load if we aren't able to fold away the select. 2315 if (SVT.isFloatingPoint()) 2316 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2317 Ld->getPointerInfo().getWithOffset(Offset), 2318 Ld->getOriginalAlign(), 2319 Ld->getMemOperand()->getFlags()); 2320 else 2321 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2322 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2323 Ld->getOriginalAlign(), 2324 Ld->getMemOperand()->getFlags()); 2325 DAG.makeEquivalentMemoryOrdering(Ld, V); 2326 2327 unsigned Opc = 2328 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2329 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2330 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2331 } 2332 2333 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2334 assert(Lane < (int)NumElts && "Unexpected lane!"); 2335 SDValue Gather = 2336 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2337 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2338 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2339 } 2340 } 2341 2342 // Detect shuffles which can be re-expressed as vector selects; these are 2343 // shuffles in which each element in the destination is taken from an element 2344 // at the corresponding index in either source vectors. 2345 bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) { 2346 int MaskIndex = MaskIdx.value(); 2347 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2348 }); 2349 2350 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2351 2352 SmallVector<SDValue> MaskVals; 2353 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2354 // merged with a second vrgather. 2355 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2356 2357 // By default we preserve the original operand order, and use a mask to 2358 // select LHS as true and RHS as false. However, since RVV vector selects may 2359 // feature splats but only on the LHS, we may choose to invert our mask and 2360 // instead select between RHS and LHS. 2361 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2362 bool InvertMask = IsSelect == SwapOps; 2363 2364 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2365 // half. 2366 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2367 2368 // Now construct the mask that will be used by the vselect or blended 2369 // vrgather operation. For vrgathers, construct the appropriate indices into 2370 // each vector. 2371 for (int MaskIndex : SVN->getMask()) { 2372 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2373 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2374 if (!IsSelect) { 2375 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2376 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2377 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2378 : DAG.getUNDEF(XLenVT)); 2379 GatherIndicesRHS.push_back( 2380 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2381 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2382 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2383 ++LHSIndexCounts[MaskIndex]; 2384 if (!IsLHSOrUndefIndex) 2385 ++RHSIndexCounts[MaskIndex - NumElts]; 2386 } 2387 } 2388 2389 if (SwapOps) { 2390 std::swap(V1, V2); 2391 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2392 } 2393 2394 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2395 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2396 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2397 2398 if (IsSelect) 2399 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2400 2401 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2402 // On such a large vector we're unable to use i8 as the index type. 2403 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2404 // may involve vector splitting if we're already at LMUL=8, or our 2405 // user-supplied maximum fixed-length LMUL. 2406 return SDValue(); 2407 } 2408 2409 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2410 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2411 MVT IndexVT = VT.changeTypeToInteger(); 2412 // Since we can't introduce illegal index types at this stage, use i16 and 2413 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2414 // than XLenVT. 2415 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2416 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2417 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2418 } 2419 2420 MVT IndexContainerVT = 2421 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2422 2423 SDValue Gather; 2424 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2425 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2426 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2427 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2428 } else { 2429 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2430 // If only one index is used, we can use a "splat" vrgather. 2431 // TODO: We can splat the most-common index and fix-up any stragglers, if 2432 // that's beneficial. 2433 if (LHSIndexCounts.size() == 1) { 2434 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2435 Gather = 2436 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2437 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2438 } else { 2439 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2440 LHSIndices = 2441 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2442 2443 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2444 TrueMask, VL); 2445 } 2446 } 2447 2448 // If a second vector operand is used by this shuffle, blend it in with an 2449 // additional vrgather. 2450 if (!V2.isUndef()) { 2451 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2452 // If only one index is used, we can use a "splat" vrgather. 2453 // TODO: We can splat the most-common index and fix-up any stragglers, if 2454 // that's beneficial. 2455 if (RHSIndexCounts.size() == 1) { 2456 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2457 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2458 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2459 } else { 2460 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2461 RHSIndices = 2462 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2463 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2464 VL); 2465 } 2466 2467 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2468 SelectMask = 2469 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2470 2471 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2472 Gather, VL); 2473 } 2474 2475 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2476 } 2477 2478 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2479 SDLoc DL, SelectionDAG &DAG, 2480 const RISCVSubtarget &Subtarget) { 2481 if (VT.isScalableVector()) 2482 return DAG.getFPExtendOrRound(Op, DL, VT); 2483 assert(VT.isFixedLengthVector() && 2484 "Unexpected value type for RVV FP extend/round lowering"); 2485 SDValue Mask, VL; 2486 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2487 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2488 ? RISCVISD::FP_EXTEND_VL 2489 : RISCVISD::FP_ROUND_VL; 2490 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2491 } 2492 2493 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2494 // the exponent. 2495 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2496 MVT VT = Op.getSimpleValueType(); 2497 unsigned EltSize = VT.getScalarSizeInBits(); 2498 SDValue Src = Op.getOperand(0); 2499 SDLoc DL(Op); 2500 2501 // We need a FP type that can represent the value. 2502 // TODO: Use f16 for i8 when possible? 2503 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2504 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2505 2506 // Legal types should have been checked in the RISCVTargetLowering 2507 // constructor. 2508 // TODO: Splitting may make sense in some cases. 2509 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2510 "Expected legal float type!"); 2511 2512 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2513 // The trailing zero count is equal to log2 of this single bit value. 2514 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2515 SDValue Neg = 2516 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2517 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2518 } 2519 2520 // We have a legal FP type, convert to it. 2521 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2522 // Bitcast to integer and shift the exponent to the LSB. 2523 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2524 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2525 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2526 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2527 DAG.getConstant(ShiftAmt, DL, IntVT)); 2528 // Truncate back to original type to allow vnsrl. 2529 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2530 // The exponent contains log2 of the value in biased form. 2531 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2532 2533 // For trailing zeros, we just need to subtract the bias. 2534 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2535 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2536 DAG.getConstant(ExponentBias, DL, VT)); 2537 2538 // For leading zeros, we need to remove the bias and convert from log2 to 2539 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2540 unsigned Adjust = ExponentBias + (EltSize - 1); 2541 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2542 } 2543 2544 // While RVV has alignment restrictions, we should always be able to load as a 2545 // legal equivalently-sized byte-typed vector instead. This method is 2546 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2547 // the load is already correctly-aligned, it returns SDValue(). 2548 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2549 SelectionDAG &DAG) const { 2550 auto *Load = cast<LoadSDNode>(Op); 2551 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2552 2553 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2554 Load->getMemoryVT(), 2555 *Load->getMemOperand())) 2556 return SDValue(); 2557 2558 SDLoc DL(Op); 2559 MVT VT = Op.getSimpleValueType(); 2560 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2561 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2562 "Unexpected unaligned RVV load type"); 2563 MVT NewVT = 2564 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2565 assert(NewVT.isValid() && 2566 "Expecting equally-sized RVV vector types to be legal"); 2567 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2568 Load->getPointerInfo(), Load->getOriginalAlign(), 2569 Load->getMemOperand()->getFlags()); 2570 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2571 } 2572 2573 // While RVV has alignment restrictions, we should always be able to store as a 2574 // legal equivalently-sized byte-typed vector instead. This method is 2575 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2576 // returns SDValue() if the store is already correctly aligned. 2577 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2578 SelectionDAG &DAG) const { 2579 auto *Store = cast<StoreSDNode>(Op); 2580 assert(Store && Store->getValue().getValueType().isVector() && 2581 "Expected vector store"); 2582 2583 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2584 Store->getMemoryVT(), 2585 *Store->getMemOperand())) 2586 return SDValue(); 2587 2588 SDLoc DL(Op); 2589 SDValue StoredVal = Store->getValue(); 2590 MVT VT = StoredVal.getSimpleValueType(); 2591 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2592 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2593 "Unexpected unaligned RVV store type"); 2594 MVT NewVT = 2595 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2596 assert(NewVT.isValid() && 2597 "Expecting equally-sized RVV vector types to be legal"); 2598 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2599 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2600 Store->getPointerInfo(), Store->getOriginalAlign(), 2601 Store->getMemOperand()->getFlags()); 2602 } 2603 2604 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2605 SelectionDAG &DAG) const { 2606 switch (Op.getOpcode()) { 2607 default: 2608 report_fatal_error("unimplemented operand"); 2609 case ISD::GlobalAddress: 2610 return lowerGlobalAddress(Op, DAG); 2611 case ISD::BlockAddress: 2612 return lowerBlockAddress(Op, DAG); 2613 case ISD::ConstantPool: 2614 return lowerConstantPool(Op, DAG); 2615 case ISD::JumpTable: 2616 return lowerJumpTable(Op, DAG); 2617 case ISD::GlobalTLSAddress: 2618 return lowerGlobalTLSAddress(Op, DAG); 2619 case ISD::SELECT: 2620 return lowerSELECT(Op, DAG); 2621 case ISD::BRCOND: 2622 return lowerBRCOND(Op, DAG); 2623 case ISD::VASTART: 2624 return lowerVASTART(Op, DAG); 2625 case ISD::FRAMEADDR: 2626 return lowerFRAMEADDR(Op, DAG); 2627 case ISD::RETURNADDR: 2628 return lowerRETURNADDR(Op, DAG); 2629 case ISD::SHL_PARTS: 2630 return lowerShiftLeftParts(Op, DAG); 2631 case ISD::SRA_PARTS: 2632 return lowerShiftRightParts(Op, DAG, true); 2633 case ISD::SRL_PARTS: 2634 return lowerShiftRightParts(Op, DAG, false); 2635 case ISD::BITCAST: { 2636 SDLoc DL(Op); 2637 EVT VT = Op.getValueType(); 2638 SDValue Op0 = Op.getOperand(0); 2639 EVT Op0VT = Op0.getValueType(); 2640 MVT XLenVT = Subtarget.getXLenVT(); 2641 if (VT.isFixedLengthVector()) { 2642 // We can handle fixed length vector bitcasts with a simple replacement 2643 // in isel. 2644 if (Op0VT.isFixedLengthVector()) 2645 return Op; 2646 // When bitcasting from scalar to fixed-length vector, insert the scalar 2647 // into a one-element vector of the result type, and perform a vector 2648 // bitcast. 2649 if (!Op0VT.isVector()) { 2650 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2651 if (!isTypeLegal(BVT)) 2652 return SDValue(); 2653 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2654 DAG.getUNDEF(BVT), Op0, 2655 DAG.getConstant(0, DL, XLenVT))); 2656 } 2657 return SDValue(); 2658 } 2659 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2660 // thus: bitcast the vector to a one-element vector type whose element type 2661 // is the same as the result type, and extract the first element. 2662 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2663 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2664 if (!isTypeLegal(BVT)) 2665 return SDValue(); 2666 SDValue BVec = DAG.getBitcast(BVT, Op0); 2667 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2668 DAG.getConstant(0, DL, XLenVT)); 2669 } 2670 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2671 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2672 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2673 return FPConv; 2674 } 2675 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2676 Subtarget.hasStdExtF()) { 2677 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2678 SDValue FPConv = 2679 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2680 return FPConv; 2681 } 2682 return SDValue(); 2683 } 2684 case ISD::INTRINSIC_WO_CHAIN: 2685 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2686 case ISD::INTRINSIC_W_CHAIN: 2687 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2688 case ISD::INTRINSIC_VOID: 2689 return LowerINTRINSIC_VOID(Op, DAG); 2690 case ISD::BSWAP: 2691 case ISD::BITREVERSE: { 2692 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2693 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2694 MVT VT = Op.getSimpleValueType(); 2695 SDLoc DL(Op); 2696 // Start with the maximum immediate value which is the bitwidth - 1. 2697 unsigned Imm = VT.getSizeInBits() - 1; 2698 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2699 if (Op.getOpcode() == ISD::BSWAP) 2700 Imm &= ~0x7U; 2701 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2702 DAG.getConstant(Imm, DL, VT)); 2703 } 2704 case ISD::FSHL: 2705 case ISD::FSHR: { 2706 MVT VT = Op.getSimpleValueType(); 2707 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2708 SDLoc DL(Op); 2709 if (Op.getOperand(2).getOpcode() == ISD::Constant) 2710 return Op; 2711 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2712 // use log(XLen) bits. Mask the shift amount accordingly. 2713 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2714 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2715 DAG.getConstant(ShAmtWidth, DL, VT)); 2716 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 2717 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 2718 } 2719 case ISD::TRUNCATE: { 2720 SDLoc DL(Op); 2721 MVT VT = Op.getSimpleValueType(); 2722 // Only custom-lower vector truncates 2723 if (!VT.isVector()) 2724 return Op; 2725 2726 // Truncates to mask types are handled differently 2727 if (VT.getVectorElementType() == MVT::i1) 2728 return lowerVectorMaskTrunc(Op, DAG); 2729 2730 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 2731 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 2732 // truncate by one power of two at a time. 2733 MVT DstEltVT = VT.getVectorElementType(); 2734 2735 SDValue Src = Op.getOperand(0); 2736 MVT SrcVT = Src.getSimpleValueType(); 2737 MVT SrcEltVT = SrcVT.getVectorElementType(); 2738 2739 assert(DstEltVT.bitsLT(SrcEltVT) && 2740 isPowerOf2_64(DstEltVT.getSizeInBits()) && 2741 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 2742 "Unexpected vector truncate lowering"); 2743 2744 MVT ContainerVT = SrcVT; 2745 if (SrcVT.isFixedLengthVector()) { 2746 ContainerVT = getContainerForFixedLengthVector(SrcVT); 2747 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2748 } 2749 2750 SDValue Result = Src; 2751 SDValue Mask, VL; 2752 std::tie(Mask, VL) = 2753 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 2754 LLVMContext &Context = *DAG.getContext(); 2755 const ElementCount Count = ContainerVT.getVectorElementCount(); 2756 do { 2757 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 2758 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 2759 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 2760 Mask, VL); 2761 } while (SrcEltVT != DstEltVT); 2762 2763 if (SrcVT.isFixedLengthVector()) 2764 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 2765 2766 return Result; 2767 } 2768 case ISD::ANY_EXTEND: 2769 case ISD::ZERO_EXTEND: 2770 if (Op.getOperand(0).getValueType().isVector() && 2771 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2772 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 2773 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 2774 case ISD::SIGN_EXTEND: 2775 if (Op.getOperand(0).getValueType().isVector() && 2776 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 2777 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 2778 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 2779 case ISD::SPLAT_VECTOR_PARTS: 2780 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 2781 case ISD::INSERT_VECTOR_ELT: 2782 return lowerINSERT_VECTOR_ELT(Op, DAG); 2783 case ISD::EXTRACT_VECTOR_ELT: 2784 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2785 case ISD::VSCALE: { 2786 MVT VT = Op.getSimpleValueType(); 2787 SDLoc DL(Op); 2788 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 2789 // We define our scalable vector types for lmul=1 to use a 64 bit known 2790 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 2791 // vscale as VLENB / 8. 2792 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 2793 if (isa<ConstantSDNode>(Op.getOperand(0))) { 2794 // We assume VLENB is a multiple of 8. We manually choose the best shift 2795 // here because SimplifyDemandedBits isn't always able to simplify it. 2796 uint64_t Val = Op.getConstantOperandVal(0); 2797 if (isPowerOf2_64(Val)) { 2798 uint64_t Log2 = Log2_64(Val); 2799 if (Log2 < 3) 2800 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 2801 DAG.getConstant(3 - Log2, DL, VT)); 2802 if (Log2 > 3) 2803 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 2804 DAG.getConstant(Log2 - 3, DL, VT)); 2805 return VLENB; 2806 } 2807 // If the multiplier is a multiple of 8, scale it down to avoid needing 2808 // to shift the VLENB value. 2809 if ((Val % 8) == 0) 2810 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 2811 DAG.getConstant(Val / 8, DL, VT)); 2812 } 2813 2814 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 2815 DAG.getConstant(3, DL, VT)); 2816 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 2817 } 2818 case ISD::FPOWI: { 2819 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 2820 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 2821 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 2822 Op.getOperand(1).getValueType() == MVT::i32) { 2823 SDLoc DL(Op); 2824 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 2825 SDValue Powi = 2826 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 2827 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 2828 DAG.getIntPtrConstant(0, DL)); 2829 } 2830 return SDValue(); 2831 } 2832 case ISD::FP_EXTEND: { 2833 // RVV can only do fp_extend to types double the size as the source. We 2834 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 2835 // via f32. 2836 SDLoc DL(Op); 2837 MVT VT = Op.getSimpleValueType(); 2838 SDValue Src = Op.getOperand(0); 2839 MVT SrcVT = Src.getSimpleValueType(); 2840 2841 // Prepare any fixed-length vector operands. 2842 MVT ContainerVT = VT; 2843 if (SrcVT.isFixedLengthVector()) { 2844 ContainerVT = getContainerForFixedLengthVector(VT); 2845 MVT SrcContainerVT = 2846 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 2847 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2848 } 2849 2850 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 2851 SrcVT.getVectorElementType() != MVT::f16) { 2852 // For scalable vectors, we only need to close the gap between 2853 // vXf16->vXf64. 2854 if (!VT.isFixedLengthVector()) 2855 return Op; 2856 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 2857 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2858 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2859 } 2860 2861 MVT InterVT = VT.changeVectorElementType(MVT::f32); 2862 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 2863 SDValue IntermediateExtend = getRVVFPExtendOrRound( 2864 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 2865 2866 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 2867 DL, DAG, Subtarget); 2868 if (VT.isFixedLengthVector()) 2869 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 2870 return Extend; 2871 } 2872 case ISD::FP_ROUND: { 2873 // RVV can only do fp_round to types half the size as the source. We 2874 // custom-lower f64->f16 rounds via RVV's round-to-odd float 2875 // conversion instruction. 2876 SDLoc DL(Op); 2877 MVT VT = Op.getSimpleValueType(); 2878 SDValue Src = Op.getOperand(0); 2879 MVT SrcVT = Src.getSimpleValueType(); 2880 2881 // Prepare any fixed-length vector operands. 2882 MVT ContainerVT = VT; 2883 if (VT.isFixedLengthVector()) { 2884 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 2885 ContainerVT = 2886 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 2887 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 2888 } 2889 2890 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 2891 SrcVT.getVectorElementType() != MVT::f64) { 2892 // For scalable vectors, we only need to close the gap between 2893 // vXf64<->vXf16. 2894 if (!VT.isFixedLengthVector()) 2895 return Op; 2896 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 2897 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 2898 return convertFromScalableVector(VT, Src, DAG, Subtarget); 2899 } 2900 2901 SDValue Mask, VL; 2902 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2903 2904 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 2905 SDValue IntermediateRound = 2906 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 2907 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 2908 DL, DAG, Subtarget); 2909 2910 if (VT.isFixedLengthVector()) 2911 return convertFromScalableVector(VT, Round, DAG, Subtarget); 2912 return Round; 2913 } 2914 case ISD::FP_TO_SINT: 2915 case ISD::FP_TO_UINT: 2916 case ISD::SINT_TO_FP: 2917 case ISD::UINT_TO_FP: { 2918 // RVV can only do fp<->int conversions to types half/double the size as 2919 // the source. We custom-lower any conversions that do two hops into 2920 // sequences. 2921 MVT VT = Op.getSimpleValueType(); 2922 if (!VT.isVector()) 2923 return Op; 2924 SDLoc DL(Op); 2925 SDValue Src = Op.getOperand(0); 2926 MVT EltVT = VT.getVectorElementType(); 2927 MVT SrcVT = Src.getSimpleValueType(); 2928 MVT SrcEltVT = SrcVT.getVectorElementType(); 2929 unsigned EltSize = EltVT.getSizeInBits(); 2930 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 2931 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 2932 "Unexpected vector element types"); 2933 2934 bool IsInt2FP = SrcEltVT.isInteger(); 2935 // Widening conversions 2936 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 2937 if (IsInt2FP) { 2938 // Do a regular integer sign/zero extension then convert to float. 2939 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 2940 VT.getVectorElementCount()); 2941 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 2942 ? ISD::ZERO_EXTEND 2943 : ISD::SIGN_EXTEND; 2944 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 2945 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 2946 } 2947 // FP2Int 2948 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 2949 // Do one doubling fp_extend then complete the operation by converting 2950 // to int. 2951 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2952 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 2953 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 2954 } 2955 2956 // Narrowing conversions 2957 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 2958 if (IsInt2FP) { 2959 // One narrowing int_to_fp, then an fp_round. 2960 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 2961 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 2962 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 2963 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 2964 } 2965 // FP2Int 2966 // One narrowing fp_to_int, then truncate the integer. If the float isn't 2967 // representable by the integer, the result is poison. 2968 MVT IVecVT = 2969 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 2970 VT.getVectorElementCount()); 2971 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 2972 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 2973 } 2974 2975 // Scalable vectors can exit here. Patterns will handle equally-sized 2976 // conversions halving/doubling ones. 2977 if (!VT.isFixedLengthVector()) 2978 return Op; 2979 2980 // For fixed-length vectors we lower to a custom "VL" node. 2981 unsigned RVVOpc = 0; 2982 switch (Op.getOpcode()) { 2983 default: 2984 llvm_unreachable("Impossible opcode"); 2985 case ISD::FP_TO_SINT: 2986 RVVOpc = RISCVISD::FP_TO_SINT_VL; 2987 break; 2988 case ISD::FP_TO_UINT: 2989 RVVOpc = RISCVISD::FP_TO_UINT_VL; 2990 break; 2991 case ISD::SINT_TO_FP: 2992 RVVOpc = RISCVISD::SINT_TO_FP_VL; 2993 break; 2994 case ISD::UINT_TO_FP: 2995 RVVOpc = RISCVISD::UINT_TO_FP_VL; 2996 break; 2997 } 2998 2999 MVT ContainerVT, SrcContainerVT; 3000 // Derive the reference container type from the larger vector type. 3001 if (SrcEltSize > EltSize) { 3002 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3003 ContainerVT = 3004 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3005 } else { 3006 ContainerVT = getContainerForFixedLengthVector(VT); 3007 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3008 } 3009 3010 SDValue Mask, VL; 3011 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3012 3013 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3014 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3015 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3016 } 3017 case ISD::FP_TO_SINT_SAT: 3018 case ISD::FP_TO_UINT_SAT: 3019 return lowerFP_TO_INT_SAT(Op, DAG); 3020 case ISD::FTRUNC: 3021 case ISD::FCEIL: 3022 case ISD::FFLOOR: 3023 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3024 case ISD::VECREDUCE_ADD: 3025 case ISD::VECREDUCE_UMAX: 3026 case ISD::VECREDUCE_SMAX: 3027 case ISD::VECREDUCE_UMIN: 3028 case ISD::VECREDUCE_SMIN: 3029 return lowerVECREDUCE(Op, DAG); 3030 case ISD::VECREDUCE_AND: 3031 case ISD::VECREDUCE_OR: 3032 case ISD::VECREDUCE_XOR: 3033 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3034 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3035 return lowerVECREDUCE(Op, DAG); 3036 case ISD::VECREDUCE_FADD: 3037 case ISD::VECREDUCE_SEQ_FADD: 3038 case ISD::VECREDUCE_FMIN: 3039 case ISD::VECREDUCE_FMAX: 3040 return lowerFPVECREDUCE(Op, DAG); 3041 case ISD::VP_REDUCE_ADD: 3042 case ISD::VP_REDUCE_UMAX: 3043 case ISD::VP_REDUCE_SMAX: 3044 case ISD::VP_REDUCE_UMIN: 3045 case ISD::VP_REDUCE_SMIN: 3046 case ISD::VP_REDUCE_FADD: 3047 case ISD::VP_REDUCE_SEQ_FADD: 3048 case ISD::VP_REDUCE_FMIN: 3049 case ISD::VP_REDUCE_FMAX: 3050 return lowerVPREDUCE(Op, DAG); 3051 case ISD::VP_REDUCE_AND: 3052 case ISD::VP_REDUCE_OR: 3053 case ISD::VP_REDUCE_XOR: 3054 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3055 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3056 return lowerVPREDUCE(Op, DAG); 3057 case ISD::INSERT_SUBVECTOR: 3058 return lowerINSERT_SUBVECTOR(Op, DAG); 3059 case ISD::EXTRACT_SUBVECTOR: 3060 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3061 case ISD::STEP_VECTOR: 3062 return lowerSTEP_VECTOR(Op, DAG); 3063 case ISD::VECTOR_REVERSE: 3064 return lowerVECTOR_REVERSE(Op, DAG); 3065 case ISD::BUILD_VECTOR: 3066 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3067 case ISD::SPLAT_VECTOR: 3068 if (Op.getValueType().getVectorElementType() == MVT::i1) 3069 return lowerVectorMaskSplat(Op, DAG); 3070 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3071 case ISD::VECTOR_SHUFFLE: 3072 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3073 case ISD::CONCAT_VECTORS: { 3074 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3075 // better than going through the stack, as the default expansion does. 3076 SDLoc DL(Op); 3077 MVT VT = Op.getSimpleValueType(); 3078 unsigned NumOpElts = 3079 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3080 SDValue Vec = DAG.getUNDEF(VT); 3081 for (const auto &OpIdx : enumerate(Op->ops())) 3082 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 3083 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3084 return Vec; 3085 } 3086 case ISD::LOAD: 3087 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3088 return V; 3089 if (Op.getValueType().isFixedLengthVector()) 3090 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3091 return Op; 3092 case ISD::STORE: 3093 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3094 return V; 3095 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3096 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3097 return Op; 3098 case ISD::MLOAD: 3099 case ISD::VP_LOAD: 3100 return lowerMaskedLoad(Op, DAG); 3101 case ISD::MSTORE: 3102 case ISD::VP_STORE: 3103 return lowerMaskedStore(Op, DAG); 3104 case ISD::SETCC: 3105 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3106 case ISD::ADD: 3107 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3108 case ISD::SUB: 3109 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3110 case ISD::MUL: 3111 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3112 case ISD::MULHS: 3113 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3114 case ISD::MULHU: 3115 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3116 case ISD::AND: 3117 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3118 RISCVISD::AND_VL); 3119 case ISD::OR: 3120 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3121 RISCVISD::OR_VL); 3122 case ISD::XOR: 3123 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3124 RISCVISD::XOR_VL); 3125 case ISD::SDIV: 3126 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3127 case ISD::SREM: 3128 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3129 case ISD::UDIV: 3130 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3131 case ISD::UREM: 3132 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3133 case ISD::SHL: 3134 case ISD::SRA: 3135 case ISD::SRL: 3136 if (Op.getSimpleValueType().isFixedLengthVector()) 3137 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3138 // This can be called for an i32 shift amount that needs to be promoted. 3139 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3140 "Unexpected custom legalisation"); 3141 return SDValue(); 3142 case ISD::SADDSAT: 3143 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3144 case ISD::UADDSAT: 3145 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3146 case ISD::SSUBSAT: 3147 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3148 case ISD::USUBSAT: 3149 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3150 case ISD::FADD: 3151 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3152 case ISD::FSUB: 3153 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3154 case ISD::FMUL: 3155 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3156 case ISD::FDIV: 3157 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3158 case ISD::FNEG: 3159 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3160 case ISD::FABS: 3161 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3162 case ISD::FSQRT: 3163 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3164 case ISD::FMA: 3165 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3166 case ISD::SMIN: 3167 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3168 case ISD::SMAX: 3169 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3170 case ISD::UMIN: 3171 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3172 case ISD::UMAX: 3173 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3174 case ISD::FMINNUM: 3175 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3176 case ISD::FMAXNUM: 3177 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3178 case ISD::ABS: 3179 return lowerABS(Op, DAG); 3180 case ISD::CTLZ_ZERO_UNDEF: 3181 case ISD::CTTZ_ZERO_UNDEF: 3182 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3183 case ISD::VSELECT: 3184 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3185 case ISD::FCOPYSIGN: 3186 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3187 case ISD::MGATHER: 3188 case ISD::VP_GATHER: 3189 return lowerMaskedGather(Op, DAG); 3190 case ISD::MSCATTER: 3191 case ISD::VP_SCATTER: 3192 return lowerMaskedScatter(Op, DAG); 3193 case ISD::FLT_ROUNDS_: 3194 return lowerGET_ROUNDING(Op, DAG); 3195 case ISD::SET_ROUNDING: 3196 return lowerSET_ROUNDING(Op, DAG); 3197 case ISD::VP_SELECT: 3198 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3199 case ISD::VP_ADD: 3200 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3201 case ISD::VP_SUB: 3202 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3203 case ISD::VP_MUL: 3204 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3205 case ISD::VP_SDIV: 3206 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3207 case ISD::VP_UDIV: 3208 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3209 case ISD::VP_SREM: 3210 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3211 case ISD::VP_UREM: 3212 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3213 case ISD::VP_AND: 3214 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3215 case ISD::VP_OR: 3216 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3217 case ISD::VP_XOR: 3218 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3219 case ISD::VP_ASHR: 3220 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3221 case ISD::VP_LSHR: 3222 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3223 case ISD::VP_SHL: 3224 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3225 case ISD::VP_FADD: 3226 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3227 case ISD::VP_FSUB: 3228 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3229 case ISD::VP_FMUL: 3230 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3231 case ISD::VP_FDIV: 3232 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3233 } 3234 } 3235 3236 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3237 SelectionDAG &DAG, unsigned Flags) { 3238 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3239 } 3240 3241 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3242 SelectionDAG &DAG, unsigned Flags) { 3243 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3244 Flags); 3245 } 3246 3247 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3248 SelectionDAG &DAG, unsigned Flags) { 3249 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3250 N->getOffset(), Flags); 3251 } 3252 3253 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3254 SelectionDAG &DAG, unsigned Flags) { 3255 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3256 } 3257 3258 template <class NodeTy> 3259 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3260 bool IsLocal) const { 3261 SDLoc DL(N); 3262 EVT Ty = getPointerTy(DAG.getDataLayout()); 3263 3264 if (isPositionIndependent()) { 3265 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3266 if (IsLocal) 3267 // Use PC-relative addressing to access the symbol. This generates the 3268 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3269 // %pcrel_lo(auipc)). 3270 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3271 3272 // Use PC-relative addressing to access the GOT for this symbol, then load 3273 // the address from the GOT. This generates the pattern (PseudoLA sym), 3274 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3275 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3276 } 3277 3278 switch (getTargetMachine().getCodeModel()) { 3279 default: 3280 report_fatal_error("Unsupported code model for lowering"); 3281 case CodeModel::Small: { 3282 // Generate a sequence for accessing addresses within the first 2 GiB of 3283 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3284 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3285 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3286 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3287 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3288 } 3289 case CodeModel::Medium: { 3290 // Generate a sequence for accessing addresses within any 2GiB range within 3291 // the address space. This generates the pattern (PseudoLLA sym), which 3292 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3293 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3294 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3295 } 3296 } 3297 } 3298 3299 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3300 SelectionDAG &DAG) const { 3301 SDLoc DL(Op); 3302 EVT Ty = Op.getValueType(); 3303 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3304 int64_t Offset = N->getOffset(); 3305 MVT XLenVT = Subtarget.getXLenVT(); 3306 3307 const GlobalValue *GV = N->getGlobal(); 3308 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3309 SDValue Addr = getAddr(N, DAG, IsLocal); 3310 3311 // In order to maximise the opportunity for common subexpression elimination, 3312 // emit a separate ADD node for the global address offset instead of folding 3313 // it in the global address node. Later peephole optimisations may choose to 3314 // fold it back in when profitable. 3315 if (Offset != 0) 3316 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3317 DAG.getConstant(Offset, DL, XLenVT)); 3318 return Addr; 3319 } 3320 3321 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3322 SelectionDAG &DAG) const { 3323 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3324 3325 return getAddr(N, DAG); 3326 } 3327 3328 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3329 SelectionDAG &DAG) const { 3330 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3331 3332 return getAddr(N, DAG); 3333 } 3334 3335 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3336 SelectionDAG &DAG) const { 3337 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3338 3339 return getAddr(N, DAG); 3340 } 3341 3342 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3343 SelectionDAG &DAG, 3344 bool UseGOT) const { 3345 SDLoc DL(N); 3346 EVT Ty = getPointerTy(DAG.getDataLayout()); 3347 const GlobalValue *GV = N->getGlobal(); 3348 MVT XLenVT = Subtarget.getXLenVT(); 3349 3350 if (UseGOT) { 3351 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3352 // load the address from the GOT and add the thread pointer. This generates 3353 // the pattern (PseudoLA_TLS_IE sym), which expands to 3354 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3355 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3356 SDValue Load = 3357 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3358 3359 // Add the thread pointer. 3360 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3361 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3362 } 3363 3364 // Generate a sequence for accessing the address relative to the thread 3365 // pointer, with the appropriate adjustment for the thread pointer offset. 3366 // This generates the pattern 3367 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3368 SDValue AddrHi = 3369 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3370 SDValue AddrAdd = 3371 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3372 SDValue AddrLo = 3373 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3374 3375 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3376 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3377 SDValue MNAdd = SDValue( 3378 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3379 0); 3380 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3381 } 3382 3383 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3384 SelectionDAG &DAG) const { 3385 SDLoc DL(N); 3386 EVT Ty = getPointerTy(DAG.getDataLayout()); 3387 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3388 const GlobalValue *GV = N->getGlobal(); 3389 3390 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3391 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3392 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3393 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3394 SDValue Load = 3395 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3396 3397 // Prepare argument list to generate call. 3398 ArgListTy Args; 3399 ArgListEntry Entry; 3400 Entry.Node = Load; 3401 Entry.Ty = CallTy; 3402 Args.push_back(Entry); 3403 3404 // Setup call to __tls_get_addr. 3405 TargetLowering::CallLoweringInfo CLI(DAG); 3406 CLI.setDebugLoc(DL) 3407 .setChain(DAG.getEntryNode()) 3408 .setLibCallee(CallingConv::C, CallTy, 3409 DAG.getExternalSymbol("__tls_get_addr", Ty), 3410 std::move(Args)); 3411 3412 return LowerCallTo(CLI).first; 3413 } 3414 3415 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3416 SelectionDAG &DAG) const { 3417 SDLoc DL(Op); 3418 EVT Ty = Op.getValueType(); 3419 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3420 int64_t Offset = N->getOffset(); 3421 MVT XLenVT = Subtarget.getXLenVT(); 3422 3423 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3424 3425 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3426 CallingConv::GHC) 3427 report_fatal_error("In GHC calling convention TLS is not supported"); 3428 3429 SDValue Addr; 3430 switch (Model) { 3431 case TLSModel::LocalExec: 3432 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3433 break; 3434 case TLSModel::InitialExec: 3435 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3436 break; 3437 case TLSModel::LocalDynamic: 3438 case TLSModel::GeneralDynamic: 3439 Addr = getDynamicTLSAddr(N, DAG); 3440 break; 3441 } 3442 3443 // In order to maximise the opportunity for common subexpression elimination, 3444 // emit a separate ADD node for the global address offset instead of folding 3445 // it in the global address node. Later peephole optimisations may choose to 3446 // fold it back in when profitable. 3447 if (Offset != 0) 3448 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3449 DAG.getConstant(Offset, DL, XLenVT)); 3450 return Addr; 3451 } 3452 3453 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3454 SDValue CondV = Op.getOperand(0); 3455 SDValue TrueV = Op.getOperand(1); 3456 SDValue FalseV = Op.getOperand(2); 3457 SDLoc DL(Op); 3458 MVT VT = Op.getSimpleValueType(); 3459 MVT XLenVT = Subtarget.getXLenVT(); 3460 3461 // Lower vector SELECTs to VSELECTs by splatting the condition. 3462 if (VT.isVector()) { 3463 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3464 SDValue CondSplat = VT.isScalableVector() 3465 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3466 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3467 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3468 } 3469 3470 // If the result type is XLenVT and CondV is the output of a SETCC node 3471 // which also operated on XLenVT inputs, then merge the SETCC node into the 3472 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3473 // compare+branch instructions. i.e.: 3474 // (select (setcc lhs, rhs, cc), truev, falsev) 3475 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3476 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3477 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3478 SDValue LHS = CondV.getOperand(0); 3479 SDValue RHS = CondV.getOperand(1); 3480 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3481 ISD::CondCode CCVal = CC->get(); 3482 3483 // Special case for a select of 2 constants that have a diffence of 1. 3484 // Normally this is done by DAGCombine, but if the select is introduced by 3485 // type legalization or op legalization, we miss it. Restricting to SETLT 3486 // case for now because that is what signed saturating add/sub need. 3487 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3488 // but we would probably want to swap the true/false values if the condition 3489 // is SETGE/SETLE to avoid an XORI. 3490 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3491 CCVal == ISD::SETLT) { 3492 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3493 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3494 if (TrueVal - 1 == FalseVal) 3495 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3496 if (TrueVal + 1 == FalseVal) 3497 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3498 } 3499 3500 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3501 3502 SDValue TargetCC = DAG.getCondCode(CCVal); 3503 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3504 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3505 } 3506 3507 // Otherwise: 3508 // (select condv, truev, falsev) 3509 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3510 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3511 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3512 3513 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3514 3515 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3516 } 3517 3518 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3519 SDValue CondV = Op.getOperand(1); 3520 SDLoc DL(Op); 3521 MVT XLenVT = Subtarget.getXLenVT(); 3522 3523 if (CondV.getOpcode() == ISD::SETCC && 3524 CondV.getOperand(0).getValueType() == XLenVT) { 3525 SDValue LHS = CondV.getOperand(0); 3526 SDValue RHS = CondV.getOperand(1); 3527 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3528 3529 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3530 3531 SDValue TargetCC = DAG.getCondCode(CCVal); 3532 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3533 LHS, RHS, TargetCC, Op.getOperand(2)); 3534 } 3535 3536 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3537 CondV, DAG.getConstant(0, DL, XLenVT), 3538 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3539 } 3540 3541 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3542 MachineFunction &MF = DAG.getMachineFunction(); 3543 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3544 3545 SDLoc DL(Op); 3546 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3547 getPointerTy(MF.getDataLayout())); 3548 3549 // vastart just stores the address of the VarArgsFrameIndex slot into the 3550 // memory location argument. 3551 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3552 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3553 MachinePointerInfo(SV)); 3554 } 3555 3556 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3557 SelectionDAG &DAG) const { 3558 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3559 MachineFunction &MF = DAG.getMachineFunction(); 3560 MachineFrameInfo &MFI = MF.getFrameInfo(); 3561 MFI.setFrameAddressIsTaken(true); 3562 Register FrameReg = RI.getFrameRegister(MF); 3563 int XLenInBytes = Subtarget.getXLen() / 8; 3564 3565 EVT VT = Op.getValueType(); 3566 SDLoc DL(Op); 3567 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3568 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3569 while (Depth--) { 3570 int Offset = -(XLenInBytes * 2); 3571 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3572 DAG.getIntPtrConstant(Offset, DL)); 3573 FrameAddr = 3574 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3575 } 3576 return FrameAddr; 3577 } 3578 3579 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3580 SelectionDAG &DAG) const { 3581 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3582 MachineFunction &MF = DAG.getMachineFunction(); 3583 MachineFrameInfo &MFI = MF.getFrameInfo(); 3584 MFI.setReturnAddressIsTaken(true); 3585 MVT XLenVT = Subtarget.getXLenVT(); 3586 int XLenInBytes = Subtarget.getXLen() / 8; 3587 3588 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3589 return SDValue(); 3590 3591 EVT VT = Op.getValueType(); 3592 SDLoc DL(Op); 3593 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3594 if (Depth) { 3595 int Off = -XLenInBytes; 3596 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3597 SDValue Offset = DAG.getConstant(Off, DL, VT); 3598 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3599 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3600 MachinePointerInfo()); 3601 } 3602 3603 // Return the value of the return address register, marking it an implicit 3604 // live-in. 3605 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3606 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3607 } 3608 3609 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3610 SelectionDAG &DAG) const { 3611 SDLoc DL(Op); 3612 SDValue Lo = Op.getOperand(0); 3613 SDValue Hi = Op.getOperand(1); 3614 SDValue Shamt = Op.getOperand(2); 3615 EVT VT = Lo.getValueType(); 3616 3617 // if Shamt-XLEN < 0: // Shamt < XLEN 3618 // Lo = Lo << Shamt 3619 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3620 // else: 3621 // Lo = 0 3622 // Hi = Lo << (Shamt-XLEN) 3623 3624 SDValue Zero = DAG.getConstant(0, DL, VT); 3625 SDValue One = DAG.getConstant(1, DL, VT); 3626 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3627 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3628 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3629 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3630 3631 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3632 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3633 SDValue ShiftRightLo = 3634 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3635 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3636 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3637 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3638 3639 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3640 3641 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3642 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3643 3644 SDValue Parts[2] = {Lo, Hi}; 3645 return DAG.getMergeValues(Parts, DL); 3646 } 3647 3648 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3649 bool IsSRA) const { 3650 SDLoc DL(Op); 3651 SDValue Lo = Op.getOperand(0); 3652 SDValue Hi = Op.getOperand(1); 3653 SDValue Shamt = Op.getOperand(2); 3654 EVT VT = Lo.getValueType(); 3655 3656 // SRA expansion: 3657 // if Shamt-XLEN < 0: // Shamt < XLEN 3658 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3659 // Hi = Hi >>s Shamt 3660 // else: 3661 // Lo = Hi >>s (Shamt-XLEN); 3662 // Hi = Hi >>s (XLEN-1) 3663 // 3664 // SRL expansion: 3665 // if Shamt-XLEN < 0: // Shamt < XLEN 3666 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3667 // Hi = Hi >>u Shamt 3668 // else: 3669 // Lo = Hi >>u (Shamt-XLEN); 3670 // Hi = 0; 3671 3672 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3673 3674 SDValue Zero = DAG.getConstant(0, DL, VT); 3675 SDValue One = DAG.getConstant(1, DL, VT); 3676 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3677 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3678 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3679 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3680 3681 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3682 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3683 SDValue ShiftLeftHi = 3684 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3685 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3686 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3687 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3688 SDValue HiFalse = 3689 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3690 3691 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3692 3693 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3694 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3695 3696 SDValue Parts[2] = {Lo, Hi}; 3697 return DAG.getMergeValues(Parts, DL); 3698 } 3699 3700 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3701 // legal equivalently-sized i8 type, so we can use that as a go-between. 3702 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3703 SelectionDAG &DAG) const { 3704 SDLoc DL(Op); 3705 MVT VT = Op.getSimpleValueType(); 3706 SDValue SplatVal = Op.getOperand(0); 3707 // All-zeros or all-ones splats are handled specially. 3708 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3709 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3710 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3711 } 3712 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3713 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3714 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3715 } 3716 MVT XLenVT = Subtarget.getXLenVT(); 3717 assert(SplatVal.getValueType() == XLenVT && 3718 "Unexpected type for i1 splat value"); 3719 MVT InterVT = VT.changeVectorElementType(MVT::i8); 3720 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 3721 DAG.getConstant(1, DL, XLenVT)); 3722 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 3723 SDValue Zero = DAG.getConstant(0, DL, InterVT); 3724 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 3725 } 3726 3727 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 3728 // illegal (currently only vXi64 RV32). 3729 // FIXME: We could also catch non-constant sign-extended i32 values and lower 3730 // them to SPLAT_VECTOR_I64 3731 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 3732 SelectionDAG &DAG) const { 3733 SDLoc DL(Op); 3734 MVT VecVT = Op.getSimpleValueType(); 3735 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 3736 "Unexpected SPLAT_VECTOR_PARTS lowering"); 3737 3738 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 3739 SDValue Lo = Op.getOperand(0); 3740 SDValue Hi = Op.getOperand(1); 3741 3742 if (VecVT.isFixedLengthVector()) { 3743 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3744 SDLoc DL(Op); 3745 SDValue Mask, VL; 3746 std::tie(Mask, VL) = 3747 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3748 3749 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 3750 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 3751 } 3752 3753 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 3754 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 3755 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 3756 // If Hi constant is all the same sign bit as Lo, lower this as a custom 3757 // node in order to try and match RVV vector/scalar instructions. 3758 if ((LoC >> 31) == HiC) 3759 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3760 } 3761 3762 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 3763 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 3764 isa<ConstantSDNode>(Hi.getOperand(1)) && 3765 Hi.getConstantOperandVal(1) == 31) 3766 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 3767 3768 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 3769 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 3770 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 3771 } 3772 3773 // Custom-lower extensions from mask vectors by using a vselect either with 1 3774 // for zero/any-extension or -1 for sign-extension: 3775 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 3776 // Note that any-extension is lowered identically to zero-extension. 3777 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 3778 int64_t ExtTrueVal) const { 3779 SDLoc DL(Op); 3780 MVT VecVT = Op.getSimpleValueType(); 3781 SDValue Src = Op.getOperand(0); 3782 // Only custom-lower extensions from mask types 3783 assert(Src.getValueType().isVector() && 3784 Src.getValueType().getVectorElementType() == MVT::i1); 3785 3786 MVT XLenVT = Subtarget.getXLenVT(); 3787 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 3788 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 3789 3790 if (VecVT.isScalableVector()) { 3791 // Be careful not to introduce illegal scalar types at this stage, and be 3792 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 3793 // illegal and must be expanded. Since we know that the constants are 3794 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 3795 bool IsRV32E64 = 3796 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 3797 3798 if (!IsRV32E64) { 3799 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 3800 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 3801 } else { 3802 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 3803 SplatTrueVal = 3804 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 3805 } 3806 3807 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 3808 } 3809 3810 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 3811 MVT I1ContainerVT = 3812 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3813 3814 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 3815 3816 SDValue Mask, VL; 3817 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3818 3819 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 3820 SplatTrueVal = 3821 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 3822 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 3823 SplatTrueVal, SplatZero, VL); 3824 3825 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 3826 } 3827 3828 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 3829 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 3830 MVT ExtVT = Op.getSimpleValueType(); 3831 // Only custom-lower extensions from fixed-length vector types. 3832 if (!ExtVT.isFixedLengthVector()) 3833 return Op; 3834 MVT VT = Op.getOperand(0).getSimpleValueType(); 3835 // Grab the canonical container type for the extended type. Infer the smaller 3836 // type from that to ensure the same number of vector elements, as we know 3837 // the LMUL will be sufficient to hold the smaller type. 3838 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 3839 // Get the extended container type manually to ensure the same number of 3840 // vector elements between source and dest. 3841 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 3842 ContainerExtVT.getVectorElementCount()); 3843 3844 SDValue Op1 = 3845 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3846 3847 SDLoc DL(Op); 3848 SDValue Mask, VL; 3849 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3850 3851 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 3852 3853 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 3854 } 3855 3856 // Custom-lower truncations from vectors to mask vectors by using a mask and a 3857 // setcc operation: 3858 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 3859 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 3860 SelectionDAG &DAG) const { 3861 SDLoc DL(Op); 3862 EVT MaskVT = Op.getValueType(); 3863 // Only expect to custom-lower truncations to mask types 3864 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 3865 "Unexpected type for vector mask lowering"); 3866 SDValue Src = Op.getOperand(0); 3867 MVT VecVT = Src.getSimpleValueType(); 3868 3869 // If this is a fixed vector, we need to convert it to a scalable vector. 3870 MVT ContainerVT = VecVT; 3871 if (VecVT.isFixedLengthVector()) { 3872 ContainerVT = getContainerForFixedLengthVector(VecVT); 3873 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3874 } 3875 3876 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 3877 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 3878 3879 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 3880 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 3881 3882 if (VecVT.isScalableVector()) { 3883 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 3884 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 3885 } 3886 3887 SDValue Mask, VL; 3888 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3889 3890 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 3891 SDValue Trunc = 3892 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 3893 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 3894 DAG.getCondCode(ISD::SETNE), Mask, VL); 3895 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 3896 } 3897 3898 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 3899 // first position of a vector, and that vector is slid up to the insert index. 3900 // By limiting the active vector length to index+1 and merging with the 3901 // original vector (with an undisturbed tail policy for elements >= VL), we 3902 // achieve the desired result of leaving all elements untouched except the one 3903 // at VL-1, which is replaced with the desired value. 3904 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3905 SelectionDAG &DAG) const { 3906 SDLoc DL(Op); 3907 MVT VecVT = Op.getSimpleValueType(); 3908 SDValue Vec = Op.getOperand(0); 3909 SDValue Val = Op.getOperand(1); 3910 SDValue Idx = Op.getOperand(2); 3911 3912 if (VecVT.getVectorElementType() == MVT::i1) { 3913 // FIXME: For now we just promote to an i8 vector and insert into that, 3914 // but this is probably not optimal. 3915 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 3916 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 3917 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 3918 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 3919 } 3920 3921 MVT ContainerVT = VecVT; 3922 // If the operand is a fixed-length vector, convert to a scalable one. 3923 if (VecVT.isFixedLengthVector()) { 3924 ContainerVT = getContainerForFixedLengthVector(VecVT); 3925 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3926 } 3927 3928 MVT XLenVT = Subtarget.getXLenVT(); 3929 3930 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3931 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 3932 // Even i64-element vectors on RV32 can be lowered without scalar 3933 // legalization if the most-significant 32 bits of the value are not affected 3934 // by the sign-extension of the lower 32 bits. 3935 // TODO: We could also catch sign extensions of a 32-bit value. 3936 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 3937 const auto *CVal = cast<ConstantSDNode>(Val); 3938 if (isInt<32>(CVal->getSExtValue())) { 3939 IsLegalInsert = true; 3940 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 3941 } 3942 } 3943 3944 SDValue Mask, VL; 3945 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 3946 3947 SDValue ValInVec; 3948 3949 if (IsLegalInsert) { 3950 unsigned Opc = 3951 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 3952 if (isNullConstant(Idx)) { 3953 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 3954 if (!VecVT.isFixedLengthVector()) 3955 return Vec; 3956 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 3957 } 3958 ValInVec = 3959 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 3960 } else { 3961 // On RV32, i64-element vectors must be specially handled to place the 3962 // value at element 0, by using two vslide1up instructions in sequence on 3963 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 3964 // this. 3965 SDValue One = DAG.getConstant(1, DL, XLenVT); 3966 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 3967 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 3968 MVT I32ContainerVT = 3969 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 3970 SDValue I32Mask = 3971 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 3972 // Limit the active VL to two. 3973 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 3974 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 3975 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 3976 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 3977 InsertI64VL); 3978 // First slide in the hi value, then the lo in underneath it. 3979 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3980 ValHi, I32Mask, InsertI64VL); 3981 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 3982 ValLo, I32Mask, InsertI64VL); 3983 // Bitcast back to the right container type. 3984 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 3985 } 3986 3987 // Now that the value is in a vector, slide it into position. 3988 SDValue InsertVL = 3989 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 3990 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 3991 ValInVec, Idx, Mask, InsertVL); 3992 if (!VecVT.isFixedLengthVector()) 3993 return Slideup; 3994 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 3995 } 3996 3997 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 3998 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 3999 // types this is done using VMV_X_S to allow us to glean information about the 4000 // sign bits of the result. 4001 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4002 SelectionDAG &DAG) const { 4003 SDLoc DL(Op); 4004 SDValue Idx = Op.getOperand(1); 4005 SDValue Vec = Op.getOperand(0); 4006 EVT EltVT = Op.getValueType(); 4007 MVT VecVT = Vec.getSimpleValueType(); 4008 MVT XLenVT = Subtarget.getXLenVT(); 4009 4010 if (VecVT.getVectorElementType() == MVT::i1) { 4011 // FIXME: For now we just promote to an i8 vector and extract from that, 4012 // but this is probably not optimal. 4013 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4014 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4015 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4016 } 4017 4018 // If this is a fixed vector, we need to convert it to a scalable vector. 4019 MVT ContainerVT = VecVT; 4020 if (VecVT.isFixedLengthVector()) { 4021 ContainerVT = getContainerForFixedLengthVector(VecVT); 4022 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4023 } 4024 4025 // If the index is 0, the vector is already in the right position. 4026 if (!isNullConstant(Idx)) { 4027 // Use a VL of 1 to avoid processing more elements than we need. 4028 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4029 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4030 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4031 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4032 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4033 } 4034 4035 if (!EltVT.isInteger()) { 4036 // Floating-point extracts are handled in TableGen. 4037 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4038 DAG.getConstant(0, DL, XLenVT)); 4039 } 4040 4041 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4042 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4043 } 4044 4045 // Some RVV intrinsics may claim that they want an integer operand to be 4046 // promoted or expanded. 4047 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4048 const RISCVSubtarget &Subtarget) { 4049 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4050 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4051 "Unexpected opcode"); 4052 4053 if (!Subtarget.hasVInstructions()) 4054 return SDValue(); 4055 4056 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4057 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4058 SDLoc DL(Op); 4059 4060 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4061 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4062 if (!II || !II->SplatOperand) 4063 return SDValue(); 4064 4065 unsigned SplatOp = II->SplatOperand + HasChain; 4066 assert(SplatOp < Op.getNumOperands()); 4067 4068 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4069 SDValue &ScalarOp = Operands[SplatOp]; 4070 MVT OpVT = ScalarOp.getSimpleValueType(); 4071 MVT XLenVT = Subtarget.getXLenVT(); 4072 4073 // If this isn't a scalar, or its type is XLenVT we're done. 4074 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4075 return SDValue(); 4076 4077 // Simplest case is that the operand needs to be promoted to XLenVT. 4078 if (OpVT.bitsLT(XLenVT)) { 4079 // If the operand is a constant, sign extend to increase our chances 4080 // of being able to use a .vi instruction. ANY_EXTEND would become a 4081 // a zero extend and the simm5 check in isel would fail. 4082 // FIXME: Should we ignore the upper bits in isel instead? 4083 unsigned ExtOpc = 4084 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4085 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4086 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4087 } 4088 4089 // Use the previous operand to get the vXi64 VT. The result might be a mask 4090 // VT for compares. Using the previous operand assumes that the previous 4091 // operand will never have a smaller element size than a scalar operand and 4092 // that a widening operation never uses SEW=64. 4093 // NOTE: If this fails the below assert, we can probably just find the 4094 // element count from any operand or result and use it to construct the VT. 4095 assert(II->SplatOperand > 1 && "Unexpected splat operand!"); 4096 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4097 4098 // The more complex case is when the scalar is larger than XLenVT. 4099 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4100 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4101 4102 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4103 // on the instruction to sign-extend since SEW>XLEN. 4104 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4105 if (isInt<32>(CVal->getSExtValue())) { 4106 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4107 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4108 } 4109 } 4110 4111 // We need to convert the scalar to a splat vector. 4112 // FIXME: Can we implicitly truncate the scalar if it is known to 4113 // be sign extended? 4114 // VL should be the last operand. 4115 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 4116 assert(VL.getValueType() == XLenVT); 4117 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4118 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4119 } 4120 4121 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4122 SelectionDAG &DAG) const { 4123 unsigned IntNo = Op.getConstantOperandVal(0); 4124 SDLoc DL(Op); 4125 MVT XLenVT = Subtarget.getXLenVT(); 4126 4127 switch (IntNo) { 4128 default: 4129 break; // Don't custom lower most intrinsics. 4130 case Intrinsic::thread_pointer: { 4131 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4132 return DAG.getRegister(RISCV::X4, PtrVT); 4133 } 4134 case Intrinsic::riscv_orc_b: 4135 // Lower to the GORCI encoding for orc.b. 4136 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 4137 DAG.getConstant(7, DL, XLenVT)); 4138 case Intrinsic::riscv_grev: 4139 case Intrinsic::riscv_gorc: { 4140 unsigned Opc = 4141 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4142 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4143 } 4144 case Intrinsic::riscv_shfl: 4145 case Intrinsic::riscv_unshfl: { 4146 unsigned Opc = 4147 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4148 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4149 } 4150 case Intrinsic::riscv_bcompress: 4151 case Intrinsic::riscv_bdecompress: { 4152 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4153 : RISCVISD::BDECOMPRESS; 4154 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4155 } 4156 case Intrinsic::riscv_vmv_x_s: 4157 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4158 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4159 Op.getOperand(1)); 4160 case Intrinsic::riscv_vmv_v_x: 4161 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4162 Op.getSimpleValueType(), DL, DAG, Subtarget); 4163 case Intrinsic::riscv_vfmv_v_f: 4164 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4165 Op.getOperand(1), Op.getOperand(2)); 4166 case Intrinsic::riscv_vmv_s_x: { 4167 SDValue Scalar = Op.getOperand(2); 4168 4169 if (Scalar.getValueType().bitsLE(XLenVT)) { 4170 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4171 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4172 Op.getOperand(1), Scalar, Op.getOperand(3)); 4173 } 4174 4175 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4176 4177 // This is an i64 value that lives in two scalar registers. We have to 4178 // insert this in a convoluted way. First we build vXi64 splat containing 4179 // the/ two values that we assemble using some bit math. Next we'll use 4180 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4181 // to merge element 0 from our splat into the source vector. 4182 // FIXME: This is probably not the best way to do this, but it is 4183 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4184 // point. 4185 // sw lo, (a0) 4186 // sw hi, 4(a0) 4187 // vlse vX, (a0) 4188 // 4189 // vid.v vVid 4190 // vmseq.vx mMask, vVid, 0 4191 // vmerge.vvm vDest, vSrc, vVal, mMask 4192 MVT VT = Op.getSimpleValueType(); 4193 SDValue Vec = Op.getOperand(1); 4194 SDValue VL = Op.getOperand(3); 4195 4196 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4197 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4198 DAG.getConstant(0, DL, MVT::i32), VL); 4199 4200 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4201 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4202 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4203 SDValue SelectCond = 4204 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4205 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4206 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4207 Vec, VL); 4208 } 4209 case Intrinsic::riscv_vslide1up: 4210 case Intrinsic::riscv_vslide1down: 4211 case Intrinsic::riscv_vslide1up_mask: 4212 case Intrinsic::riscv_vslide1down_mask: { 4213 // We need to special case these when the scalar is larger than XLen. 4214 unsigned NumOps = Op.getNumOperands(); 4215 bool IsMasked = NumOps == 7; 4216 unsigned OpOffset = IsMasked ? 1 : 0; 4217 SDValue Scalar = Op.getOperand(2 + OpOffset); 4218 if (Scalar.getValueType().bitsLE(XLenVT)) 4219 break; 4220 4221 // Splatting a sign extended constant is fine. 4222 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4223 if (isInt<32>(CVal->getSExtValue())) 4224 break; 4225 4226 MVT VT = Op.getSimpleValueType(); 4227 assert(VT.getVectorElementType() == MVT::i64 && 4228 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4229 4230 // Convert the vector source to the equivalent nxvXi32 vector. 4231 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4232 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4233 4234 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4235 DAG.getConstant(0, DL, XLenVT)); 4236 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4237 DAG.getConstant(1, DL, XLenVT)); 4238 4239 // Double the VL since we halved SEW. 4240 SDValue VL = Op.getOperand(NumOps - (1 + OpOffset)); 4241 SDValue I32VL = 4242 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4243 4244 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4245 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4246 4247 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4248 // instructions. 4249 if (IntNo == Intrinsic::riscv_vslide1up || 4250 IntNo == Intrinsic::riscv_vslide1up_mask) { 4251 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4252 I32Mask, I32VL); 4253 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4254 I32Mask, I32VL); 4255 } else { 4256 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4257 I32Mask, I32VL); 4258 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4259 I32Mask, I32VL); 4260 } 4261 4262 // Convert back to nxvXi64. 4263 Vec = DAG.getBitcast(VT, Vec); 4264 4265 if (!IsMasked) 4266 return Vec; 4267 4268 // Apply mask after the operation. 4269 SDValue Mask = Op.getOperand(NumOps - 3); 4270 SDValue MaskedOff = Op.getOperand(1); 4271 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4272 } 4273 } 4274 4275 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4276 } 4277 4278 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4279 SelectionDAG &DAG) const { 4280 unsigned IntNo = Op.getConstantOperandVal(1); 4281 switch (IntNo) { 4282 default: 4283 break; 4284 case Intrinsic::riscv_masked_strided_load: { 4285 SDLoc DL(Op); 4286 MVT XLenVT = Subtarget.getXLenVT(); 4287 4288 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4289 // the selection of the masked intrinsics doesn't do this for us. 4290 SDValue Mask = Op.getOperand(5); 4291 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4292 4293 MVT VT = Op->getSimpleValueType(0); 4294 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4295 4296 SDValue PassThru = Op.getOperand(2); 4297 if (!IsUnmasked) { 4298 MVT MaskVT = 4299 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4300 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4301 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4302 } 4303 4304 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4305 4306 SDValue IntID = DAG.getTargetConstant( 4307 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4308 XLenVT); 4309 4310 auto *Load = cast<MemIntrinsicSDNode>(Op); 4311 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4312 if (!IsUnmasked) 4313 Ops.push_back(PassThru); 4314 Ops.push_back(Op.getOperand(3)); // Ptr 4315 Ops.push_back(Op.getOperand(4)); // Stride 4316 if (!IsUnmasked) 4317 Ops.push_back(Mask); 4318 Ops.push_back(VL); 4319 if (!IsUnmasked) { 4320 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4321 Ops.push_back(Policy); 4322 } 4323 4324 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4325 SDValue Result = 4326 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4327 Load->getMemoryVT(), Load->getMemOperand()); 4328 SDValue Chain = Result.getValue(1); 4329 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4330 return DAG.getMergeValues({Result, Chain}, DL); 4331 } 4332 } 4333 4334 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4335 } 4336 4337 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4338 SelectionDAG &DAG) const { 4339 unsigned IntNo = Op.getConstantOperandVal(1); 4340 switch (IntNo) { 4341 default: 4342 break; 4343 case Intrinsic::riscv_masked_strided_store: { 4344 SDLoc DL(Op); 4345 MVT XLenVT = Subtarget.getXLenVT(); 4346 4347 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4348 // the selection of the masked intrinsics doesn't do this for us. 4349 SDValue Mask = Op.getOperand(5); 4350 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4351 4352 SDValue Val = Op.getOperand(2); 4353 MVT VT = Val.getSimpleValueType(); 4354 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4355 4356 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4357 if (!IsUnmasked) { 4358 MVT MaskVT = 4359 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4360 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4361 } 4362 4363 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4364 4365 SDValue IntID = DAG.getTargetConstant( 4366 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4367 XLenVT); 4368 4369 auto *Store = cast<MemIntrinsicSDNode>(Op); 4370 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4371 Ops.push_back(Val); 4372 Ops.push_back(Op.getOperand(3)); // Ptr 4373 Ops.push_back(Op.getOperand(4)); // Stride 4374 if (!IsUnmasked) 4375 Ops.push_back(Mask); 4376 Ops.push_back(VL); 4377 4378 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4379 Ops, Store->getMemoryVT(), 4380 Store->getMemOperand()); 4381 } 4382 } 4383 4384 return SDValue(); 4385 } 4386 4387 static MVT getLMUL1VT(MVT VT) { 4388 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4389 "Unexpected vector MVT"); 4390 return MVT::getScalableVectorVT( 4391 VT.getVectorElementType(), 4392 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4393 } 4394 4395 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4396 switch (ISDOpcode) { 4397 default: 4398 llvm_unreachable("Unhandled reduction"); 4399 case ISD::VECREDUCE_ADD: 4400 return RISCVISD::VECREDUCE_ADD_VL; 4401 case ISD::VECREDUCE_UMAX: 4402 return RISCVISD::VECREDUCE_UMAX_VL; 4403 case ISD::VECREDUCE_SMAX: 4404 return RISCVISD::VECREDUCE_SMAX_VL; 4405 case ISD::VECREDUCE_UMIN: 4406 return RISCVISD::VECREDUCE_UMIN_VL; 4407 case ISD::VECREDUCE_SMIN: 4408 return RISCVISD::VECREDUCE_SMIN_VL; 4409 case ISD::VECREDUCE_AND: 4410 return RISCVISD::VECREDUCE_AND_VL; 4411 case ISD::VECREDUCE_OR: 4412 return RISCVISD::VECREDUCE_OR_VL; 4413 case ISD::VECREDUCE_XOR: 4414 return RISCVISD::VECREDUCE_XOR_VL; 4415 } 4416 } 4417 4418 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4419 SelectionDAG &DAG, 4420 bool IsVP) const { 4421 SDLoc DL(Op); 4422 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4423 MVT VecVT = Vec.getSimpleValueType(); 4424 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4425 Op.getOpcode() == ISD::VECREDUCE_OR || 4426 Op.getOpcode() == ISD::VECREDUCE_XOR || 4427 Op.getOpcode() == ISD::VP_REDUCE_AND || 4428 Op.getOpcode() == ISD::VP_REDUCE_OR || 4429 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4430 "Unexpected reduction lowering"); 4431 4432 MVT XLenVT = Subtarget.getXLenVT(); 4433 assert(Op.getValueType() == XLenVT && 4434 "Expected reduction output to be legalized to XLenVT"); 4435 4436 MVT ContainerVT = VecVT; 4437 if (VecVT.isFixedLengthVector()) { 4438 ContainerVT = getContainerForFixedLengthVector(VecVT); 4439 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4440 } 4441 4442 SDValue Mask, VL; 4443 if (IsVP) { 4444 Mask = Op.getOperand(2); 4445 VL = Op.getOperand(3); 4446 } else { 4447 std::tie(Mask, VL) = 4448 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4449 } 4450 4451 unsigned BaseOpc; 4452 ISD::CondCode CC; 4453 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4454 4455 switch (Op.getOpcode()) { 4456 default: 4457 llvm_unreachable("Unhandled reduction"); 4458 case ISD::VECREDUCE_AND: 4459 case ISD::VP_REDUCE_AND: { 4460 // vcpop ~x == 0 4461 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4462 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4463 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4464 CC = ISD::SETEQ; 4465 BaseOpc = ISD::AND; 4466 break; 4467 } 4468 case ISD::VECREDUCE_OR: 4469 case ISD::VP_REDUCE_OR: 4470 // vcpop x != 0 4471 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4472 CC = ISD::SETNE; 4473 BaseOpc = ISD::OR; 4474 break; 4475 case ISD::VECREDUCE_XOR: 4476 case ISD::VP_REDUCE_XOR: { 4477 // ((vcpop x) & 1) != 0 4478 SDValue One = DAG.getConstant(1, DL, XLenVT); 4479 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4480 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4481 CC = ISD::SETNE; 4482 BaseOpc = ISD::XOR; 4483 break; 4484 } 4485 } 4486 4487 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4488 4489 if (!IsVP) 4490 return SetCC; 4491 4492 // Now include the start value in the operation. 4493 // Note that we must return the start value when no elements are operated 4494 // upon. The vcpop instructions we've emitted in each case above will return 4495 // 0 for an inactive vector, and so we've already received the neutral value: 4496 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4497 // can simply include the start value. 4498 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4499 } 4500 4501 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4502 SelectionDAG &DAG) const { 4503 SDLoc DL(Op); 4504 SDValue Vec = Op.getOperand(0); 4505 EVT VecEVT = Vec.getValueType(); 4506 4507 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4508 4509 // Due to ordering in legalize types we may have a vector type that needs to 4510 // be split. Do that manually so we can get down to a legal type. 4511 while (getTypeAction(*DAG.getContext(), VecEVT) == 4512 TargetLowering::TypeSplitVector) { 4513 SDValue Lo, Hi; 4514 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4515 VecEVT = Lo.getValueType(); 4516 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4517 } 4518 4519 // TODO: The type may need to be widened rather than split. Or widened before 4520 // it can be split. 4521 if (!isTypeLegal(VecEVT)) 4522 return SDValue(); 4523 4524 MVT VecVT = VecEVT.getSimpleVT(); 4525 MVT VecEltVT = VecVT.getVectorElementType(); 4526 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4527 4528 MVT ContainerVT = VecVT; 4529 if (VecVT.isFixedLengthVector()) { 4530 ContainerVT = getContainerForFixedLengthVector(VecVT); 4531 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4532 } 4533 4534 MVT M1VT = getLMUL1VT(ContainerVT); 4535 MVT XLenVT = Subtarget.getXLenVT(); 4536 4537 SDValue Mask, VL; 4538 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4539 4540 SDValue NeutralElem = 4541 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4542 SDValue IdentitySplat = lowerScalarSplat( 4543 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4544 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4545 IdentitySplat, Mask, VL); 4546 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4547 DAG.getConstant(0, DL, XLenVT)); 4548 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4549 } 4550 4551 // Given a reduction op, this function returns the matching reduction opcode, 4552 // the vector SDValue and the scalar SDValue required to lower this to a 4553 // RISCVISD node. 4554 static std::tuple<unsigned, SDValue, SDValue> 4555 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4556 SDLoc DL(Op); 4557 auto Flags = Op->getFlags(); 4558 unsigned Opcode = Op.getOpcode(); 4559 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4560 switch (Opcode) { 4561 default: 4562 llvm_unreachable("Unhandled reduction"); 4563 case ISD::VECREDUCE_FADD: { 4564 // Use positive zero if we can. It is cheaper to materialize. 4565 SDValue Zero = 4566 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 4567 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 4568 } 4569 case ISD::VECREDUCE_SEQ_FADD: 4570 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4571 Op.getOperand(0)); 4572 case ISD::VECREDUCE_FMIN: 4573 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4574 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4575 case ISD::VECREDUCE_FMAX: 4576 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4577 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4578 } 4579 } 4580 4581 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4582 SelectionDAG &DAG) const { 4583 SDLoc DL(Op); 4584 MVT VecEltVT = Op.getSimpleValueType(); 4585 4586 unsigned RVVOpcode; 4587 SDValue VectorVal, ScalarVal; 4588 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4589 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4590 MVT VecVT = VectorVal.getSimpleValueType(); 4591 4592 MVT ContainerVT = VecVT; 4593 if (VecVT.isFixedLengthVector()) { 4594 ContainerVT = getContainerForFixedLengthVector(VecVT); 4595 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4596 } 4597 4598 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4599 MVT XLenVT = Subtarget.getXLenVT(); 4600 4601 SDValue Mask, VL; 4602 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4603 4604 SDValue ScalarSplat = lowerScalarSplat( 4605 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4606 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4607 VectorVal, ScalarSplat, Mask, VL); 4608 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4609 DAG.getConstant(0, DL, XLenVT)); 4610 } 4611 4612 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4613 switch (ISDOpcode) { 4614 default: 4615 llvm_unreachable("Unhandled reduction"); 4616 case ISD::VP_REDUCE_ADD: 4617 return RISCVISD::VECREDUCE_ADD_VL; 4618 case ISD::VP_REDUCE_UMAX: 4619 return RISCVISD::VECREDUCE_UMAX_VL; 4620 case ISD::VP_REDUCE_SMAX: 4621 return RISCVISD::VECREDUCE_SMAX_VL; 4622 case ISD::VP_REDUCE_UMIN: 4623 return RISCVISD::VECREDUCE_UMIN_VL; 4624 case ISD::VP_REDUCE_SMIN: 4625 return RISCVISD::VECREDUCE_SMIN_VL; 4626 case ISD::VP_REDUCE_AND: 4627 return RISCVISD::VECREDUCE_AND_VL; 4628 case ISD::VP_REDUCE_OR: 4629 return RISCVISD::VECREDUCE_OR_VL; 4630 case ISD::VP_REDUCE_XOR: 4631 return RISCVISD::VECREDUCE_XOR_VL; 4632 case ISD::VP_REDUCE_FADD: 4633 return RISCVISD::VECREDUCE_FADD_VL; 4634 case ISD::VP_REDUCE_SEQ_FADD: 4635 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4636 case ISD::VP_REDUCE_FMAX: 4637 return RISCVISD::VECREDUCE_FMAX_VL; 4638 case ISD::VP_REDUCE_FMIN: 4639 return RISCVISD::VECREDUCE_FMIN_VL; 4640 } 4641 } 4642 4643 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4644 SelectionDAG &DAG) const { 4645 SDLoc DL(Op); 4646 SDValue Vec = Op.getOperand(1); 4647 EVT VecEVT = Vec.getValueType(); 4648 4649 // TODO: The type may need to be widened rather than split. Or widened before 4650 // it can be split. 4651 if (!isTypeLegal(VecEVT)) 4652 return SDValue(); 4653 4654 MVT VecVT = VecEVT.getSimpleVT(); 4655 MVT VecEltVT = VecVT.getVectorElementType(); 4656 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4657 4658 MVT ContainerVT = VecVT; 4659 if (VecVT.isFixedLengthVector()) { 4660 ContainerVT = getContainerForFixedLengthVector(VecVT); 4661 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4662 } 4663 4664 SDValue VL = Op.getOperand(3); 4665 SDValue Mask = Op.getOperand(2); 4666 4667 MVT M1VT = getLMUL1VT(ContainerVT); 4668 MVT XLenVT = Subtarget.getXLenVT(); 4669 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4670 4671 SDValue StartSplat = 4672 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 4673 DL, DAG, Subtarget); 4674 SDValue Reduction = 4675 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4676 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4677 DAG.getConstant(0, DL, XLenVT)); 4678 if (!VecVT.isInteger()) 4679 return Elt0; 4680 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4681 } 4682 4683 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4684 SelectionDAG &DAG) const { 4685 SDValue Vec = Op.getOperand(0); 4686 SDValue SubVec = Op.getOperand(1); 4687 MVT VecVT = Vec.getSimpleValueType(); 4688 MVT SubVecVT = SubVec.getSimpleValueType(); 4689 4690 SDLoc DL(Op); 4691 MVT XLenVT = Subtarget.getXLenVT(); 4692 unsigned OrigIdx = Op.getConstantOperandVal(2); 4693 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4694 4695 // We don't have the ability to slide mask vectors up indexed by their i1 4696 // elements; the smallest we can do is i8. Often we are able to bitcast to 4697 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4698 // into a scalable one, we might not necessarily have enough scalable 4699 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4700 if (SubVecVT.getVectorElementType() == MVT::i1 && 4701 (OrigIdx != 0 || !Vec.isUndef())) { 4702 if (VecVT.getVectorMinNumElements() >= 8 && 4703 SubVecVT.getVectorMinNumElements() >= 8) { 4704 assert(OrigIdx % 8 == 0 && "Invalid index"); 4705 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4706 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4707 "Unexpected mask vector lowering"); 4708 OrigIdx /= 8; 4709 SubVecVT = 4710 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4711 SubVecVT.isScalableVector()); 4712 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4713 VecVT.isScalableVector()); 4714 Vec = DAG.getBitcast(VecVT, Vec); 4715 SubVec = DAG.getBitcast(SubVecVT, SubVec); 4716 } else { 4717 // We can't slide this mask vector up indexed by its i1 elements. 4718 // This poses a problem when we wish to insert a scalable vector which 4719 // can't be re-expressed as a larger type. Just choose the slow path and 4720 // extend to a larger type, then truncate back down. 4721 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4722 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4723 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4724 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 4725 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 4726 Op.getOperand(2)); 4727 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 4728 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 4729 } 4730 } 4731 4732 // If the subvector vector is a fixed-length type, we cannot use subregister 4733 // manipulation to simplify the codegen; we don't know which register of a 4734 // LMUL group contains the specific subvector as we only know the minimum 4735 // register size. Therefore we must slide the vector group up the full 4736 // amount. 4737 if (SubVecVT.isFixedLengthVector()) { 4738 if (OrigIdx == 0 && Vec.isUndef()) 4739 return Op; 4740 MVT ContainerVT = VecVT; 4741 if (VecVT.isFixedLengthVector()) { 4742 ContainerVT = getContainerForFixedLengthVector(VecVT); 4743 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4744 } 4745 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 4746 DAG.getUNDEF(ContainerVT), SubVec, 4747 DAG.getConstant(0, DL, XLenVT)); 4748 SDValue Mask = 4749 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4750 // Set the vector length to only the number of elements we care about. Note 4751 // that for slideup this includes the offset. 4752 SDValue VL = 4753 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 4754 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4755 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4756 SubVec, SlideupAmt, Mask, VL); 4757 if (VecVT.isFixedLengthVector()) 4758 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4759 return DAG.getBitcast(Op.getValueType(), Slideup); 4760 } 4761 4762 unsigned SubRegIdx, RemIdx; 4763 std::tie(SubRegIdx, RemIdx) = 4764 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4765 VecVT, SubVecVT, OrigIdx, TRI); 4766 4767 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 4768 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 4769 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 4770 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 4771 4772 // 1. If the Idx has been completely eliminated and this subvector's size is 4773 // a vector register or a multiple thereof, or the surrounding elements are 4774 // undef, then this is a subvector insert which naturally aligns to a vector 4775 // register. These can easily be handled using subregister manipulation. 4776 // 2. If the subvector is smaller than a vector register, then the insertion 4777 // must preserve the undisturbed elements of the register. We do this by 4778 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 4779 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 4780 // subvector within the vector register, and an INSERT_SUBVECTOR of that 4781 // LMUL=1 type back into the larger vector (resolving to another subregister 4782 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 4783 // to avoid allocating a large register group to hold our subvector. 4784 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 4785 return Op; 4786 4787 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 4788 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 4789 // (in our case undisturbed). This means we can set up a subvector insertion 4790 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 4791 // size of the subvector. 4792 MVT InterSubVT = VecVT; 4793 SDValue AlignedExtract = Vec; 4794 unsigned AlignedIdx = OrigIdx - RemIdx; 4795 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4796 InterSubVT = getLMUL1VT(VecVT); 4797 // Extract a subvector equal to the nearest full vector register type. This 4798 // should resolve to a EXTRACT_SUBREG instruction. 4799 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4800 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4801 } 4802 4803 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4804 // For scalable vectors this must be further multiplied by vscale. 4805 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 4806 4807 SDValue Mask, VL; 4808 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 4809 4810 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 4811 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 4812 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 4813 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 4814 4815 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 4816 DAG.getUNDEF(InterSubVT), SubVec, 4817 DAG.getConstant(0, DL, XLenVT)); 4818 4819 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 4820 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 4821 4822 // If required, insert this subvector back into the correct vector register. 4823 // This should resolve to an INSERT_SUBREG instruction. 4824 if (VecVT.bitsGT(InterSubVT)) 4825 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 4826 DAG.getConstant(AlignedIdx, DL, XLenVT)); 4827 4828 // We might have bitcast from a mask type: cast back to the original type if 4829 // required. 4830 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 4831 } 4832 4833 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 4834 SelectionDAG &DAG) const { 4835 SDValue Vec = Op.getOperand(0); 4836 MVT SubVecVT = Op.getSimpleValueType(); 4837 MVT VecVT = Vec.getSimpleValueType(); 4838 4839 SDLoc DL(Op); 4840 MVT XLenVT = Subtarget.getXLenVT(); 4841 unsigned OrigIdx = Op.getConstantOperandVal(1); 4842 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4843 4844 // We don't have the ability to slide mask vectors down indexed by their i1 4845 // elements; the smallest we can do is i8. Often we are able to bitcast to 4846 // equivalent i8 vectors. Note that when extracting a fixed-length vector 4847 // from a scalable one, we might not necessarily have enough scalable 4848 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 4849 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 4850 if (VecVT.getVectorMinNumElements() >= 8 && 4851 SubVecVT.getVectorMinNumElements() >= 8) { 4852 assert(OrigIdx % 8 == 0 && "Invalid index"); 4853 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4854 SubVecVT.getVectorMinNumElements() % 8 == 0 && 4855 "Unexpected mask vector lowering"); 4856 OrigIdx /= 8; 4857 SubVecVT = 4858 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 4859 SubVecVT.isScalableVector()); 4860 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 4861 VecVT.isScalableVector()); 4862 Vec = DAG.getBitcast(VecVT, Vec); 4863 } else { 4864 // We can't slide this mask vector down, indexed by its i1 elements. 4865 // This poses a problem when we wish to extract a scalable vector which 4866 // can't be re-expressed as a larger type. Just choose the slow path and 4867 // extend to a larger type, then truncate back down. 4868 // TODO: We could probably improve this when extracting certain fixed 4869 // from fixed, where we can extract as i8 and shift the correct element 4870 // right to reach the desired subvector? 4871 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 4872 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 4873 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 4874 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 4875 Op.getOperand(1)); 4876 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 4877 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 4878 } 4879 } 4880 4881 // If the subvector vector is a fixed-length type, we cannot use subregister 4882 // manipulation to simplify the codegen; we don't know which register of a 4883 // LMUL group contains the specific subvector as we only know the minimum 4884 // register size. Therefore we must slide the vector group down the full 4885 // amount. 4886 if (SubVecVT.isFixedLengthVector()) { 4887 // With an index of 0 this is a cast-like subvector, which can be performed 4888 // with subregister operations. 4889 if (OrigIdx == 0) 4890 return Op; 4891 MVT ContainerVT = VecVT; 4892 if (VecVT.isFixedLengthVector()) { 4893 ContainerVT = getContainerForFixedLengthVector(VecVT); 4894 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4895 } 4896 SDValue Mask = 4897 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 4898 // Set the vector length to only the number of elements we care about. This 4899 // avoids sliding down elements we're going to discard straight away. 4900 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 4901 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 4902 SDValue Slidedown = 4903 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4904 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 4905 // Now we can use a cast-like subvector extract to get the result. 4906 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4907 DAG.getConstant(0, DL, XLenVT)); 4908 return DAG.getBitcast(Op.getValueType(), Slidedown); 4909 } 4910 4911 unsigned SubRegIdx, RemIdx; 4912 std::tie(SubRegIdx, RemIdx) = 4913 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 4914 VecVT, SubVecVT, OrigIdx, TRI); 4915 4916 // If the Idx has been completely eliminated then this is a subvector extract 4917 // which naturally aligns to a vector register. These can easily be handled 4918 // using subregister manipulation. 4919 if (RemIdx == 0) 4920 return Op; 4921 4922 // Else we must shift our vector register directly to extract the subvector. 4923 // Do this using VSLIDEDOWN. 4924 4925 // If the vector type is an LMUL-group type, extract a subvector equal to the 4926 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 4927 // instruction. 4928 MVT InterSubVT = VecVT; 4929 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 4930 InterSubVT = getLMUL1VT(VecVT); 4931 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 4932 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 4933 } 4934 4935 // Slide this vector register down by the desired number of elements in order 4936 // to place the desired subvector starting at element 0. 4937 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 4938 // For scalable vectors this must be further multiplied by vscale. 4939 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 4940 4941 SDValue Mask, VL; 4942 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 4943 SDValue Slidedown = 4944 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 4945 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 4946 4947 // Now the vector is in the right position, extract our final subvector. This 4948 // should resolve to a COPY. 4949 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 4950 DAG.getConstant(0, DL, XLenVT)); 4951 4952 // We might have bitcast from a mask type: cast back to the original type if 4953 // required. 4954 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 4955 } 4956 4957 // Lower step_vector to the vid instruction. Any non-identity step value must 4958 // be accounted for my manual expansion. 4959 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 4960 SelectionDAG &DAG) const { 4961 SDLoc DL(Op); 4962 MVT VT = Op.getSimpleValueType(); 4963 MVT XLenVT = Subtarget.getXLenVT(); 4964 SDValue Mask, VL; 4965 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 4966 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4967 uint64_t StepValImm = Op.getConstantOperandVal(0); 4968 if (StepValImm != 1) { 4969 if (isPowerOf2_64(StepValImm)) { 4970 SDValue StepVal = 4971 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4972 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 4973 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 4974 } else { 4975 SDValue StepVal = lowerScalarSplat( 4976 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 4977 DL, DAG, Subtarget); 4978 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 4979 } 4980 } 4981 return StepVec; 4982 } 4983 4984 // Implement vector_reverse using vrgather.vv with indices determined by 4985 // subtracting the id of each element from (VLMAX-1). This will convert 4986 // the indices like so: 4987 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 4988 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 4989 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 4990 SelectionDAG &DAG) const { 4991 SDLoc DL(Op); 4992 MVT VecVT = Op.getSimpleValueType(); 4993 unsigned EltSize = VecVT.getScalarSizeInBits(); 4994 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 4995 4996 unsigned MaxVLMAX = 0; 4997 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 4998 if (VectorBitsMax != 0) 4999 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5000 5001 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5002 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5003 5004 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5005 // to use vrgatherei16.vv. 5006 // TODO: It's also possible to use vrgatherei16.vv for other types to 5007 // decrease register width for the index calculation. 5008 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5009 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5010 // Reverse each half, then reassemble them in reverse order. 5011 // NOTE: It's also possible that after splitting that VLMAX no longer 5012 // requires vrgatherei16.vv. 5013 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5014 SDValue Lo, Hi; 5015 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5016 EVT LoVT, HiVT; 5017 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5018 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5019 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5020 // Reassemble the low and high pieces reversed. 5021 // FIXME: This is a CONCAT_VECTORS. 5022 SDValue Res = 5023 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5024 DAG.getIntPtrConstant(0, DL)); 5025 return DAG.getNode( 5026 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5027 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5028 } 5029 5030 // Just promote the int type to i16 which will double the LMUL. 5031 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5032 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5033 } 5034 5035 MVT XLenVT = Subtarget.getXLenVT(); 5036 SDValue Mask, VL; 5037 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5038 5039 // Calculate VLMAX-1 for the desired SEW. 5040 unsigned MinElts = VecVT.getVectorMinNumElements(); 5041 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5042 DAG.getConstant(MinElts, DL, XLenVT)); 5043 SDValue VLMinus1 = 5044 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5045 5046 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5047 bool IsRV32E64 = 5048 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5049 SDValue SplatVL; 5050 if (!IsRV32E64) 5051 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5052 else 5053 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 5054 5055 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5056 SDValue Indices = 5057 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5058 5059 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5060 } 5061 5062 SDValue 5063 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5064 SelectionDAG &DAG) const { 5065 SDLoc DL(Op); 5066 auto *Load = cast<LoadSDNode>(Op); 5067 5068 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5069 Load->getMemoryVT(), 5070 *Load->getMemOperand()) && 5071 "Expecting a correctly-aligned load"); 5072 5073 MVT VT = Op.getSimpleValueType(); 5074 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5075 5076 SDValue VL = 5077 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5078 5079 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5080 SDValue NewLoad = DAG.getMemIntrinsicNode( 5081 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5082 Load->getMemoryVT(), Load->getMemOperand()); 5083 5084 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5085 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5086 } 5087 5088 SDValue 5089 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5090 SelectionDAG &DAG) const { 5091 SDLoc DL(Op); 5092 auto *Store = cast<StoreSDNode>(Op); 5093 5094 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5095 Store->getMemoryVT(), 5096 *Store->getMemOperand()) && 5097 "Expecting a correctly-aligned store"); 5098 5099 SDValue StoreVal = Store->getValue(); 5100 MVT VT = StoreVal.getSimpleValueType(); 5101 5102 // If the size less than a byte, we need to pad with zeros to make a byte. 5103 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5104 VT = MVT::v8i1; 5105 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5106 DAG.getConstant(0, DL, VT), StoreVal, 5107 DAG.getIntPtrConstant(0, DL)); 5108 } 5109 5110 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5111 5112 SDValue VL = 5113 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5114 5115 SDValue NewValue = 5116 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5117 return DAG.getMemIntrinsicNode( 5118 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5119 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5120 Store->getMemoryVT(), Store->getMemOperand()); 5121 } 5122 5123 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5124 SelectionDAG &DAG) const { 5125 SDLoc DL(Op); 5126 MVT VT = Op.getSimpleValueType(); 5127 5128 const auto *MemSD = cast<MemSDNode>(Op); 5129 EVT MemVT = MemSD->getMemoryVT(); 5130 MachineMemOperand *MMO = MemSD->getMemOperand(); 5131 SDValue Chain = MemSD->getChain(); 5132 SDValue BasePtr = MemSD->getBasePtr(); 5133 5134 SDValue Mask, PassThru, VL; 5135 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5136 Mask = VPLoad->getMask(); 5137 PassThru = DAG.getUNDEF(VT); 5138 VL = VPLoad->getVectorLength(); 5139 } else { 5140 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5141 Mask = MLoad->getMask(); 5142 PassThru = MLoad->getPassThru(); 5143 } 5144 5145 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5146 5147 MVT XLenVT = Subtarget.getXLenVT(); 5148 5149 MVT ContainerVT = VT; 5150 if (VT.isFixedLengthVector()) { 5151 ContainerVT = getContainerForFixedLengthVector(VT); 5152 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5153 if (!IsUnmasked) { 5154 MVT MaskVT = 5155 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5156 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5157 } 5158 } 5159 5160 if (!VL) 5161 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5162 5163 unsigned IntID = 5164 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5165 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5166 if (!IsUnmasked) 5167 Ops.push_back(PassThru); 5168 Ops.push_back(BasePtr); 5169 if (!IsUnmasked) 5170 Ops.push_back(Mask); 5171 Ops.push_back(VL); 5172 if (!IsUnmasked) 5173 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5174 5175 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5176 5177 SDValue Result = 5178 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5179 Chain = Result.getValue(1); 5180 5181 if (VT.isFixedLengthVector()) 5182 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5183 5184 return DAG.getMergeValues({Result, Chain}, DL); 5185 } 5186 5187 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5188 SelectionDAG &DAG) const { 5189 SDLoc DL(Op); 5190 5191 const auto *MemSD = cast<MemSDNode>(Op); 5192 EVT MemVT = MemSD->getMemoryVT(); 5193 MachineMemOperand *MMO = MemSD->getMemOperand(); 5194 SDValue Chain = MemSD->getChain(); 5195 SDValue BasePtr = MemSD->getBasePtr(); 5196 SDValue Val, Mask, VL; 5197 5198 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5199 Val = VPStore->getValue(); 5200 Mask = VPStore->getMask(); 5201 VL = VPStore->getVectorLength(); 5202 } else { 5203 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5204 Val = MStore->getValue(); 5205 Mask = MStore->getMask(); 5206 } 5207 5208 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5209 5210 MVT VT = Val.getSimpleValueType(); 5211 MVT XLenVT = Subtarget.getXLenVT(); 5212 5213 MVT ContainerVT = VT; 5214 if (VT.isFixedLengthVector()) { 5215 ContainerVT = getContainerForFixedLengthVector(VT); 5216 5217 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5218 if (!IsUnmasked) { 5219 MVT MaskVT = 5220 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5221 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5222 } 5223 } 5224 5225 if (!VL) 5226 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5227 5228 unsigned IntID = 5229 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5230 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5231 Ops.push_back(Val); 5232 Ops.push_back(BasePtr); 5233 if (!IsUnmasked) 5234 Ops.push_back(Mask); 5235 Ops.push_back(VL); 5236 5237 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5238 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5239 } 5240 5241 SDValue 5242 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5243 SelectionDAG &DAG) const { 5244 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5245 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5246 5247 MVT VT = Op.getSimpleValueType(); 5248 5249 SDValue Op1 = 5250 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5251 SDValue Op2 = 5252 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5253 5254 SDLoc DL(Op); 5255 SDValue VL = 5256 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5257 5258 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5259 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5260 5261 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5262 Op.getOperand(2), Mask, VL); 5263 5264 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5265 } 5266 5267 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5268 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5269 MVT VT = Op.getSimpleValueType(); 5270 5271 if (VT.getVectorElementType() == MVT::i1) 5272 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5273 5274 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5275 } 5276 5277 SDValue 5278 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5279 SelectionDAG &DAG) const { 5280 unsigned Opc; 5281 switch (Op.getOpcode()) { 5282 default: llvm_unreachable("Unexpected opcode!"); 5283 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5284 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5285 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5286 } 5287 5288 return lowerToScalableOp(Op, DAG, Opc); 5289 } 5290 5291 // Lower vector ABS to smax(X, sub(0, X)). 5292 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5293 SDLoc DL(Op); 5294 MVT VT = Op.getSimpleValueType(); 5295 SDValue X = Op.getOperand(0); 5296 5297 assert(VT.isFixedLengthVector() && "Unexpected type"); 5298 5299 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5300 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5301 5302 SDValue Mask, VL; 5303 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5304 5305 SDValue SplatZero = 5306 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5307 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5308 SDValue NegX = 5309 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5310 SDValue Max = 5311 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5312 5313 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5314 } 5315 5316 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5317 SDValue Op, SelectionDAG &DAG) const { 5318 SDLoc DL(Op); 5319 MVT VT = Op.getSimpleValueType(); 5320 SDValue Mag = Op.getOperand(0); 5321 SDValue Sign = Op.getOperand(1); 5322 assert(Mag.getValueType() == Sign.getValueType() && 5323 "Can only handle COPYSIGN with matching types."); 5324 5325 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5326 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5327 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5328 5329 SDValue Mask, VL; 5330 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5331 5332 SDValue CopySign = 5333 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5334 5335 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5336 } 5337 5338 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5339 SDValue Op, SelectionDAG &DAG) const { 5340 MVT VT = Op.getSimpleValueType(); 5341 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5342 5343 MVT I1ContainerVT = 5344 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5345 5346 SDValue CC = 5347 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5348 SDValue Op1 = 5349 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5350 SDValue Op2 = 5351 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5352 5353 SDLoc DL(Op); 5354 SDValue Mask, VL; 5355 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5356 5357 SDValue Select = 5358 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5359 5360 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5361 } 5362 5363 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5364 unsigned NewOpc, 5365 bool HasMask) const { 5366 MVT VT = Op.getSimpleValueType(); 5367 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5368 5369 // Create list of operands by converting existing ones to scalable types. 5370 SmallVector<SDValue, 6> Ops; 5371 for (const SDValue &V : Op->op_values()) { 5372 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5373 5374 // Pass through non-vector operands. 5375 if (!V.getValueType().isVector()) { 5376 Ops.push_back(V); 5377 continue; 5378 } 5379 5380 // "cast" fixed length vector to a scalable vector. 5381 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5382 "Only fixed length vectors are supported!"); 5383 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5384 } 5385 5386 SDLoc DL(Op); 5387 SDValue Mask, VL; 5388 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5389 if (HasMask) 5390 Ops.push_back(Mask); 5391 Ops.push_back(VL); 5392 5393 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5394 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5395 } 5396 5397 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5398 // * Operands of each node are assumed to be in the same order. 5399 // * The EVL operand is promoted from i32 to i64 on RV64. 5400 // * Fixed-length vectors are converted to their scalable-vector container 5401 // types. 5402 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5403 unsigned RISCVISDOpc) const { 5404 SDLoc DL(Op); 5405 MVT VT = Op.getSimpleValueType(); 5406 SmallVector<SDValue, 4> Ops; 5407 5408 for (const auto &OpIdx : enumerate(Op->ops())) { 5409 SDValue V = OpIdx.value(); 5410 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5411 // Pass through operands which aren't fixed-length vectors. 5412 if (!V.getValueType().isFixedLengthVector()) { 5413 Ops.push_back(V); 5414 continue; 5415 } 5416 // "cast" fixed length vector to a scalable vector. 5417 MVT OpVT = V.getSimpleValueType(); 5418 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5419 assert(useRVVForFixedLengthVectorVT(OpVT) && 5420 "Only fixed length vectors are supported!"); 5421 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5422 } 5423 5424 if (!VT.isFixedLengthVector()) 5425 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5426 5427 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5428 5429 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5430 5431 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5432 } 5433 5434 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 5435 unsigned MaskOpc, 5436 unsigned VecOpc) const { 5437 MVT VT = Op.getSimpleValueType(); 5438 if (VT.getVectorElementType() != MVT::i1) 5439 return lowerVPOp(Op, DAG, VecOpc); 5440 5441 // It is safe to drop mask parameter as masked-off elements are undef. 5442 SDValue Op1 = Op->getOperand(0); 5443 SDValue Op2 = Op->getOperand(1); 5444 SDValue VL = Op->getOperand(3); 5445 5446 MVT ContainerVT = VT; 5447 const bool IsFixed = VT.isFixedLengthVector(); 5448 if (IsFixed) { 5449 ContainerVT = getContainerForFixedLengthVector(VT); 5450 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 5451 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 5452 } 5453 5454 SDLoc DL(Op); 5455 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 5456 if (!IsFixed) 5457 return Val; 5458 return convertFromScalableVector(VT, Val, DAG, Subtarget); 5459 } 5460 5461 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5462 // matched to a RVV indexed load. The RVV indexed load instructions only 5463 // support the "unsigned unscaled" addressing mode; indices are implicitly 5464 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5465 // signed or scaled indexing is extended to the XLEN value type and scaled 5466 // accordingly. 5467 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5468 SelectionDAG &DAG) const { 5469 SDLoc DL(Op); 5470 MVT VT = Op.getSimpleValueType(); 5471 5472 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5473 EVT MemVT = MemSD->getMemoryVT(); 5474 MachineMemOperand *MMO = MemSD->getMemOperand(); 5475 SDValue Chain = MemSD->getChain(); 5476 SDValue BasePtr = MemSD->getBasePtr(); 5477 5478 ISD::LoadExtType LoadExtType; 5479 SDValue Index, Mask, PassThru, VL; 5480 5481 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5482 Index = VPGN->getIndex(); 5483 Mask = VPGN->getMask(); 5484 PassThru = DAG.getUNDEF(VT); 5485 VL = VPGN->getVectorLength(); 5486 // VP doesn't support extending loads. 5487 LoadExtType = ISD::NON_EXTLOAD; 5488 } else { 5489 // Else it must be a MGATHER. 5490 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5491 Index = MGN->getIndex(); 5492 Mask = MGN->getMask(); 5493 PassThru = MGN->getPassThru(); 5494 LoadExtType = MGN->getExtensionType(); 5495 } 5496 5497 MVT IndexVT = Index.getSimpleValueType(); 5498 MVT XLenVT = Subtarget.getXLenVT(); 5499 5500 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5501 "Unexpected VTs!"); 5502 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5503 // Targets have to explicitly opt-in for extending vector loads. 5504 assert(LoadExtType == ISD::NON_EXTLOAD && 5505 "Unexpected extending MGATHER/VP_GATHER"); 5506 (void)LoadExtType; 5507 5508 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5509 // the selection of the masked intrinsics doesn't do this for us. 5510 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5511 5512 MVT ContainerVT = VT; 5513 if (VT.isFixedLengthVector()) { 5514 // We need to use the larger of the result and index type to determine the 5515 // scalable type to use so we don't increase LMUL for any operand/result. 5516 if (VT.bitsGE(IndexVT)) { 5517 ContainerVT = getContainerForFixedLengthVector(VT); 5518 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5519 ContainerVT.getVectorElementCount()); 5520 } else { 5521 IndexVT = getContainerForFixedLengthVector(IndexVT); 5522 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5523 IndexVT.getVectorElementCount()); 5524 } 5525 5526 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5527 5528 if (!IsUnmasked) { 5529 MVT MaskVT = 5530 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5531 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5532 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5533 } 5534 } 5535 5536 if (!VL) 5537 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5538 5539 unsigned IntID = 5540 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5541 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5542 if (!IsUnmasked) 5543 Ops.push_back(PassThru); 5544 Ops.push_back(BasePtr); 5545 Ops.push_back(Index); 5546 if (!IsUnmasked) 5547 Ops.push_back(Mask); 5548 Ops.push_back(VL); 5549 if (!IsUnmasked) 5550 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5551 5552 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5553 SDValue Result = 5554 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5555 Chain = Result.getValue(1); 5556 5557 if (VT.isFixedLengthVector()) 5558 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5559 5560 return DAG.getMergeValues({Result, Chain}, DL); 5561 } 5562 5563 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5564 // matched to a RVV indexed store. The RVV indexed store instructions only 5565 // support the "unsigned unscaled" addressing mode; indices are implicitly 5566 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5567 // signed or scaled indexing is extended to the XLEN value type and scaled 5568 // accordingly. 5569 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5570 SelectionDAG &DAG) const { 5571 SDLoc DL(Op); 5572 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5573 EVT MemVT = MemSD->getMemoryVT(); 5574 MachineMemOperand *MMO = MemSD->getMemOperand(); 5575 SDValue Chain = MemSD->getChain(); 5576 SDValue BasePtr = MemSD->getBasePtr(); 5577 5578 bool IsTruncatingStore = false; 5579 SDValue Index, Mask, Val, VL; 5580 5581 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5582 Index = VPSN->getIndex(); 5583 Mask = VPSN->getMask(); 5584 Val = VPSN->getValue(); 5585 VL = VPSN->getVectorLength(); 5586 // VP doesn't support truncating stores. 5587 IsTruncatingStore = false; 5588 } else { 5589 // Else it must be a MSCATTER. 5590 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5591 Index = MSN->getIndex(); 5592 Mask = MSN->getMask(); 5593 Val = MSN->getValue(); 5594 IsTruncatingStore = MSN->isTruncatingStore(); 5595 } 5596 5597 MVT VT = Val.getSimpleValueType(); 5598 MVT IndexVT = Index.getSimpleValueType(); 5599 MVT XLenVT = Subtarget.getXLenVT(); 5600 5601 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5602 "Unexpected VTs!"); 5603 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5604 // Targets have to explicitly opt-in for extending vector loads and 5605 // truncating vector stores. 5606 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5607 (void)IsTruncatingStore; 5608 5609 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5610 // the selection of the masked intrinsics doesn't do this for us. 5611 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5612 5613 MVT ContainerVT = VT; 5614 if (VT.isFixedLengthVector()) { 5615 // We need to use the larger of the value and index type to determine the 5616 // scalable type to use so we don't increase LMUL for any operand/result. 5617 if (VT.bitsGE(IndexVT)) { 5618 ContainerVT = getContainerForFixedLengthVector(VT); 5619 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5620 ContainerVT.getVectorElementCount()); 5621 } else { 5622 IndexVT = getContainerForFixedLengthVector(IndexVT); 5623 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5624 IndexVT.getVectorElementCount()); 5625 } 5626 5627 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5628 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5629 5630 if (!IsUnmasked) { 5631 MVT MaskVT = 5632 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5633 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5634 } 5635 } 5636 5637 if (!VL) 5638 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5639 5640 unsigned IntID = 5641 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5642 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5643 Ops.push_back(Val); 5644 Ops.push_back(BasePtr); 5645 Ops.push_back(Index); 5646 if (!IsUnmasked) 5647 Ops.push_back(Mask); 5648 Ops.push_back(VL); 5649 5650 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5651 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5652 } 5653 5654 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5655 SelectionDAG &DAG) const { 5656 const MVT XLenVT = Subtarget.getXLenVT(); 5657 SDLoc DL(Op); 5658 SDValue Chain = Op->getOperand(0); 5659 SDValue SysRegNo = DAG.getTargetConstant( 5660 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5661 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5662 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5663 5664 // Encoding used for rounding mode in RISCV differs from that used in 5665 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5666 // table, which consists of a sequence of 4-bit fields, each representing 5667 // corresponding FLT_ROUNDS mode. 5668 static const int Table = 5669 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5670 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5671 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5672 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5673 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5674 5675 SDValue Shift = 5676 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5677 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5678 DAG.getConstant(Table, DL, XLenVT), Shift); 5679 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5680 DAG.getConstant(7, DL, XLenVT)); 5681 5682 return DAG.getMergeValues({Masked, Chain}, DL); 5683 } 5684 5685 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 5686 SelectionDAG &DAG) const { 5687 const MVT XLenVT = Subtarget.getXLenVT(); 5688 SDLoc DL(Op); 5689 SDValue Chain = Op->getOperand(0); 5690 SDValue RMValue = Op->getOperand(1); 5691 SDValue SysRegNo = DAG.getTargetConstant( 5692 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5693 5694 // Encoding used for rounding mode in RISCV differs from that used in 5695 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 5696 // a table, which consists of a sequence of 4-bit fields, each representing 5697 // corresponding RISCV mode. 5698 static const unsigned Table = 5699 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 5700 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 5701 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 5702 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 5703 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 5704 5705 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 5706 DAG.getConstant(2, DL, XLenVT)); 5707 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5708 DAG.getConstant(Table, DL, XLenVT), Shift); 5709 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5710 DAG.getConstant(0x7, DL, XLenVT)); 5711 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 5712 RMValue); 5713 } 5714 5715 // Returns the opcode of the target-specific SDNode that implements the 32-bit 5716 // form of the given Opcode. 5717 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 5718 switch (Opcode) { 5719 default: 5720 llvm_unreachable("Unexpected opcode"); 5721 case ISD::SHL: 5722 return RISCVISD::SLLW; 5723 case ISD::SRA: 5724 return RISCVISD::SRAW; 5725 case ISD::SRL: 5726 return RISCVISD::SRLW; 5727 case ISD::SDIV: 5728 return RISCVISD::DIVW; 5729 case ISD::UDIV: 5730 return RISCVISD::DIVUW; 5731 case ISD::UREM: 5732 return RISCVISD::REMUW; 5733 case ISD::ROTL: 5734 return RISCVISD::ROLW; 5735 case ISD::ROTR: 5736 return RISCVISD::RORW; 5737 case RISCVISD::GREV: 5738 return RISCVISD::GREVW; 5739 case RISCVISD::GORC: 5740 return RISCVISD::GORCW; 5741 } 5742 } 5743 5744 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 5745 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 5746 // otherwise be promoted to i64, making it difficult to select the 5747 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 5748 // type i8/i16/i32 is lost. 5749 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 5750 unsigned ExtOpc = ISD::ANY_EXTEND) { 5751 SDLoc DL(N); 5752 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 5753 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 5754 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 5755 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 5756 // ReplaceNodeResults requires we maintain the same type for the return value. 5757 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 5758 } 5759 5760 // Converts the given 32-bit operation to a i64 operation with signed extension 5761 // semantic to reduce the signed extension instructions. 5762 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 5763 SDLoc DL(N); 5764 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5765 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5766 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 5767 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5768 DAG.getValueType(MVT::i32)); 5769 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 5770 } 5771 5772 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 5773 SmallVectorImpl<SDValue> &Results, 5774 SelectionDAG &DAG) const { 5775 SDLoc DL(N); 5776 switch (N->getOpcode()) { 5777 default: 5778 llvm_unreachable("Don't know how to custom type legalize this operation!"); 5779 case ISD::STRICT_FP_TO_SINT: 5780 case ISD::STRICT_FP_TO_UINT: 5781 case ISD::FP_TO_SINT: 5782 case ISD::FP_TO_UINT: { 5783 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5784 "Unexpected custom legalisation"); 5785 bool IsStrict = N->isStrictFPOpcode(); 5786 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 5787 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 5788 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 5789 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 5790 TargetLowering::TypeSoftenFloat) { 5791 if (!isTypeLegal(Op0.getValueType())) 5792 return; 5793 if (IsStrict) { 5794 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RTZ_RV64 5795 : RISCVISD::STRICT_FCVT_WU_RTZ_RV64; 5796 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 5797 SDValue Res = DAG.getNode(Opc, DL, VTs, N->getOperand(0), Op0); 5798 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5799 Results.push_back(Res.getValue(1)); 5800 return; 5801 } 5802 unsigned Opc = 5803 IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64; 5804 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0); 5805 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5806 return; 5807 } 5808 // If the FP type needs to be softened, emit a library call using the 'si' 5809 // version. If we left it to default legalization we'd end up with 'di'. If 5810 // the FP type doesn't need to be softened just let generic type 5811 // legalization promote the result type. 5812 RTLIB::Libcall LC; 5813 if (IsSigned) 5814 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 5815 else 5816 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 5817 MakeLibCallOptions CallOptions; 5818 EVT OpVT = Op0.getValueType(); 5819 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 5820 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 5821 SDValue Result; 5822 std::tie(Result, Chain) = 5823 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 5824 Results.push_back(Result); 5825 if (IsStrict) 5826 Results.push_back(Chain); 5827 break; 5828 } 5829 case ISD::READCYCLECOUNTER: { 5830 assert(!Subtarget.is64Bit() && 5831 "READCYCLECOUNTER only has custom type legalization on riscv32"); 5832 5833 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 5834 SDValue RCW = 5835 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 5836 5837 Results.push_back( 5838 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 5839 Results.push_back(RCW.getValue(2)); 5840 break; 5841 } 5842 case ISD::MUL: { 5843 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 5844 unsigned XLen = Subtarget.getXLen(); 5845 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 5846 if (Size > XLen) { 5847 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 5848 SDValue LHS = N->getOperand(0); 5849 SDValue RHS = N->getOperand(1); 5850 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 5851 5852 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 5853 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 5854 // We need exactly one side to be unsigned. 5855 if (LHSIsU == RHSIsU) 5856 return; 5857 5858 auto MakeMULPair = [&](SDValue S, SDValue U) { 5859 MVT XLenVT = Subtarget.getXLenVT(); 5860 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 5861 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 5862 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 5863 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 5864 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 5865 }; 5866 5867 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 5868 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 5869 5870 // The other operand should be signed, but still prefer MULH when 5871 // possible. 5872 if (RHSIsU && LHSIsS && !RHSIsS) 5873 Results.push_back(MakeMULPair(LHS, RHS)); 5874 else if (LHSIsU && RHSIsS && !LHSIsS) 5875 Results.push_back(MakeMULPair(RHS, LHS)); 5876 5877 return; 5878 } 5879 LLVM_FALLTHROUGH; 5880 } 5881 case ISD::ADD: 5882 case ISD::SUB: 5883 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5884 "Unexpected custom legalisation"); 5885 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 5886 break; 5887 case ISD::SHL: 5888 case ISD::SRA: 5889 case ISD::SRL: 5890 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5891 "Unexpected custom legalisation"); 5892 if (N->getOperand(1).getOpcode() != ISD::Constant) { 5893 Results.push_back(customLegalizeToWOp(N, DAG)); 5894 break; 5895 } 5896 5897 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 5898 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 5899 // shift amount. 5900 if (N->getOpcode() == ISD::SHL) { 5901 SDLoc DL(N); 5902 SDValue NewOp0 = 5903 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5904 SDValue NewOp1 = 5905 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 5906 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 5907 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 5908 DAG.getValueType(MVT::i32)); 5909 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 5910 } 5911 5912 break; 5913 case ISD::ROTL: 5914 case ISD::ROTR: 5915 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5916 "Unexpected custom legalisation"); 5917 Results.push_back(customLegalizeToWOp(N, DAG)); 5918 break; 5919 case ISD::CTTZ: 5920 case ISD::CTTZ_ZERO_UNDEF: 5921 case ISD::CTLZ: 5922 case ISD::CTLZ_ZERO_UNDEF: { 5923 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5924 "Unexpected custom legalisation"); 5925 5926 SDValue NewOp0 = 5927 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5928 bool IsCTZ = 5929 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 5930 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 5931 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 5932 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5933 return; 5934 } 5935 case ISD::SDIV: 5936 case ISD::UDIV: 5937 case ISD::UREM: { 5938 MVT VT = N->getSimpleValueType(0); 5939 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 5940 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 5941 "Unexpected custom legalisation"); 5942 // Don't promote division/remainder by constant since we should expand those 5943 // to multiply by magic constant. 5944 // FIXME: What if the expansion is disabled for minsize. 5945 if (N->getOperand(1).getOpcode() == ISD::Constant) 5946 return; 5947 5948 // If the input is i32, use ANY_EXTEND since the W instructions don't read 5949 // the upper 32 bits. For other types we need to sign or zero extend 5950 // based on the opcode. 5951 unsigned ExtOpc = ISD::ANY_EXTEND; 5952 if (VT != MVT::i32) 5953 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 5954 : ISD::ZERO_EXTEND; 5955 5956 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 5957 break; 5958 } 5959 case ISD::UADDO: 5960 case ISD::USUBO: { 5961 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5962 "Unexpected custom legalisation"); 5963 bool IsAdd = N->getOpcode() == ISD::UADDO; 5964 // Create an ADDW or SUBW. 5965 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 5966 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 5967 SDValue Res = 5968 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 5969 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 5970 DAG.getValueType(MVT::i32)); 5971 5972 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 5973 // Since the inputs are sign extended from i32, this is equivalent to 5974 // comparing the lower 32 bits. 5975 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5976 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 5977 IsAdd ? ISD::SETULT : ISD::SETUGT); 5978 5979 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5980 Results.push_back(Overflow); 5981 return; 5982 } 5983 case ISD::UADDSAT: 5984 case ISD::USUBSAT: { 5985 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 5986 "Unexpected custom legalisation"); 5987 if (Subtarget.hasStdExtZbb()) { 5988 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 5989 // sign extend allows overflow of the lower 32 bits to be detected on 5990 // the promoted size. 5991 SDValue LHS = 5992 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 5993 SDValue RHS = 5994 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 5995 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 5996 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 5997 return; 5998 } 5999 6000 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6001 // promotion for UADDO/USUBO. 6002 Results.push_back(expandAddSubSat(N, DAG)); 6003 return; 6004 } 6005 case ISD::BITCAST: { 6006 EVT VT = N->getValueType(0); 6007 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6008 SDValue Op0 = N->getOperand(0); 6009 EVT Op0VT = Op0.getValueType(); 6010 MVT XLenVT = Subtarget.getXLenVT(); 6011 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6012 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6013 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6014 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6015 Subtarget.hasStdExtF()) { 6016 SDValue FPConv = 6017 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6018 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6019 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6020 isTypeLegal(Op0VT)) { 6021 // Custom-legalize bitcasts from fixed-length vector types to illegal 6022 // scalar types in order to improve codegen. Bitcast the vector to a 6023 // one-element vector type whose element type is the same as the result 6024 // type, and extract the first element. 6025 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6026 if (isTypeLegal(BVT)) { 6027 SDValue BVec = DAG.getBitcast(BVT, Op0); 6028 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6029 DAG.getConstant(0, DL, XLenVT))); 6030 } 6031 } 6032 break; 6033 } 6034 case RISCVISD::GREV: 6035 case RISCVISD::GORC: { 6036 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6037 "Unexpected custom legalisation"); 6038 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6039 // This is similar to customLegalizeToWOp, except that we pass the second 6040 // operand (a TargetConstant) straight through: it is already of type 6041 // XLenVT. 6042 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6043 SDValue NewOp0 = 6044 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6045 SDValue NewOp1 = 6046 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6047 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6048 // ReplaceNodeResults requires we maintain the same type for the return 6049 // value. 6050 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6051 break; 6052 } 6053 case RISCVISD::SHFL: { 6054 // There is no SHFLIW instruction, but we can just promote the operation. 6055 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6056 "Unexpected custom legalisation"); 6057 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6058 SDValue NewOp0 = 6059 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6060 SDValue NewOp1 = 6061 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6062 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6063 // ReplaceNodeResults requires we maintain the same type for the return 6064 // value. 6065 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6066 break; 6067 } 6068 case ISD::BSWAP: 6069 case ISD::BITREVERSE: { 6070 MVT VT = N->getSimpleValueType(0); 6071 MVT XLenVT = Subtarget.getXLenVT(); 6072 assert((VT == MVT::i8 || VT == MVT::i16 || 6073 (VT == MVT::i32 && Subtarget.is64Bit())) && 6074 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6075 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6076 unsigned Imm = VT.getSizeInBits() - 1; 6077 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6078 if (N->getOpcode() == ISD::BSWAP) 6079 Imm &= ~0x7U; 6080 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6081 SDValue GREVI = 6082 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6083 // ReplaceNodeResults requires we maintain the same type for the return 6084 // value. 6085 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6086 break; 6087 } 6088 case ISD::FSHL: 6089 case ISD::FSHR: { 6090 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6091 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6092 SDValue NewOp0 = 6093 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6094 SDValue NewOp1 = 6095 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6096 SDValue NewOp2 = 6097 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6098 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6099 // Mask the shift amount to 5 bits. 6100 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6101 DAG.getConstant(0x1f, DL, MVT::i64)); 6102 unsigned Opc = 6103 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 6104 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 6105 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6106 break; 6107 } 6108 case ISD::EXTRACT_VECTOR_ELT: { 6109 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6110 // type is illegal (currently only vXi64 RV32). 6111 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6112 // transferred to the destination register. We issue two of these from the 6113 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6114 // first element. 6115 SDValue Vec = N->getOperand(0); 6116 SDValue Idx = N->getOperand(1); 6117 6118 // The vector type hasn't been legalized yet so we can't issue target 6119 // specific nodes if it needs legalization. 6120 // FIXME: We would manually legalize if it's important. 6121 if (!isTypeLegal(Vec.getValueType())) 6122 return; 6123 6124 MVT VecVT = Vec.getSimpleValueType(); 6125 6126 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6127 VecVT.getVectorElementType() == MVT::i64 && 6128 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6129 6130 // If this is a fixed vector, we need to convert it to a scalable vector. 6131 MVT ContainerVT = VecVT; 6132 if (VecVT.isFixedLengthVector()) { 6133 ContainerVT = getContainerForFixedLengthVector(VecVT); 6134 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6135 } 6136 6137 MVT XLenVT = Subtarget.getXLenVT(); 6138 6139 // Use a VL of 1 to avoid processing more elements than we need. 6140 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6141 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6142 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6143 6144 // Unless the index is known to be 0, we must slide the vector down to get 6145 // the desired element into index 0. 6146 if (!isNullConstant(Idx)) { 6147 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6148 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6149 } 6150 6151 // Extract the lower XLEN bits of the correct vector element. 6152 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6153 6154 // To extract the upper XLEN bits of the vector element, shift the first 6155 // element right by 32 bits and re-extract the lower XLEN bits. 6156 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6157 DAG.getConstant(32, DL, XLenVT), VL); 6158 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6159 ThirtyTwoV, Mask, VL); 6160 6161 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6162 6163 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6164 break; 6165 } 6166 case ISD::INTRINSIC_WO_CHAIN: { 6167 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6168 switch (IntNo) { 6169 default: 6170 llvm_unreachable( 6171 "Don't know how to custom type legalize this intrinsic!"); 6172 case Intrinsic::riscv_orc_b: { 6173 // Lower to the GORCI encoding for orc.b with the operand extended. 6174 SDValue NewOp = 6175 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6176 // If Zbp is enabled, use GORCIW which will sign extend the result. 6177 unsigned Opc = 6178 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6179 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6180 DAG.getConstant(7, DL, MVT::i64)); 6181 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6182 return; 6183 } 6184 case Intrinsic::riscv_grev: 6185 case Intrinsic::riscv_gorc: { 6186 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6187 "Unexpected custom legalisation"); 6188 SDValue NewOp1 = 6189 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6190 SDValue NewOp2 = 6191 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6192 unsigned Opc = 6193 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 6194 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6195 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6196 break; 6197 } 6198 case Intrinsic::riscv_shfl: 6199 case Intrinsic::riscv_unshfl: { 6200 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6201 "Unexpected custom legalisation"); 6202 SDValue NewOp1 = 6203 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6204 SDValue NewOp2 = 6205 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6206 unsigned Opc = 6207 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6208 if (isa<ConstantSDNode>(N->getOperand(2))) { 6209 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6210 DAG.getConstant(0xf, DL, MVT::i64)); 6211 Opc = 6212 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6213 } 6214 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6215 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6216 break; 6217 } 6218 case Intrinsic::riscv_bcompress: 6219 case Intrinsic::riscv_bdecompress: { 6220 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6221 "Unexpected custom legalisation"); 6222 SDValue NewOp1 = 6223 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6224 SDValue NewOp2 = 6225 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6226 unsigned Opc = IntNo == Intrinsic::riscv_bcompress 6227 ? RISCVISD::BCOMPRESSW 6228 : RISCVISD::BDECOMPRESSW; 6229 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6230 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6231 break; 6232 } 6233 case Intrinsic::riscv_vmv_x_s: { 6234 EVT VT = N->getValueType(0); 6235 MVT XLenVT = Subtarget.getXLenVT(); 6236 if (VT.bitsLT(XLenVT)) { 6237 // Simple case just extract using vmv.x.s and truncate. 6238 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6239 Subtarget.getXLenVT(), N->getOperand(1)); 6240 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6241 return; 6242 } 6243 6244 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6245 "Unexpected custom legalization"); 6246 6247 // We need to do the move in two steps. 6248 SDValue Vec = N->getOperand(1); 6249 MVT VecVT = Vec.getSimpleValueType(); 6250 6251 // First extract the lower XLEN bits of the element. 6252 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6253 6254 // To extract the upper XLEN bits of the vector element, shift the first 6255 // element right by 32 bits and re-extract the lower XLEN bits. 6256 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6257 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6258 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6259 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6260 DAG.getConstant(32, DL, XLenVT), VL); 6261 SDValue LShr32 = 6262 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6263 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6264 6265 Results.push_back( 6266 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6267 break; 6268 } 6269 } 6270 break; 6271 } 6272 case ISD::VECREDUCE_ADD: 6273 case ISD::VECREDUCE_AND: 6274 case ISD::VECREDUCE_OR: 6275 case ISD::VECREDUCE_XOR: 6276 case ISD::VECREDUCE_SMAX: 6277 case ISD::VECREDUCE_UMAX: 6278 case ISD::VECREDUCE_SMIN: 6279 case ISD::VECREDUCE_UMIN: 6280 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6281 Results.push_back(V); 6282 break; 6283 case ISD::VP_REDUCE_ADD: 6284 case ISD::VP_REDUCE_AND: 6285 case ISD::VP_REDUCE_OR: 6286 case ISD::VP_REDUCE_XOR: 6287 case ISD::VP_REDUCE_SMAX: 6288 case ISD::VP_REDUCE_UMAX: 6289 case ISD::VP_REDUCE_SMIN: 6290 case ISD::VP_REDUCE_UMIN: 6291 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6292 Results.push_back(V); 6293 break; 6294 case ISD::FLT_ROUNDS_: { 6295 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6296 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6297 Results.push_back(Res.getValue(0)); 6298 Results.push_back(Res.getValue(1)); 6299 break; 6300 } 6301 } 6302 } 6303 6304 // A structure to hold one of the bit-manipulation patterns below. Together, a 6305 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6306 // (or (and (shl x, 1), 0xAAAAAAAA), 6307 // (and (srl x, 1), 0x55555555)) 6308 struct RISCVBitmanipPat { 6309 SDValue Op; 6310 unsigned ShAmt; 6311 bool IsSHL; 6312 6313 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6314 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6315 } 6316 }; 6317 6318 // Matches patterns of the form 6319 // (and (shl x, C2), (C1 << C2)) 6320 // (and (srl x, C2), C1) 6321 // (shl (and x, C1), C2) 6322 // (srl (and x, (C1 << C2)), C2) 6323 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6324 // The expected masks for each shift amount are specified in BitmanipMasks where 6325 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6326 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6327 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6328 // XLen is 64. 6329 static Optional<RISCVBitmanipPat> 6330 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6331 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6332 "Unexpected number of masks"); 6333 Optional<uint64_t> Mask; 6334 // Optionally consume a mask around the shift operation. 6335 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6336 Mask = Op.getConstantOperandVal(1); 6337 Op = Op.getOperand(0); 6338 } 6339 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6340 return None; 6341 bool IsSHL = Op.getOpcode() == ISD::SHL; 6342 6343 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6344 return None; 6345 uint64_t ShAmt = Op.getConstantOperandVal(1); 6346 6347 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6348 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6349 return None; 6350 // If we don't have enough masks for 64 bit, then we must be trying to 6351 // match SHFL so we're only allowed to shift 1/4 of the width. 6352 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6353 return None; 6354 6355 SDValue Src = Op.getOperand(0); 6356 6357 // The expected mask is shifted left when the AND is found around SHL 6358 // patterns. 6359 // ((x >> 1) & 0x55555555) 6360 // ((x << 1) & 0xAAAAAAAA) 6361 bool SHLExpMask = IsSHL; 6362 6363 if (!Mask) { 6364 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6365 // the mask is all ones: consume that now. 6366 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6367 Mask = Src.getConstantOperandVal(1); 6368 Src = Src.getOperand(0); 6369 // The expected mask is now in fact shifted left for SRL, so reverse the 6370 // decision. 6371 // ((x & 0xAAAAAAAA) >> 1) 6372 // ((x & 0x55555555) << 1) 6373 SHLExpMask = !SHLExpMask; 6374 } else { 6375 // Use a default shifted mask of all-ones if there's no AND, truncated 6376 // down to the expected width. This simplifies the logic later on. 6377 Mask = maskTrailingOnes<uint64_t>(Width); 6378 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6379 } 6380 } 6381 6382 unsigned MaskIdx = Log2_32(ShAmt); 6383 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6384 6385 if (SHLExpMask) 6386 ExpMask <<= ShAmt; 6387 6388 if (Mask != ExpMask) 6389 return None; 6390 6391 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6392 } 6393 6394 // Matches any of the following bit-manipulation patterns: 6395 // (and (shl x, 1), (0x55555555 << 1)) 6396 // (and (srl x, 1), 0x55555555) 6397 // (shl (and x, 0x55555555), 1) 6398 // (srl (and x, (0x55555555 << 1)), 1) 6399 // where the shift amount and mask may vary thus: 6400 // [1] = 0x55555555 / 0xAAAAAAAA 6401 // [2] = 0x33333333 / 0xCCCCCCCC 6402 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6403 // [8] = 0x00FF00FF / 0xFF00FF00 6404 // [16] = 0x0000FFFF / 0xFFFFFFFF 6405 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6406 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6407 // These are the unshifted masks which we use to match bit-manipulation 6408 // patterns. They may be shifted left in certain circumstances. 6409 static const uint64_t BitmanipMasks[] = { 6410 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6411 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6412 6413 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6414 } 6415 6416 // Match the following pattern as a GREVI(W) operation 6417 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6418 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6419 const RISCVSubtarget &Subtarget) { 6420 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6421 EVT VT = Op.getValueType(); 6422 6423 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6424 auto LHS = matchGREVIPat(Op.getOperand(0)); 6425 auto RHS = matchGREVIPat(Op.getOperand(1)); 6426 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6427 SDLoc DL(Op); 6428 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6429 DAG.getConstant(LHS->ShAmt, DL, VT)); 6430 } 6431 } 6432 return SDValue(); 6433 } 6434 6435 // Matches any the following pattern as a GORCI(W) operation 6436 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6437 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6438 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6439 // Note that with the variant of 3., 6440 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6441 // the inner pattern will first be matched as GREVI and then the outer 6442 // pattern will be matched to GORC via the first rule above. 6443 // 4. (or (rotl/rotr x, bitwidth/2), x) 6444 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6445 const RISCVSubtarget &Subtarget) { 6446 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6447 EVT VT = Op.getValueType(); 6448 6449 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6450 SDLoc DL(Op); 6451 SDValue Op0 = Op.getOperand(0); 6452 SDValue Op1 = Op.getOperand(1); 6453 6454 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6455 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6456 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6457 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6458 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6459 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6460 if ((Reverse.getOpcode() == ISD::ROTL || 6461 Reverse.getOpcode() == ISD::ROTR) && 6462 Reverse.getOperand(0) == X && 6463 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6464 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6465 if (RotAmt == (VT.getSizeInBits() / 2)) 6466 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6467 DAG.getConstant(RotAmt, DL, VT)); 6468 } 6469 return SDValue(); 6470 }; 6471 6472 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6473 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6474 return V; 6475 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6476 return V; 6477 6478 // OR is commutable so canonicalize its OR operand to the left 6479 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6480 std::swap(Op0, Op1); 6481 if (Op0.getOpcode() != ISD::OR) 6482 return SDValue(); 6483 SDValue OrOp0 = Op0.getOperand(0); 6484 SDValue OrOp1 = Op0.getOperand(1); 6485 auto LHS = matchGREVIPat(OrOp0); 6486 // OR is commutable so swap the operands and try again: x might have been 6487 // on the left 6488 if (!LHS) { 6489 std::swap(OrOp0, OrOp1); 6490 LHS = matchGREVIPat(OrOp0); 6491 } 6492 auto RHS = matchGREVIPat(Op1); 6493 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6494 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6495 DAG.getConstant(LHS->ShAmt, DL, VT)); 6496 } 6497 } 6498 return SDValue(); 6499 } 6500 6501 // Matches any of the following bit-manipulation patterns: 6502 // (and (shl x, 1), (0x22222222 << 1)) 6503 // (and (srl x, 1), 0x22222222) 6504 // (shl (and x, 0x22222222), 1) 6505 // (srl (and x, (0x22222222 << 1)), 1) 6506 // where the shift amount and mask may vary thus: 6507 // [1] = 0x22222222 / 0x44444444 6508 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6509 // [4] = 0x00F000F0 / 0x0F000F00 6510 // [8] = 0x0000FF00 / 0x00FF0000 6511 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6512 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6513 // These are the unshifted masks which we use to match bit-manipulation 6514 // patterns. They may be shifted left in certain circumstances. 6515 static const uint64_t BitmanipMasks[] = { 6516 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6517 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6518 6519 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6520 } 6521 6522 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6523 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6524 const RISCVSubtarget &Subtarget) { 6525 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6526 EVT VT = Op.getValueType(); 6527 6528 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6529 return SDValue(); 6530 6531 SDValue Op0 = Op.getOperand(0); 6532 SDValue Op1 = Op.getOperand(1); 6533 6534 // Or is commutable so canonicalize the second OR to the LHS. 6535 if (Op0.getOpcode() != ISD::OR) 6536 std::swap(Op0, Op1); 6537 if (Op0.getOpcode() != ISD::OR) 6538 return SDValue(); 6539 6540 // We found an inner OR, so our operands are the operands of the inner OR 6541 // and the other operand of the outer OR. 6542 SDValue A = Op0.getOperand(0); 6543 SDValue B = Op0.getOperand(1); 6544 SDValue C = Op1; 6545 6546 auto Match1 = matchSHFLPat(A); 6547 auto Match2 = matchSHFLPat(B); 6548 6549 // If neither matched, we failed. 6550 if (!Match1 && !Match2) 6551 return SDValue(); 6552 6553 // We had at least one match. if one failed, try the remaining C operand. 6554 if (!Match1) { 6555 std::swap(A, C); 6556 Match1 = matchSHFLPat(A); 6557 if (!Match1) 6558 return SDValue(); 6559 } else if (!Match2) { 6560 std::swap(B, C); 6561 Match2 = matchSHFLPat(B); 6562 if (!Match2) 6563 return SDValue(); 6564 } 6565 assert(Match1 && Match2); 6566 6567 // Make sure our matches pair up. 6568 if (!Match1->formsPairWith(*Match2)) 6569 return SDValue(); 6570 6571 // All the remains is to make sure C is an AND with the same input, that masks 6572 // out the bits that are being shuffled. 6573 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6574 C.getOperand(0) != Match1->Op) 6575 return SDValue(); 6576 6577 uint64_t Mask = C.getConstantOperandVal(1); 6578 6579 static const uint64_t BitmanipMasks[] = { 6580 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6581 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6582 }; 6583 6584 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6585 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6586 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6587 6588 if (Mask != ExpMask) 6589 return SDValue(); 6590 6591 SDLoc DL(Op); 6592 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6593 DAG.getConstant(Match1->ShAmt, DL, VT)); 6594 } 6595 6596 // Optimize (add (shl x, c0), (shl y, c1)) -> 6597 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6598 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6599 const RISCVSubtarget &Subtarget) { 6600 // Perform this optimization only in the zba extension. 6601 if (!Subtarget.hasStdExtZba()) 6602 return SDValue(); 6603 6604 // Skip for vector types and larger types. 6605 EVT VT = N->getValueType(0); 6606 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6607 return SDValue(); 6608 6609 // The two operand nodes must be SHL and have no other use. 6610 SDValue N0 = N->getOperand(0); 6611 SDValue N1 = N->getOperand(1); 6612 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6613 !N0->hasOneUse() || !N1->hasOneUse()) 6614 return SDValue(); 6615 6616 // Check c0 and c1. 6617 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6618 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6619 if (!N0C || !N1C) 6620 return SDValue(); 6621 int64_t C0 = N0C->getSExtValue(); 6622 int64_t C1 = N1C->getSExtValue(); 6623 if (C0 <= 0 || C1 <= 0) 6624 return SDValue(); 6625 6626 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6627 int64_t Bits = std::min(C0, C1); 6628 int64_t Diff = std::abs(C0 - C1); 6629 if (Diff != 1 && Diff != 2 && Diff != 3) 6630 return SDValue(); 6631 6632 // Build nodes. 6633 SDLoc DL(N); 6634 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6635 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6636 SDValue NA0 = 6637 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6638 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6639 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6640 } 6641 6642 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 6643 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 6644 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 6645 // not undo itself, but they are redundant. 6646 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 6647 SDValue Src = N->getOperand(0); 6648 6649 if (Src.getOpcode() != N->getOpcode()) 6650 return SDValue(); 6651 6652 if (!isa<ConstantSDNode>(N->getOperand(1)) || 6653 !isa<ConstantSDNode>(Src.getOperand(1))) 6654 return SDValue(); 6655 6656 unsigned ShAmt1 = N->getConstantOperandVal(1); 6657 unsigned ShAmt2 = Src.getConstantOperandVal(1); 6658 Src = Src.getOperand(0); 6659 6660 unsigned CombinedShAmt; 6661 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 6662 CombinedShAmt = ShAmt1 | ShAmt2; 6663 else 6664 CombinedShAmt = ShAmt1 ^ ShAmt2; 6665 6666 if (CombinedShAmt == 0) 6667 return Src; 6668 6669 SDLoc DL(N); 6670 return DAG.getNode( 6671 N->getOpcode(), DL, N->getValueType(0), Src, 6672 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 6673 } 6674 6675 // Combine a constant select operand into its use: 6676 // 6677 // (and (select cond, -1, c), x) 6678 // -> (select cond, x, (and x, c)) [AllOnes=1] 6679 // (or (select cond, 0, c), x) 6680 // -> (select cond, x, (or x, c)) [AllOnes=0] 6681 // (xor (select cond, 0, c), x) 6682 // -> (select cond, x, (xor x, c)) [AllOnes=0] 6683 // (add (select cond, 0, c), x) 6684 // -> (select cond, x, (add x, c)) [AllOnes=0] 6685 // (sub x, (select cond, 0, c)) 6686 // -> (select cond, x, (sub x, c)) [AllOnes=0] 6687 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 6688 SelectionDAG &DAG, bool AllOnes) { 6689 EVT VT = N->getValueType(0); 6690 6691 // Skip vectors. 6692 if (VT.isVector()) 6693 return SDValue(); 6694 6695 if ((Slct.getOpcode() != ISD::SELECT && 6696 Slct.getOpcode() != RISCVISD::SELECT_CC) || 6697 !Slct.hasOneUse()) 6698 return SDValue(); 6699 6700 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 6701 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 6702 }; 6703 6704 bool SwapSelectOps; 6705 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 6706 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 6707 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 6708 SDValue NonConstantVal; 6709 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 6710 SwapSelectOps = false; 6711 NonConstantVal = FalseVal; 6712 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 6713 SwapSelectOps = true; 6714 NonConstantVal = TrueVal; 6715 } else 6716 return SDValue(); 6717 6718 // Slct is now know to be the desired identity constant when CC is true. 6719 TrueVal = OtherOp; 6720 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 6721 // Unless SwapSelectOps says the condition should be false. 6722 if (SwapSelectOps) 6723 std::swap(TrueVal, FalseVal); 6724 6725 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 6726 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 6727 {Slct.getOperand(0), Slct.getOperand(1), 6728 Slct.getOperand(2), TrueVal, FalseVal}); 6729 6730 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 6731 {Slct.getOperand(0), TrueVal, FalseVal}); 6732 } 6733 6734 // Attempt combineSelectAndUse on each operand of a commutative operator N. 6735 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 6736 bool AllOnes) { 6737 SDValue N0 = N->getOperand(0); 6738 SDValue N1 = N->getOperand(1); 6739 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 6740 return Result; 6741 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 6742 return Result; 6743 return SDValue(); 6744 } 6745 6746 // Transform (add (mul x, c0), c1) -> 6747 // (add (mul (add x, c1/c0), c0), c1%c0). 6748 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 6749 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 6750 // to an infinite loop in DAGCombine if transformed. 6751 // Or transform (add (mul x, c0), c1) -> 6752 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 6753 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 6754 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 6755 // lead to an infinite loop in DAGCombine if transformed. 6756 // Or transform (add (mul x, c0), c1) -> 6757 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 6758 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 6759 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 6760 // lead to an infinite loop in DAGCombine if transformed. 6761 // Or transform (add (mul x, c0), c1) -> 6762 // (mul (add x, c1/c0), c0). 6763 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 6764 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 6765 const RISCVSubtarget &Subtarget) { 6766 // Skip for vector types and larger types. 6767 EVT VT = N->getValueType(0); 6768 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6769 return SDValue(); 6770 // The first operand node must be a MUL and has no other use. 6771 SDValue N0 = N->getOperand(0); 6772 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 6773 return SDValue(); 6774 // Check if c0 and c1 match above conditions. 6775 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6776 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6777 if (!N0C || !N1C) 6778 return SDValue(); 6779 int64_t C0 = N0C->getSExtValue(); 6780 int64_t C1 = N1C->getSExtValue(); 6781 int64_t CA, CB; 6782 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 6783 return SDValue(); 6784 // Search for proper CA (non-zero) and CB that both are simm12. 6785 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 6786 !isInt<12>(C0 * (C1 / C0))) { 6787 CA = C1 / C0; 6788 CB = C1 % C0; 6789 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 6790 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 6791 CA = C1 / C0 + 1; 6792 CB = C1 % C0 - C0; 6793 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 6794 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 6795 CA = C1 / C0 - 1; 6796 CB = C1 % C0 + C0; 6797 } else 6798 return SDValue(); 6799 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 6800 SDLoc DL(N); 6801 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 6802 DAG.getConstant(CA, DL, VT)); 6803 SDValue New1 = 6804 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 6805 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 6806 } 6807 6808 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 6809 const RISCVSubtarget &Subtarget) { 6810 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 6811 return V; 6812 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 6813 return V; 6814 // fold (add (select lhs, rhs, cc, 0, y), x) -> 6815 // (select lhs, rhs, cc, x, (add x, y)) 6816 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6817 } 6818 6819 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 6820 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 6821 // (select lhs, rhs, cc, x, (sub x, y)) 6822 SDValue N0 = N->getOperand(0); 6823 SDValue N1 = N->getOperand(1); 6824 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 6825 } 6826 6827 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 6828 // fold (and (select lhs, rhs, cc, -1, y), x) -> 6829 // (select lhs, rhs, cc, x, (and x, y)) 6830 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 6831 } 6832 6833 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 6834 const RISCVSubtarget &Subtarget) { 6835 if (Subtarget.hasStdExtZbp()) { 6836 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 6837 return GREV; 6838 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 6839 return GORC; 6840 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 6841 return SHFL; 6842 } 6843 6844 // fold (or (select cond, 0, y), x) -> 6845 // (select cond, x, (or x, y)) 6846 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6847 } 6848 6849 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 6850 // fold (xor (select cond, 0, y), x) -> 6851 // (select cond, x, (xor x, y)) 6852 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 6853 } 6854 6855 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 6856 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 6857 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 6858 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 6859 // ADDW/SUBW/MULW. 6860 static SDValue performANY_EXTENDCombine(SDNode *N, 6861 TargetLowering::DAGCombinerInfo &DCI, 6862 const RISCVSubtarget &Subtarget) { 6863 if (!Subtarget.is64Bit()) 6864 return SDValue(); 6865 6866 SelectionDAG &DAG = DCI.DAG; 6867 6868 SDValue Src = N->getOperand(0); 6869 EVT VT = N->getValueType(0); 6870 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 6871 return SDValue(); 6872 6873 // The opcode must be one that can implicitly sign_extend. 6874 // FIXME: Additional opcodes. 6875 switch (Src.getOpcode()) { 6876 default: 6877 return SDValue(); 6878 case ISD::MUL: 6879 if (!Subtarget.hasStdExtM()) 6880 return SDValue(); 6881 LLVM_FALLTHROUGH; 6882 case ISD::ADD: 6883 case ISD::SUB: 6884 break; 6885 } 6886 6887 // Only handle cases where the result is used by a CopyToReg. That likely 6888 // means the value is a liveout of the basic block. This helps prevent 6889 // infinite combine loops like PR51206. 6890 if (none_of(N->uses(), 6891 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 6892 return SDValue(); 6893 6894 SmallVector<SDNode *, 4> SetCCs; 6895 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 6896 UE = Src.getNode()->use_end(); 6897 UI != UE; ++UI) { 6898 SDNode *User = *UI; 6899 if (User == N) 6900 continue; 6901 if (UI.getUse().getResNo() != Src.getResNo()) 6902 continue; 6903 // All i32 setccs are legalized by sign extending operands. 6904 if (User->getOpcode() == ISD::SETCC) { 6905 SetCCs.push_back(User); 6906 continue; 6907 } 6908 // We don't know if we can extend this user. 6909 break; 6910 } 6911 6912 // If we don't have any SetCCs, this isn't worthwhile. 6913 if (SetCCs.empty()) 6914 return SDValue(); 6915 6916 SDLoc DL(N); 6917 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 6918 DCI.CombineTo(N, SExt); 6919 6920 // Promote all the setccs. 6921 for (SDNode *SetCC : SetCCs) { 6922 SmallVector<SDValue, 4> Ops; 6923 6924 for (unsigned j = 0; j != 2; ++j) { 6925 SDValue SOp = SetCC->getOperand(j); 6926 if (SOp == Src) 6927 Ops.push_back(SExt); 6928 else 6929 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 6930 } 6931 6932 Ops.push_back(SetCC->getOperand(2)); 6933 DCI.CombineTo(SetCC, 6934 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6935 } 6936 return SDValue(N, 0); 6937 } 6938 6939 // Try to form VWMUL or VWMULU. 6940 // FIXME: Support VWMULSU. 6941 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1, 6942 SelectionDAG &DAG) { 6943 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 6944 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 6945 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 6946 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 6947 return SDValue(); 6948 6949 SDValue Mask = N->getOperand(2); 6950 SDValue VL = N->getOperand(3); 6951 6952 // Make sure the mask and VL match. 6953 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 6954 return SDValue(); 6955 6956 MVT VT = N->getSimpleValueType(0); 6957 6958 // Determine the narrow size for a widening multiply. 6959 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 6960 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 6961 VT.getVectorElementCount()); 6962 6963 SDLoc DL(N); 6964 6965 // See if the other operand is the same opcode. 6966 if (Op0.getOpcode() == Op1.getOpcode()) { 6967 if (!Op1.hasOneUse()) 6968 return SDValue(); 6969 6970 // Make sure the mask and VL match. 6971 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 6972 return SDValue(); 6973 6974 Op1 = Op1.getOperand(0); 6975 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 6976 // The operand is a splat of a scalar. 6977 6978 // The VL must be the same. 6979 if (Op1.getOperand(1) != VL) 6980 return SDValue(); 6981 6982 // Get the scalar value. 6983 Op1 = Op1.getOperand(0); 6984 6985 // See if have enough sign bits or zero bits in the scalar to use a 6986 // widening multiply by splatting to smaller element size. 6987 unsigned EltBits = VT.getScalarSizeInBits(); 6988 unsigned ScalarBits = Op1.getValueSizeInBits(); 6989 // Make sure we're getting all element bits from the scalar register. 6990 // FIXME: Support implicit sign extension of vmv.v.x? 6991 if (ScalarBits < EltBits) 6992 return SDValue(); 6993 6994 if (IsSignExt) { 6995 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 6996 return SDValue(); 6997 } else { 6998 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 6999 if (!DAG.MaskedValueIsZero(Op1, Mask)) 7000 return SDValue(); 7001 } 7002 7003 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 7004 } else 7005 return SDValue(); 7006 7007 Op0 = Op0.getOperand(0); 7008 7009 // Re-introduce narrower extends if needed. 7010 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7011 if (Op0.getValueType() != NarrowVT) 7012 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7013 if (Op1.getValueType() != NarrowVT) 7014 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7015 7016 unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7017 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7018 } 7019 7020 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7021 DAGCombinerInfo &DCI) const { 7022 SelectionDAG &DAG = DCI.DAG; 7023 7024 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7025 // bits are demanded. N will be added to the Worklist if it was not deleted. 7026 // Caller should return SDValue(N, 0) if this returns true. 7027 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7028 SDValue Op = N->getOperand(OpNo); 7029 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7030 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7031 return false; 7032 7033 if (N->getOpcode() != ISD::DELETED_NODE) 7034 DCI.AddToWorklist(N); 7035 return true; 7036 }; 7037 7038 switch (N->getOpcode()) { 7039 default: 7040 break; 7041 case RISCVISD::SplitF64: { 7042 SDValue Op0 = N->getOperand(0); 7043 // If the input to SplitF64 is just BuildPairF64 then the operation is 7044 // redundant. Instead, use BuildPairF64's operands directly. 7045 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7046 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7047 7048 SDLoc DL(N); 7049 7050 // It's cheaper to materialise two 32-bit integers than to load a double 7051 // from the constant pool and transfer it to integer registers through the 7052 // stack. 7053 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7054 APInt V = C->getValueAPF().bitcastToAPInt(); 7055 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 7056 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 7057 return DCI.CombineTo(N, Lo, Hi); 7058 } 7059 7060 // This is a target-specific version of a DAGCombine performed in 7061 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7062 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7063 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7064 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7065 !Op0.getNode()->hasOneUse()) 7066 break; 7067 SDValue NewSplitF64 = 7068 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 7069 Op0.getOperand(0)); 7070 SDValue Lo = NewSplitF64.getValue(0); 7071 SDValue Hi = NewSplitF64.getValue(1); 7072 APInt SignBit = APInt::getSignMask(32); 7073 if (Op0.getOpcode() == ISD::FNEG) { 7074 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 7075 DAG.getConstant(SignBit, DL, MVT::i32)); 7076 return DCI.CombineTo(N, Lo, NewHi); 7077 } 7078 assert(Op0.getOpcode() == ISD::FABS); 7079 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 7080 DAG.getConstant(~SignBit, DL, MVT::i32)); 7081 return DCI.CombineTo(N, Lo, NewHi); 7082 } 7083 case RISCVISD::SLLW: 7084 case RISCVISD::SRAW: 7085 case RISCVISD::SRLW: 7086 case RISCVISD::ROLW: 7087 case RISCVISD::RORW: { 7088 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7089 if (SimplifyDemandedLowBitsHelper(0, 32) || 7090 SimplifyDemandedLowBitsHelper(1, 5)) 7091 return SDValue(N, 0); 7092 break; 7093 } 7094 case RISCVISD::CLZW: 7095 case RISCVISD::CTZW: { 7096 // Only the lower 32 bits of the first operand are read 7097 if (SimplifyDemandedLowBitsHelper(0, 32)) 7098 return SDValue(N, 0); 7099 break; 7100 } 7101 case RISCVISD::FSL: 7102 case RISCVISD::FSR: { 7103 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 7104 unsigned BitWidth = N->getOperand(2).getValueSizeInBits(); 7105 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7106 if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1)) 7107 return SDValue(N, 0); 7108 break; 7109 } 7110 case RISCVISD::FSLW: 7111 case RISCVISD::FSRW: { 7112 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 7113 // read. 7114 if (SimplifyDemandedLowBitsHelper(0, 32) || 7115 SimplifyDemandedLowBitsHelper(1, 32) || 7116 SimplifyDemandedLowBitsHelper(2, 6)) 7117 return SDValue(N, 0); 7118 break; 7119 } 7120 case RISCVISD::GREV: 7121 case RISCVISD::GORC: { 7122 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 7123 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7124 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7125 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 7126 return SDValue(N, 0); 7127 7128 return combineGREVI_GORCI(N, DAG); 7129 } 7130 case RISCVISD::GREVW: 7131 case RISCVISD::GORCW: { 7132 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7133 if (SimplifyDemandedLowBitsHelper(0, 32) || 7134 SimplifyDemandedLowBitsHelper(1, 5)) 7135 return SDValue(N, 0); 7136 7137 return combineGREVI_GORCI(N, DAG); 7138 } 7139 case RISCVISD::SHFL: 7140 case RISCVISD::UNSHFL: { 7141 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 7142 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7143 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7144 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 7145 return SDValue(N, 0); 7146 7147 break; 7148 } 7149 case RISCVISD::SHFLW: 7150 case RISCVISD::UNSHFLW: { 7151 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 7152 SDValue LHS = N->getOperand(0); 7153 SDValue RHS = N->getOperand(1); 7154 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 7155 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 7156 if (SimplifyDemandedLowBitsHelper(0, 32) || 7157 SimplifyDemandedLowBitsHelper(1, 4)) 7158 return SDValue(N, 0); 7159 7160 break; 7161 } 7162 case RISCVISD::BCOMPRESSW: 7163 case RISCVISD::BDECOMPRESSW: { 7164 // Only the lower 32 bits of LHS and RHS are read. 7165 if (SimplifyDemandedLowBitsHelper(0, 32) || 7166 SimplifyDemandedLowBitsHelper(1, 32)) 7167 return SDValue(N, 0); 7168 7169 break; 7170 } 7171 case RISCVISD::FMV_X_ANYEXTH: 7172 case RISCVISD::FMV_X_ANYEXTW_RV64: { 7173 SDLoc DL(N); 7174 SDValue Op0 = N->getOperand(0); 7175 MVT VT = N->getSimpleValueType(0); 7176 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 7177 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 7178 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 7179 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 7180 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 7181 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7182 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 7183 assert(Op0.getOperand(0).getValueType() == VT && 7184 "Unexpected value type!"); 7185 return Op0.getOperand(0); 7186 } 7187 7188 // This is a target-specific version of a DAGCombine performed in 7189 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7190 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7191 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7192 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7193 !Op0.getNode()->hasOneUse()) 7194 break; 7195 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 7196 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 7197 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7198 if (Op0.getOpcode() == ISD::FNEG) 7199 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7200 DAG.getConstant(SignBit, DL, VT)); 7201 7202 assert(Op0.getOpcode() == ISD::FABS); 7203 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7204 DAG.getConstant(~SignBit, DL, VT)); 7205 } 7206 case ISD::ADD: 7207 return performADDCombine(N, DAG, Subtarget); 7208 case ISD::SUB: 7209 return performSUBCombine(N, DAG); 7210 case ISD::AND: 7211 return performANDCombine(N, DAG); 7212 case ISD::OR: 7213 return performORCombine(N, DAG, Subtarget); 7214 case ISD::XOR: 7215 return performXORCombine(N, DAG); 7216 case ISD::ANY_EXTEND: 7217 return performANY_EXTENDCombine(N, DCI, Subtarget); 7218 case ISD::ZERO_EXTEND: 7219 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7220 // type legalization. This is safe because fp_to_uint produces poison if 7221 // it overflows. 7222 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 7223 SDValue Src = N->getOperand(0); 7224 if (Src.getOpcode() == ISD::FP_TO_UINT && 7225 isTypeLegal(Src.getOperand(0).getValueType())) 7226 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7227 Src.getOperand(0)); 7228 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 7229 isTypeLegal(Src.getOperand(1).getValueType())) { 7230 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7231 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 7232 Src.getOperand(0), Src.getOperand(1)); 7233 DCI.CombineTo(N, Res); 7234 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 7235 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 7236 return SDValue(N, 0); // Return N so it doesn't get rechecked. 7237 } 7238 } 7239 return SDValue(); 7240 case RISCVISD::SELECT_CC: { 7241 // Transform 7242 SDValue LHS = N->getOperand(0); 7243 SDValue RHS = N->getOperand(1); 7244 SDValue TrueV = N->getOperand(3); 7245 SDValue FalseV = N->getOperand(4); 7246 7247 // If the True and False values are the same, we don't need a select_cc. 7248 if (TrueV == FalseV) 7249 return TrueV; 7250 7251 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7252 if (!ISD::isIntEqualitySetCC(CCVal)) 7253 break; 7254 7255 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7256 // (select_cc X, Y, lt, trueV, falseV) 7257 // Sometimes the setcc is introduced after select_cc has been formed. 7258 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7259 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7260 // If we're looking for eq 0 instead of ne 0, we need to invert the 7261 // condition. 7262 bool Invert = CCVal == ISD::SETEQ; 7263 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7264 if (Invert) 7265 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7266 7267 SDLoc DL(N); 7268 RHS = LHS.getOperand(1); 7269 LHS = LHS.getOperand(0); 7270 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7271 7272 SDValue TargetCC = DAG.getCondCode(CCVal); 7273 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7274 {LHS, RHS, TargetCC, TrueV, FalseV}); 7275 } 7276 7277 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7278 // (select_cc X, Y, eq/ne, trueV, falseV) 7279 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7280 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7281 {LHS.getOperand(0), LHS.getOperand(1), 7282 N->getOperand(2), TrueV, FalseV}); 7283 // (select_cc X, 1, setne, trueV, falseV) -> 7284 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7285 // This can occur when legalizing some floating point comparisons. 7286 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7287 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7288 SDLoc DL(N); 7289 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7290 SDValue TargetCC = DAG.getCondCode(CCVal); 7291 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7292 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7293 {LHS, RHS, TargetCC, TrueV, FalseV}); 7294 } 7295 7296 break; 7297 } 7298 case RISCVISD::BR_CC: { 7299 SDValue LHS = N->getOperand(1); 7300 SDValue RHS = N->getOperand(2); 7301 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7302 if (!ISD::isIntEqualitySetCC(CCVal)) 7303 break; 7304 7305 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7306 // (br_cc X, Y, lt, dest) 7307 // Sometimes the setcc is introduced after br_cc has been formed. 7308 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7309 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7310 // If we're looking for eq 0 instead of ne 0, we need to invert the 7311 // condition. 7312 bool Invert = CCVal == ISD::SETEQ; 7313 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7314 if (Invert) 7315 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7316 7317 SDLoc DL(N); 7318 RHS = LHS.getOperand(1); 7319 LHS = LHS.getOperand(0); 7320 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7321 7322 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7323 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7324 N->getOperand(4)); 7325 } 7326 7327 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7328 // (br_cc X, Y, eq/ne, trueV, falseV) 7329 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7330 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7331 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7332 N->getOperand(3), N->getOperand(4)); 7333 7334 // (br_cc X, 1, setne, br_cc) -> 7335 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7336 // This can occur when legalizing some floating point comparisons. 7337 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7338 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7339 SDLoc DL(N); 7340 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7341 SDValue TargetCC = DAG.getCondCode(CCVal); 7342 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7343 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7344 N->getOperand(0), LHS, RHS, TargetCC, 7345 N->getOperand(4)); 7346 } 7347 break; 7348 } 7349 case ISD::FCOPYSIGN: { 7350 EVT VT = N->getValueType(0); 7351 if (!VT.isVector()) 7352 break; 7353 // There is a form of VFSGNJ which injects the negated sign of its second 7354 // operand. Try and bubble any FNEG up after the extend/round to produce 7355 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7356 // TRUNC=1. 7357 SDValue In2 = N->getOperand(1); 7358 // Avoid cases where the extend/round has multiple uses, as duplicating 7359 // those is typically more expensive than removing a fneg. 7360 if (!In2.hasOneUse()) 7361 break; 7362 if (In2.getOpcode() != ISD::FP_EXTEND && 7363 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7364 break; 7365 In2 = In2.getOperand(0); 7366 if (In2.getOpcode() != ISD::FNEG) 7367 break; 7368 SDLoc DL(N); 7369 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7370 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7371 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7372 } 7373 case ISD::MGATHER: 7374 case ISD::MSCATTER: 7375 case ISD::VP_GATHER: 7376 case ISD::VP_SCATTER: { 7377 if (!DCI.isBeforeLegalize()) 7378 break; 7379 SDValue Index, ScaleOp; 7380 bool IsIndexScaled = false; 7381 bool IsIndexSigned = false; 7382 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7383 Index = VPGSN->getIndex(); 7384 ScaleOp = VPGSN->getScale(); 7385 IsIndexScaled = VPGSN->isIndexScaled(); 7386 IsIndexSigned = VPGSN->isIndexSigned(); 7387 } else { 7388 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7389 Index = MGSN->getIndex(); 7390 ScaleOp = MGSN->getScale(); 7391 IsIndexScaled = MGSN->isIndexScaled(); 7392 IsIndexSigned = MGSN->isIndexSigned(); 7393 } 7394 EVT IndexVT = Index.getValueType(); 7395 MVT XLenVT = Subtarget.getXLenVT(); 7396 // RISCV indexed loads only support the "unsigned unscaled" addressing 7397 // mode, so anything else must be manually legalized. 7398 bool NeedsIdxLegalization = 7399 IsIndexScaled || 7400 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7401 if (!NeedsIdxLegalization) 7402 break; 7403 7404 SDLoc DL(N); 7405 7406 // Any index legalization should first promote to XLenVT, so we don't lose 7407 // bits when scaling. This may create an illegal index type so we let 7408 // LLVM's legalization take care of the splitting. 7409 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7410 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7411 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7412 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7413 DL, IndexVT, Index); 7414 } 7415 7416 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7417 if (IsIndexScaled && Scale != 1) { 7418 // Manually scale the indices by the element size. 7419 // TODO: Sanitize the scale operand here? 7420 // TODO: For VP nodes, should we use VP_SHL here? 7421 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7422 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7423 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7424 } 7425 7426 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7427 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7428 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7429 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7430 VPGN->getScale(), VPGN->getMask(), 7431 VPGN->getVectorLength()}, 7432 VPGN->getMemOperand(), NewIndexTy); 7433 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7434 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7435 {VPSN->getChain(), VPSN->getValue(), 7436 VPSN->getBasePtr(), Index, VPSN->getScale(), 7437 VPSN->getMask(), VPSN->getVectorLength()}, 7438 VPSN->getMemOperand(), NewIndexTy); 7439 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7440 return DAG.getMaskedGather( 7441 N->getVTList(), MGN->getMemoryVT(), DL, 7442 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7443 MGN->getBasePtr(), Index, MGN->getScale()}, 7444 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7445 const auto *MSN = cast<MaskedScatterSDNode>(N); 7446 return DAG.getMaskedScatter( 7447 N->getVTList(), MSN->getMemoryVT(), DL, 7448 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7449 Index, MSN->getScale()}, 7450 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7451 } 7452 case RISCVISD::SRA_VL: 7453 case RISCVISD::SRL_VL: 7454 case RISCVISD::SHL_VL: { 7455 SDValue ShAmt = N->getOperand(1); 7456 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7457 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7458 SDLoc DL(N); 7459 SDValue VL = N->getOperand(3); 7460 EVT VT = N->getValueType(0); 7461 ShAmt = 7462 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7463 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7464 N->getOperand(2), N->getOperand(3)); 7465 } 7466 break; 7467 } 7468 case ISD::SRA: 7469 case ISD::SRL: 7470 case ISD::SHL: { 7471 SDValue ShAmt = N->getOperand(1); 7472 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7473 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7474 SDLoc DL(N); 7475 EVT VT = N->getValueType(0); 7476 ShAmt = 7477 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7478 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7479 } 7480 break; 7481 } 7482 case RISCVISD::MUL_VL: { 7483 SDValue Op0 = N->getOperand(0); 7484 SDValue Op1 = N->getOperand(1); 7485 if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG)) 7486 return V; 7487 if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG)) 7488 return V; 7489 return SDValue(); 7490 } 7491 case ISD::STORE: { 7492 auto *Store = cast<StoreSDNode>(N); 7493 SDValue Val = Store->getValue(); 7494 // Combine store of vmv.x.s to vse with VL of 1. 7495 // FIXME: Support FP. 7496 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7497 SDValue Src = Val.getOperand(0); 7498 EVT VecVT = Src.getValueType(); 7499 EVT MemVT = Store->getMemoryVT(); 7500 // The memory VT and the element type must match. 7501 if (VecVT.getVectorElementType() == MemVT) { 7502 SDLoc DL(N); 7503 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7504 return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(), 7505 DAG.getConstant(1, DL, MaskVT), 7506 DAG.getConstant(1, DL, Subtarget.getXLenVT()), 7507 Store->getPointerInfo(), 7508 Store->getOriginalAlign(), 7509 Store->getMemOperand()->getFlags()); 7510 } 7511 } 7512 7513 break; 7514 } 7515 } 7516 7517 return SDValue(); 7518 } 7519 7520 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7521 const SDNode *N, CombineLevel Level) const { 7522 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7523 // materialised in fewer instructions than `(OP _, c1)`: 7524 // 7525 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7526 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7527 SDValue N0 = N->getOperand(0); 7528 EVT Ty = N0.getValueType(); 7529 if (Ty.isScalarInteger() && 7530 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7531 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7532 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7533 if (C1 && C2) { 7534 const APInt &C1Int = C1->getAPIntValue(); 7535 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 7536 7537 // We can materialise `c1 << c2` into an add immediate, so it's "free", 7538 // and the combine should happen, to potentially allow further combines 7539 // later. 7540 if (ShiftedC1Int.getMinSignedBits() <= 64 && 7541 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 7542 return true; 7543 7544 // We can materialise `c1` in an add immediate, so it's "free", and the 7545 // combine should be prevented. 7546 if (C1Int.getMinSignedBits() <= 64 && 7547 isLegalAddImmediate(C1Int.getSExtValue())) 7548 return false; 7549 7550 // Neither constant will fit into an immediate, so find materialisation 7551 // costs. 7552 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 7553 Subtarget.getFeatureBits(), 7554 /*CompressionCost*/true); 7555 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 7556 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 7557 /*CompressionCost*/true); 7558 7559 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 7560 // combine should be prevented. 7561 if (C1Cost < ShiftedC1Cost) 7562 return false; 7563 } 7564 } 7565 return true; 7566 } 7567 7568 bool RISCVTargetLowering::targetShrinkDemandedConstant( 7569 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 7570 TargetLoweringOpt &TLO) const { 7571 // Delay this optimization as late as possible. 7572 if (!TLO.LegalOps) 7573 return false; 7574 7575 EVT VT = Op.getValueType(); 7576 if (VT.isVector()) 7577 return false; 7578 7579 // Only handle AND for now. 7580 if (Op.getOpcode() != ISD::AND) 7581 return false; 7582 7583 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7584 if (!C) 7585 return false; 7586 7587 const APInt &Mask = C->getAPIntValue(); 7588 7589 // Clear all non-demanded bits initially. 7590 APInt ShrunkMask = Mask & DemandedBits; 7591 7592 // Try to make a smaller immediate by setting undemanded bits. 7593 7594 APInt ExpandedMask = Mask | ~DemandedBits; 7595 7596 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 7597 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 7598 }; 7599 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 7600 if (NewMask == Mask) 7601 return true; 7602 SDLoc DL(Op); 7603 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 7604 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 7605 return TLO.CombineTo(Op, NewOp); 7606 }; 7607 7608 // If the shrunk mask fits in sign extended 12 bits, let the target 7609 // independent code apply it. 7610 if (ShrunkMask.isSignedIntN(12)) 7611 return false; 7612 7613 // Preserve (and X, 0xffff) when zext.h is supported. 7614 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 7615 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 7616 if (IsLegalMask(NewMask)) 7617 return UseMask(NewMask); 7618 } 7619 7620 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 7621 if (VT == MVT::i64) { 7622 APInt NewMask = APInt(64, 0xffffffff); 7623 if (IsLegalMask(NewMask)) 7624 return UseMask(NewMask); 7625 } 7626 7627 // For the remaining optimizations, we need to be able to make a negative 7628 // number through a combination of mask and undemanded bits. 7629 if (!ExpandedMask.isNegative()) 7630 return false; 7631 7632 // What is the fewest number of bits we need to represent the negative number. 7633 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 7634 7635 // Try to make a 12 bit negative immediate. If that fails try to make a 32 7636 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 7637 APInt NewMask = ShrunkMask; 7638 if (MinSignedBits <= 12) 7639 NewMask.setBitsFrom(11); 7640 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 7641 NewMask.setBitsFrom(31); 7642 else 7643 return false; 7644 7645 // Check that our new mask is a subset of the demanded mask. 7646 assert(IsLegalMask(NewMask)); 7647 return UseMask(NewMask); 7648 } 7649 7650 static void computeGREV(APInt &Src, unsigned ShAmt) { 7651 ShAmt &= Src.getBitWidth() - 1; 7652 uint64_t x = Src.getZExtValue(); 7653 if (ShAmt & 1) 7654 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 7655 if (ShAmt & 2) 7656 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 7657 if (ShAmt & 4) 7658 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 7659 if (ShAmt & 8) 7660 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 7661 if (ShAmt & 16) 7662 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 7663 if (ShAmt & 32) 7664 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 7665 Src = x; 7666 } 7667 7668 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 7669 KnownBits &Known, 7670 const APInt &DemandedElts, 7671 const SelectionDAG &DAG, 7672 unsigned Depth) const { 7673 unsigned BitWidth = Known.getBitWidth(); 7674 unsigned Opc = Op.getOpcode(); 7675 assert((Opc >= ISD::BUILTIN_OP_END || 7676 Opc == ISD::INTRINSIC_WO_CHAIN || 7677 Opc == ISD::INTRINSIC_W_CHAIN || 7678 Opc == ISD::INTRINSIC_VOID) && 7679 "Should use MaskedValueIsZero if you don't know whether Op" 7680 " is a target node!"); 7681 7682 Known.resetAll(); 7683 switch (Opc) { 7684 default: break; 7685 case RISCVISD::SELECT_CC: { 7686 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 7687 // If we don't know any bits, early out. 7688 if (Known.isUnknown()) 7689 break; 7690 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 7691 7692 // Only known if known in both the LHS and RHS. 7693 Known = KnownBits::commonBits(Known, Known2); 7694 break; 7695 } 7696 case RISCVISD::REMUW: { 7697 KnownBits Known2; 7698 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7699 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7700 // We only care about the lower 32 bits. 7701 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 7702 // Restore the original width by sign extending. 7703 Known = Known.sext(BitWidth); 7704 break; 7705 } 7706 case RISCVISD::DIVUW: { 7707 KnownBits Known2; 7708 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 7709 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 7710 // We only care about the lower 32 bits. 7711 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 7712 // Restore the original width by sign extending. 7713 Known = Known.sext(BitWidth); 7714 break; 7715 } 7716 case RISCVISD::CTZW: { 7717 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7718 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 7719 unsigned LowBits = Log2_32(PossibleTZ) + 1; 7720 Known.Zero.setBitsFrom(LowBits); 7721 break; 7722 } 7723 case RISCVISD::CLZW: { 7724 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7725 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 7726 unsigned LowBits = Log2_32(PossibleLZ) + 1; 7727 Known.Zero.setBitsFrom(LowBits); 7728 break; 7729 } 7730 case RISCVISD::GREV: 7731 case RISCVISD::GREVW: { 7732 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7733 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 7734 if (Opc == RISCVISD::GREVW) 7735 Known = Known.trunc(32); 7736 unsigned ShAmt = C->getZExtValue(); 7737 computeGREV(Known.Zero, ShAmt); 7738 computeGREV(Known.One, ShAmt); 7739 if (Opc == RISCVISD::GREVW) 7740 Known = Known.sext(BitWidth); 7741 } 7742 break; 7743 } 7744 case RISCVISD::READ_VLENB: 7745 // We assume VLENB is at least 16 bytes. 7746 Known.Zero.setLowBits(4); 7747 // We assume VLENB is no more than 65536 / 8 bytes. 7748 Known.Zero.setBitsFrom(14); 7749 break; 7750 case ISD::INTRINSIC_W_CHAIN: { 7751 unsigned IntNo = Op.getConstantOperandVal(1); 7752 switch (IntNo) { 7753 default: 7754 // We can't do anything for most intrinsics. 7755 break; 7756 case Intrinsic::riscv_vsetvli: 7757 case Intrinsic::riscv_vsetvlimax: 7758 // Assume that VL output is positive and would fit in an int32_t. 7759 // TODO: VLEN might be capped at 16 bits in a future V spec update. 7760 if (BitWidth >= 32) 7761 Known.Zero.setBitsFrom(31); 7762 break; 7763 } 7764 break; 7765 } 7766 } 7767 } 7768 7769 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 7770 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 7771 unsigned Depth) const { 7772 switch (Op.getOpcode()) { 7773 default: 7774 break; 7775 case RISCVISD::SELECT_CC: { 7776 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 7777 if (Tmp == 1) return 1; // Early out. 7778 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 7779 return std::min(Tmp, Tmp2); 7780 } 7781 case RISCVISD::SLLW: 7782 case RISCVISD::SRAW: 7783 case RISCVISD::SRLW: 7784 case RISCVISD::DIVW: 7785 case RISCVISD::DIVUW: 7786 case RISCVISD::REMUW: 7787 case RISCVISD::ROLW: 7788 case RISCVISD::RORW: 7789 case RISCVISD::GREVW: 7790 case RISCVISD::GORCW: 7791 case RISCVISD::FSLW: 7792 case RISCVISD::FSRW: 7793 case RISCVISD::SHFLW: 7794 case RISCVISD::UNSHFLW: 7795 case RISCVISD::BCOMPRESSW: 7796 case RISCVISD::BDECOMPRESSW: 7797 case RISCVISD::FCVT_W_RTZ_RV64: 7798 case RISCVISD::FCVT_WU_RTZ_RV64: 7799 case RISCVISD::STRICT_FCVT_W_RTZ_RV64: 7800 case RISCVISD::STRICT_FCVT_WU_RTZ_RV64: 7801 // TODO: As the result is sign-extended, this is conservatively correct. A 7802 // more precise answer could be calculated for SRAW depending on known 7803 // bits in the shift amount. 7804 return 33; 7805 case RISCVISD::SHFL: 7806 case RISCVISD::UNSHFL: { 7807 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 7808 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 7809 // will stay within the upper 32 bits. If there were more than 32 sign bits 7810 // before there will be at least 33 sign bits after. 7811 if (Op.getValueType() == MVT::i64 && 7812 isa<ConstantSDNode>(Op.getOperand(1)) && 7813 (Op.getConstantOperandVal(1) & 0x10) == 0) { 7814 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 7815 if (Tmp > 32) 7816 return 33; 7817 } 7818 break; 7819 } 7820 case RISCVISD::VMV_X_S: 7821 // The number of sign bits of the scalar result is computed by obtaining the 7822 // element type of the input vector operand, subtracting its width from the 7823 // XLEN, and then adding one (sign bit within the element type). If the 7824 // element type is wider than XLen, the least-significant XLEN bits are 7825 // taken. 7826 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 7827 return 1; 7828 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 7829 } 7830 7831 return 1; 7832 } 7833 7834 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 7835 MachineBasicBlock *BB) { 7836 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 7837 7838 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 7839 // Should the count have wrapped while it was being read, we need to try 7840 // again. 7841 // ... 7842 // read: 7843 // rdcycleh x3 # load high word of cycle 7844 // rdcycle x2 # load low word of cycle 7845 // rdcycleh x4 # load high word of cycle 7846 // bne x3, x4, read # check if high word reads match, otherwise try again 7847 // ... 7848 7849 MachineFunction &MF = *BB->getParent(); 7850 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7851 MachineFunction::iterator It = ++BB->getIterator(); 7852 7853 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7854 MF.insert(It, LoopMBB); 7855 7856 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 7857 MF.insert(It, DoneMBB); 7858 7859 // Transfer the remainder of BB and its successor edges to DoneMBB. 7860 DoneMBB->splice(DoneMBB->begin(), BB, 7861 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7862 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 7863 7864 BB->addSuccessor(LoopMBB); 7865 7866 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7867 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 7868 Register LoReg = MI.getOperand(0).getReg(); 7869 Register HiReg = MI.getOperand(1).getReg(); 7870 DebugLoc DL = MI.getDebugLoc(); 7871 7872 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 7873 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 7874 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7875 .addReg(RISCV::X0); 7876 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 7877 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 7878 .addReg(RISCV::X0); 7879 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 7880 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 7881 .addReg(RISCV::X0); 7882 7883 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 7884 .addReg(HiReg) 7885 .addReg(ReadAgainReg) 7886 .addMBB(LoopMBB); 7887 7888 LoopMBB->addSuccessor(LoopMBB); 7889 LoopMBB->addSuccessor(DoneMBB); 7890 7891 MI.eraseFromParent(); 7892 7893 return DoneMBB; 7894 } 7895 7896 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 7897 MachineBasicBlock *BB) { 7898 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 7899 7900 MachineFunction &MF = *BB->getParent(); 7901 DebugLoc DL = MI.getDebugLoc(); 7902 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7903 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7904 Register LoReg = MI.getOperand(0).getReg(); 7905 Register HiReg = MI.getOperand(1).getReg(); 7906 Register SrcReg = MI.getOperand(2).getReg(); 7907 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 7908 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7909 7910 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 7911 RI); 7912 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7913 MachineMemOperand *MMOLo = 7914 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 7915 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7916 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 7917 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 7918 .addFrameIndex(FI) 7919 .addImm(0) 7920 .addMemOperand(MMOLo); 7921 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 7922 .addFrameIndex(FI) 7923 .addImm(4) 7924 .addMemOperand(MMOHi); 7925 MI.eraseFromParent(); // The pseudo instruction is gone now. 7926 return BB; 7927 } 7928 7929 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 7930 MachineBasicBlock *BB) { 7931 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 7932 "Unexpected instruction"); 7933 7934 MachineFunction &MF = *BB->getParent(); 7935 DebugLoc DL = MI.getDebugLoc(); 7936 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 7937 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 7938 Register DstReg = MI.getOperand(0).getReg(); 7939 Register LoReg = MI.getOperand(1).getReg(); 7940 Register HiReg = MI.getOperand(2).getReg(); 7941 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 7942 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 7943 7944 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 7945 MachineMemOperand *MMOLo = 7946 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 7947 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 7948 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 7949 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7950 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 7951 .addFrameIndex(FI) 7952 .addImm(0) 7953 .addMemOperand(MMOLo); 7954 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 7955 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 7956 .addFrameIndex(FI) 7957 .addImm(4) 7958 .addMemOperand(MMOHi); 7959 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 7960 MI.eraseFromParent(); // The pseudo instruction is gone now. 7961 return BB; 7962 } 7963 7964 static bool isSelectPseudo(MachineInstr &MI) { 7965 switch (MI.getOpcode()) { 7966 default: 7967 return false; 7968 case RISCV::Select_GPR_Using_CC_GPR: 7969 case RISCV::Select_FPR16_Using_CC_GPR: 7970 case RISCV::Select_FPR32_Using_CC_GPR: 7971 case RISCV::Select_FPR64_Using_CC_GPR: 7972 return true; 7973 } 7974 } 7975 7976 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 7977 MachineBasicBlock *BB, 7978 const RISCVSubtarget &Subtarget) { 7979 // To "insert" Select_* instructions, we actually have to insert the triangle 7980 // control-flow pattern. The incoming instructions know the destination vreg 7981 // to set, the condition code register to branch on, the true/false values to 7982 // select between, and the condcode to use to select the appropriate branch. 7983 // 7984 // We produce the following control flow: 7985 // HeadMBB 7986 // | \ 7987 // | IfFalseMBB 7988 // | / 7989 // TailMBB 7990 // 7991 // When we find a sequence of selects we attempt to optimize their emission 7992 // by sharing the control flow. Currently we only handle cases where we have 7993 // multiple selects with the exact same condition (same LHS, RHS and CC). 7994 // The selects may be interleaved with other instructions if the other 7995 // instructions meet some requirements we deem safe: 7996 // - They are debug instructions. Otherwise, 7997 // - They do not have side-effects, do not access memory and their inputs do 7998 // not depend on the results of the select pseudo-instructions. 7999 // The TrueV/FalseV operands of the selects cannot depend on the result of 8000 // previous selects in the sequence. 8001 // These conditions could be further relaxed. See the X86 target for a 8002 // related approach and more information. 8003 Register LHS = MI.getOperand(1).getReg(); 8004 Register RHS = MI.getOperand(2).getReg(); 8005 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 8006 8007 SmallVector<MachineInstr *, 4> SelectDebugValues; 8008 SmallSet<Register, 4> SelectDests; 8009 SelectDests.insert(MI.getOperand(0).getReg()); 8010 8011 MachineInstr *LastSelectPseudo = &MI; 8012 8013 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 8014 SequenceMBBI != E; ++SequenceMBBI) { 8015 if (SequenceMBBI->isDebugInstr()) 8016 continue; 8017 else if (isSelectPseudo(*SequenceMBBI)) { 8018 if (SequenceMBBI->getOperand(1).getReg() != LHS || 8019 SequenceMBBI->getOperand(2).getReg() != RHS || 8020 SequenceMBBI->getOperand(3).getImm() != CC || 8021 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 8022 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 8023 break; 8024 LastSelectPseudo = &*SequenceMBBI; 8025 SequenceMBBI->collectDebugValues(SelectDebugValues); 8026 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 8027 } else { 8028 if (SequenceMBBI->hasUnmodeledSideEffects() || 8029 SequenceMBBI->mayLoadOrStore()) 8030 break; 8031 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 8032 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 8033 })) 8034 break; 8035 } 8036 } 8037 8038 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 8039 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8040 DebugLoc DL = MI.getDebugLoc(); 8041 MachineFunction::iterator I = ++BB->getIterator(); 8042 8043 MachineBasicBlock *HeadMBB = BB; 8044 MachineFunction *F = BB->getParent(); 8045 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 8046 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 8047 8048 F->insert(I, IfFalseMBB); 8049 F->insert(I, TailMBB); 8050 8051 // Transfer debug instructions associated with the selects to TailMBB. 8052 for (MachineInstr *DebugInstr : SelectDebugValues) { 8053 TailMBB->push_back(DebugInstr->removeFromParent()); 8054 } 8055 8056 // Move all instructions after the sequence to TailMBB. 8057 TailMBB->splice(TailMBB->end(), HeadMBB, 8058 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 8059 // Update machine-CFG edges by transferring all successors of the current 8060 // block to the new block which will contain the Phi nodes for the selects. 8061 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 8062 // Set the successors for HeadMBB. 8063 HeadMBB->addSuccessor(IfFalseMBB); 8064 HeadMBB->addSuccessor(TailMBB); 8065 8066 // Insert appropriate branch. 8067 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 8068 .addReg(LHS) 8069 .addReg(RHS) 8070 .addMBB(TailMBB); 8071 8072 // IfFalseMBB just falls through to TailMBB. 8073 IfFalseMBB->addSuccessor(TailMBB); 8074 8075 // Create PHIs for all of the select pseudo-instructions. 8076 auto SelectMBBI = MI.getIterator(); 8077 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 8078 auto InsertionPoint = TailMBB->begin(); 8079 while (SelectMBBI != SelectEnd) { 8080 auto Next = std::next(SelectMBBI); 8081 if (isSelectPseudo(*SelectMBBI)) { 8082 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 8083 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 8084 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 8085 .addReg(SelectMBBI->getOperand(4).getReg()) 8086 .addMBB(HeadMBB) 8087 .addReg(SelectMBBI->getOperand(5).getReg()) 8088 .addMBB(IfFalseMBB); 8089 SelectMBBI->eraseFromParent(); 8090 } 8091 SelectMBBI = Next; 8092 } 8093 8094 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8095 return TailMBB; 8096 } 8097 8098 MachineBasicBlock * 8099 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8100 MachineBasicBlock *BB) const { 8101 switch (MI.getOpcode()) { 8102 default: 8103 llvm_unreachable("Unexpected instr type to insert"); 8104 case RISCV::ReadCycleWide: 8105 assert(!Subtarget.is64Bit() && 8106 "ReadCycleWrite is only to be used on riscv32"); 8107 return emitReadCycleWidePseudo(MI, BB); 8108 case RISCV::Select_GPR_Using_CC_GPR: 8109 case RISCV::Select_FPR16_Using_CC_GPR: 8110 case RISCV::Select_FPR32_Using_CC_GPR: 8111 case RISCV::Select_FPR64_Using_CC_GPR: 8112 return emitSelectPseudo(MI, BB, Subtarget); 8113 case RISCV::BuildPairF64Pseudo: 8114 return emitBuildPairF64Pseudo(MI, BB); 8115 case RISCV::SplitF64Pseudo: 8116 return emitSplitF64Pseudo(MI, BB); 8117 } 8118 } 8119 8120 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8121 SDNode *Node) const { 8122 // Add FRM dependency to any instructions with dynamic rounding mode. 8123 unsigned Opc = MI.getOpcode(); 8124 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 8125 if (Idx < 0) 8126 return; 8127 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 8128 return; 8129 // If the instruction already reads FRM, don't add another read. 8130 if (MI.readsRegister(RISCV::FRM)) 8131 return; 8132 MI.addOperand( 8133 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 8134 } 8135 8136 // Calling Convention Implementation. 8137 // The expectations for frontend ABI lowering vary from target to target. 8138 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 8139 // details, but this is a longer term goal. For now, we simply try to keep the 8140 // role of the frontend as simple and well-defined as possible. The rules can 8141 // be summarised as: 8142 // * Never split up large scalar arguments. We handle them here. 8143 // * If a hardfloat calling convention is being used, and the struct may be 8144 // passed in a pair of registers (fp+fp, int+fp), and both registers are 8145 // available, then pass as two separate arguments. If either the GPRs or FPRs 8146 // are exhausted, then pass according to the rule below. 8147 // * If a struct could never be passed in registers or directly in a stack 8148 // slot (as it is larger than 2*XLEN and the floating point rules don't 8149 // apply), then pass it using a pointer with the byval attribute. 8150 // * If a struct is less than 2*XLEN, then coerce to either a two-element 8151 // word-sized array or a 2*XLEN scalar (depending on alignment). 8152 // * The frontend can determine whether a struct is returned by reference or 8153 // not based on its size and fields. If it will be returned by reference, the 8154 // frontend must modify the prototype so a pointer with the sret annotation is 8155 // passed as the first argument. This is not necessary for large scalar 8156 // returns. 8157 // * Struct return values and varargs should be coerced to structs containing 8158 // register-size fields in the same situations they would be for fixed 8159 // arguments. 8160 8161 static const MCPhysReg ArgGPRs[] = { 8162 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 8163 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 8164 }; 8165 static const MCPhysReg ArgFPR16s[] = { 8166 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 8167 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 8168 }; 8169 static const MCPhysReg ArgFPR32s[] = { 8170 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 8171 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 8172 }; 8173 static const MCPhysReg ArgFPR64s[] = { 8174 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 8175 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 8176 }; 8177 // This is an interim calling convention and it may be changed in the future. 8178 static const MCPhysReg ArgVRs[] = { 8179 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 8180 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 8181 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 8182 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 8183 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 8184 RISCV::V20M2, RISCV::V22M2}; 8185 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 8186 RISCV::V20M4}; 8187 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 8188 8189 // Pass a 2*XLEN argument that has been split into two XLEN values through 8190 // registers or the stack as necessary. 8191 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 8192 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 8193 MVT ValVT2, MVT LocVT2, 8194 ISD::ArgFlagsTy ArgFlags2) { 8195 unsigned XLenInBytes = XLen / 8; 8196 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8197 // At least one half can be passed via register. 8198 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 8199 VA1.getLocVT(), CCValAssign::Full)); 8200 } else { 8201 // Both halves must be passed on the stack, with proper alignment. 8202 Align StackAlign = 8203 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 8204 State.addLoc( 8205 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 8206 State.AllocateStack(XLenInBytes, StackAlign), 8207 VA1.getLocVT(), CCValAssign::Full)); 8208 State.addLoc(CCValAssign::getMem( 8209 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8210 LocVT2, CCValAssign::Full)); 8211 return false; 8212 } 8213 8214 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8215 // The second half can also be passed via register. 8216 State.addLoc( 8217 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 8218 } else { 8219 // The second half is passed via the stack, without additional alignment. 8220 State.addLoc(CCValAssign::getMem( 8221 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8222 LocVT2, CCValAssign::Full)); 8223 } 8224 8225 return false; 8226 } 8227 8228 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8229 Optional<unsigned> FirstMaskArgument, 8230 CCState &State, const RISCVTargetLowering &TLI) { 8231 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8232 if (RC == &RISCV::VRRegClass) { 8233 // Assign the first mask argument to V0. 8234 // This is an interim calling convention and it may be changed in the 8235 // future. 8236 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8237 return State.AllocateReg(RISCV::V0); 8238 return State.AllocateReg(ArgVRs); 8239 } 8240 if (RC == &RISCV::VRM2RegClass) 8241 return State.AllocateReg(ArgVRM2s); 8242 if (RC == &RISCV::VRM4RegClass) 8243 return State.AllocateReg(ArgVRM4s); 8244 if (RC == &RISCV::VRM8RegClass) 8245 return State.AllocateReg(ArgVRM8s); 8246 llvm_unreachable("Unhandled register class for ValueType"); 8247 } 8248 8249 // Implements the RISC-V calling convention. Returns true upon failure. 8250 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8251 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8252 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8253 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8254 Optional<unsigned> FirstMaskArgument) { 8255 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8256 assert(XLen == 32 || XLen == 64); 8257 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8258 8259 // Any return value split in to more than two values can't be returned 8260 // directly. Vectors are returned via the available vector registers. 8261 if (!LocVT.isVector() && IsRet && ValNo > 1) 8262 return true; 8263 8264 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8265 // variadic argument, or if no F16/F32 argument registers are available. 8266 bool UseGPRForF16_F32 = true; 8267 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8268 // variadic argument, or if no F64 argument registers are available. 8269 bool UseGPRForF64 = true; 8270 8271 switch (ABI) { 8272 default: 8273 llvm_unreachable("Unexpected ABI"); 8274 case RISCVABI::ABI_ILP32: 8275 case RISCVABI::ABI_LP64: 8276 break; 8277 case RISCVABI::ABI_ILP32F: 8278 case RISCVABI::ABI_LP64F: 8279 UseGPRForF16_F32 = !IsFixed; 8280 break; 8281 case RISCVABI::ABI_ILP32D: 8282 case RISCVABI::ABI_LP64D: 8283 UseGPRForF16_F32 = !IsFixed; 8284 UseGPRForF64 = !IsFixed; 8285 break; 8286 } 8287 8288 // FPR16, FPR32, and FPR64 alias each other. 8289 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 8290 UseGPRForF16_F32 = true; 8291 UseGPRForF64 = true; 8292 } 8293 8294 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 8295 // similar local variables rather than directly checking against the target 8296 // ABI. 8297 8298 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 8299 LocVT = XLenVT; 8300 LocInfo = CCValAssign::BCvt; 8301 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 8302 LocVT = MVT::i64; 8303 LocInfo = CCValAssign::BCvt; 8304 } 8305 8306 // If this is a variadic argument, the RISC-V calling convention requires 8307 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 8308 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 8309 // be used regardless of whether the original argument was split during 8310 // legalisation or not. The argument will not be passed by registers if the 8311 // original type is larger than 2*XLEN, so the register alignment rule does 8312 // not apply. 8313 unsigned TwoXLenInBytes = (2 * XLen) / 8; 8314 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 8315 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 8316 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8317 // Skip 'odd' register if necessary. 8318 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8319 State.AllocateReg(ArgGPRs); 8320 } 8321 8322 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8323 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8324 State.getPendingArgFlags(); 8325 8326 assert(PendingLocs.size() == PendingArgFlags.size() && 8327 "PendingLocs and PendingArgFlags out of sync"); 8328 8329 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8330 // registers are exhausted. 8331 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8332 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8333 "Can't lower f64 if it is split"); 8334 // Depending on available argument GPRS, f64 may be passed in a pair of 8335 // GPRs, split between a GPR and the stack, or passed completely on the 8336 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8337 // cases. 8338 Register Reg = State.AllocateReg(ArgGPRs); 8339 LocVT = MVT::i32; 8340 if (!Reg) { 8341 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8342 State.addLoc( 8343 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8344 return false; 8345 } 8346 if (!State.AllocateReg(ArgGPRs)) 8347 State.AllocateStack(4, Align(4)); 8348 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8349 return false; 8350 } 8351 8352 // Fixed-length vectors are located in the corresponding scalable-vector 8353 // container types. 8354 if (ValVT.isFixedLengthVector()) 8355 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8356 8357 // Split arguments might be passed indirectly, so keep track of the pending 8358 // values. Split vectors are passed via a mix of registers and indirectly, so 8359 // treat them as we would any other argument. 8360 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8361 LocVT = XLenVT; 8362 LocInfo = CCValAssign::Indirect; 8363 PendingLocs.push_back( 8364 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8365 PendingArgFlags.push_back(ArgFlags); 8366 if (!ArgFlags.isSplitEnd()) { 8367 return false; 8368 } 8369 } 8370 8371 // If the split argument only had two elements, it should be passed directly 8372 // in registers or on the stack. 8373 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8374 PendingLocs.size() <= 2) { 8375 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8376 // Apply the normal calling convention rules to the first half of the 8377 // split argument. 8378 CCValAssign VA = PendingLocs[0]; 8379 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8380 PendingLocs.clear(); 8381 PendingArgFlags.clear(); 8382 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8383 ArgFlags); 8384 } 8385 8386 // Allocate to a register if possible, or else a stack slot. 8387 Register Reg; 8388 unsigned StoreSizeBytes = XLen / 8; 8389 Align StackAlign = Align(XLen / 8); 8390 8391 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8392 Reg = State.AllocateReg(ArgFPR16s); 8393 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8394 Reg = State.AllocateReg(ArgFPR32s); 8395 else if (ValVT == MVT::f64 && !UseGPRForF64) 8396 Reg = State.AllocateReg(ArgFPR64s); 8397 else if (ValVT.isVector()) { 8398 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8399 if (!Reg) { 8400 // For return values, the vector must be passed fully via registers or 8401 // via the stack. 8402 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8403 // but we're using all of them. 8404 if (IsRet) 8405 return true; 8406 // Try using a GPR to pass the address 8407 if ((Reg = State.AllocateReg(ArgGPRs))) { 8408 LocVT = XLenVT; 8409 LocInfo = CCValAssign::Indirect; 8410 } else if (ValVT.isScalableVector()) { 8411 LocVT = XLenVT; 8412 LocInfo = CCValAssign::Indirect; 8413 } else { 8414 // Pass fixed-length vectors on the stack. 8415 LocVT = ValVT; 8416 StoreSizeBytes = ValVT.getStoreSize(); 8417 // Align vectors to their element sizes, being careful for vXi1 8418 // vectors. 8419 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8420 } 8421 } 8422 } else { 8423 Reg = State.AllocateReg(ArgGPRs); 8424 } 8425 8426 unsigned StackOffset = 8427 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8428 8429 // If we reach this point and PendingLocs is non-empty, we must be at the 8430 // end of a split argument that must be passed indirectly. 8431 if (!PendingLocs.empty()) { 8432 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8433 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8434 8435 for (auto &It : PendingLocs) { 8436 if (Reg) 8437 It.convertToReg(Reg); 8438 else 8439 It.convertToMem(StackOffset); 8440 State.addLoc(It); 8441 } 8442 PendingLocs.clear(); 8443 PendingArgFlags.clear(); 8444 return false; 8445 } 8446 8447 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8448 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8449 "Expected an XLenVT or vector types at this stage"); 8450 8451 if (Reg) { 8452 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8453 return false; 8454 } 8455 8456 // When a floating-point value is passed on the stack, no bit-conversion is 8457 // needed. 8458 if (ValVT.isFloatingPoint()) { 8459 LocVT = ValVT; 8460 LocInfo = CCValAssign::Full; 8461 } 8462 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8463 return false; 8464 } 8465 8466 template <typename ArgTy> 8467 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8468 for (const auto &ArgIdx : enumerate(Args)) { 8469 MVT ArgVT = ArgIdx.value().VT; 8470 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8471 return ArgIdx.index(); 8472 } 8473 return None; 8474 } 8475 8476 void RISCVTargetLowering::analyzeInputArgs( 8477 MachineFunction &MF, CCState &CCInfo, 8478 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8479 RISCVCCAssignFn Fn) const { 8480 unsigned NumArgs = Ins.size(); 8481 FunctionType *FType = MF.getFunction().getFunctionType(); 8482 8483 Optional<unsigned> FirstMaskArgument; 8484 if (Subtarget.hasVInstructions()) 8485 FirstMaskArgument = preAssignMask(Ins); 8486 8487 for (unsigned i = 0; i != NumArgs; ++i) { 8488 MVT ArgVT = Ins[i].VT; 8489 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 8490 8491 Type *ArgTy = nullptr; 8492 if (IsRet) 8493 ArgTy = FType->getReturnType(); 8494 else if (Ins[i].isOrigArg()) 8495 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 8496 8497 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8498 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8499 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 8500 FirstMaskArgument)) { 8501 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 8502 << EVT(ArgVT).getEVTString() << '\n'); 8503 llvm_unreachable(nullptr); 8504 } 8505 } 8506 } 8507 8508 void RISCVTargetLowering::analyzeOutputArgs( 8509 MachineFunction &MF, CCState &CCInfo, 8510 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 8511 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 8512 unsigned NumArgs = Outs.size(); 8513 8514 Optional<unsigned> FirstMaskArgument; 8515 if (Subtarget.hasVInstructions()) 8516 FirstMaskArgument = preAssignMask(Outs); 8517 8518 for (unsigned i = 0; i != NumArgs; i++) { 8519 MVT ArgVT = Outs[i].VT; 8520 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 8521 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 8522 8523 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 8524 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 8525 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 8526 FirstMaskArgument)) { 8527 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 8528 << EVT(ArgVT).getEVTString() << "\n"); 8529 llvm_unreachable(nullptr); 8530 } 8531 } 8532 } 8533 8534 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 8535 // values. 8536 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 8537 const CCValAssign &VA, const SDLoc &DL, 8538 const RISCVSubtarget &Subtarget) { 8539 switch (VA.getLocInfo()) { 8540 default: 8541 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8542 case CCValAssign::Full: 8543 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 8544 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 8545 break; 8546 case CCValAssign::BCvt: 8547 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8548 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 8549 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8550 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 8551 else 8552 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 8553 break; 8554 } 8555 return Val; 8556 } 8557 8558 // The caller is responsible for loading the full value if the argument is 8559 // passed with CCValAssign::Indirect. 8560 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 8561 const CCValAssign &VA, const SDLoc &DL, 8562 const RISCVTargetLowering &TLI) { 8563 MachineFunction &MF = DAG.getMachineFunction(); 8564 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8565 EVT LocVT = VA.getLocVT(); 8566 SDValue Val; 8567 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 8568 Register VReg = RegInfo.createVirtualRegister(RC); 8569 RegInfo.addLiveIn(VA.getLocReg(), VReg); 8570 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 8571 8572 if (VA.getLocInfo() == CCValAssign::Indirect) 8573 return Val; 8574 8575 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 8576 } 8577 8578 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 8579 const CCValAssign &VA, const SDLoc &DL, 8580 const RISCVSubtarget &Subtarget) { 8581 EVT LocVT = VA.getLocVT(); 8582 8583 switch (VA.getLocInfo()) { 8584 default: 8585 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8586 case CCValAssign::Full: 8587 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 8588 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 8589 break; 8590 case CCValAssign::BCvt: 8591 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 8592 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 8593 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 8594 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 8595 else 8596 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 8597 break; 8598 } 8599 return Val; 8600 } 8601 8602 // The caller is responsible for loading the full value if the argument is 8603 // passed with CCValAssign::Indirect. 8604 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 8605 const CCValAssign &VA, const SDLoc &DL) { 8606 MachineFunction &MF = DAG.getMachineFunction(); 8607 MachineFrameInfo &MFI = MF.getFrameInfo(); 8608 EVT LocVT = VA.getLocVT(); 8609 EVT ValVT = VA.getValVT(); 8610 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 8611 if (ValVT.isScalableVector()) { 8612 // When the value is a scalable vector, we save the pointer which points to 8613 // the scalable vector value in the stack. The ValVT will be the pointer 8614 // type, instead of the scalable vector type. 8615 ValVT = LocVT; 8616 } 8617 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 8618 /*Immutable=*/true); 8619 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 8620 SDValue Val; 8621 8622 ISD::LoadExtType ExtType; 8623 switch (VA.getLocInfo()) { 8624 default: 8625 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 8626 case CCValAssign::Full: 8627 case CCValAssign::Indirect: 8628 case CCValAssign::BCvt: 8629 ExtType = ISD::NON_EXTLOAD; 8630 break; 8631 } 8632 Val = DAG.getExtLoad( 8633 ExtType, DL, LocVT, Chain, FIN, 8634 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 8635 return Val; 8636 } 8637 8638 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 8639 const CCValAssign &VA, const SDLoc &DL) { 8640 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 8641 "Unexpected VA"); 8642 MachineFunction &MF = DAG.getMachineFunction(); 8643 MachineFrameInfo &MFI = MF.getFrameInfo(); 8644 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8645 8646 if (VA.isMemLoc()) { 8647 // f64 is passed on the stack. 8648 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 8649 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8650 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 8651 MachinePointerInfo::getFixedStack(MF, FI)); 8652 } 8653 8654 assert(VA.isRegLoc() && "Expected register VA assignment"); 8655 8656 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8657 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 8658 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 8659 SDValue Hi; 8660 if (VA.getLocReg() == RISCV::X17) { 8661 // Second half of f64 is passed on the stack. 8662 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 8663 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 8664 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 8665 MachinePointerInfo::getFixedStack(MF, FI)); 8666 } else { 8667 // Second half of f64 is passed in another GPR. 8668 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8669 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 8670 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 8671 } 8672 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 8673 } 8674 8675 // FastCC has less than 1% performance improvement for some particular 8676 // benchmark. But theoretically, it may has benenfit for some cases. 8677 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 8678 unsigned ValNo, MVT ValVT, MVT LocVT, 8679 CCValAssign::LocInfo LocInfo, 8680 ISD::ArgFlagsTy ArgFlags, CCState &State, 8681 bool IsFixed, bool IsRet, Type *OrigTy, 8682 const RISCVTargetLowering &TLI, 8683 Optional<unsigned> FirstMaskArgument) { 8684 8685 // X5 and X6 might be used for save-restore libcall. 8686 static const MCPhysReg GPRList[] = { 8687 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 8688 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 8689 RISCV::X29, RISCV::X30, RISCV::X31}; 8690 8691 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8692 if (unsigned Reg = State.AllocateReg(GPRList)) { 8693 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8694 return false; 8695 } 8696 } 8697 8698 if (LocVT == MVT::f16) { 8699 static const MCPhysReg FPR16List[] = { 8700 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 8701 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 8702 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 8703 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 8704 if (unsigned Reg = State.AllocateReg(FPR16List)) { 8705 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8706 return false; 8707 } 8708 } 8709 8710 if (LocVT == MVT::f32) { 8711 static const MCPhysReg FPR32List[] = { 8712 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 8713 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 8714 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 8715 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 8716 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8717 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8718 return false; 8719 } 8720 } 8721 8722 if (LocVT == MVT::f64) { 8723 static const MCPhysReg FPR64List[] = { 8724 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 8725 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 8726 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 8727 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 8728 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8729 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8730 return false; 8731 } 8732 } 8733 8734 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 8735 unsigned Offset4 = State.AllocateStack(4, Align(4)); 8736 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 8737 return false; 8738 } 8739 8740 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 8741 unsigned Offset5 = State.AllocateStack(8, Align(8)); 8742 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 8743 return false; 8744 } 8745 8746 if (LocVT.isVector()) { 8747 if (unsigned Reg = 8748 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 8749 // Fixed-length vectors are located in the corresponding scalable-vector 8750 // container types. 8751 if (ValVT.isFixedLengthVector()) 8752 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8753 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8754 } else { 8755 // Try and pass the address via a "fast" GPR. 8756 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 8757 LocInfo = CCValAssign::Indirect; 8758 LocVT = TLI.getSubtarget().getXLenVT(); 8759 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 8760 } else if (ValVT.isFixedLengthVector()) { 8761 auto StackAlign = 8762 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8763 unsigned StackOffset = 8764 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 8765 State.addLoc( 8766 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8767 } else { 8768 // Can't pass scalable vectors on the stack. 8769 return true; 8770 } 8771 } 8772 8773 return false; 8774 } 8775 8776 return true; // CC didn't match. 8777 } 8778 8779 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 8780 CCValAssign::LocInfo LocInfo, 8781 ISD::ArgFlagsTy ArgFlags, CCState &State) { 8782 8783 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 8784 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 8785 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 8786 static const MCPhysReg GPRList[] = { 8787 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 8788 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 8789 if (unsigned Reg = State.AllocateReg(GPRList)) { 8790 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8791 return false; 8792 } 8793 } 8794 8795 if (LocVT == MVT::f32) { 8796 // Pass in STG registers: F1, ..., F6 8797 // fs0 ... fs5 8798 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 8799 RISCV::F18_F, RISCV::F19_F, 8800 RISCV::F20_F, RISCV::F21_F}; 8801 if (unsigned Reg = State.AllocateReg(FPR32List)) { 8802 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8803 return false; 8804 } 8805 } 8806 8807 if (LocVT == MVT::f64) { 8808 // Pass in STG registers: D1, ..., D6 8809 // fs6 ... fs11 8810 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 8811 RISCV::F24_D, RISCV::F25_D, 8812 RISCV::F26_D, RISCV::F27_D}; 8813 if (unsigned Reg = State.AllocateReg(FPR64List)) { 8814 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8815 return false; 8816 } 8817 } 8818 8819 report_fatal_error("No registers left in GHC calling convention"); 8820 return true; 8821 } 8822 8823 // Transform physical registers into virtual registers. 8824 SDValue RISCVTargetLowering::LowerFormalArguments( 8825 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 8826 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 8827 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 8828 8829 MachineFunction &MF = DAG.getMachineFunction(); 8830 8831 switch (CallConv) { 8832 default: 8833 report_fatal_error("Unsupported calling convention"); 8834 case CallingConv::C: 8835 case CallingConv::Fast: 8836 break; 8837 case CallingConv::GHC: 8838 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 8839 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 8840 report_fatal_error( 8841 "GHC calling convention requires the F and D instruction set extensions"); 8842 } 8843 8844 const Function &Func = MF.getFunction(); 8845 if (Func.hasFnAttribute("interrupt")) { 8846 if (!Func.arg_empty()) 8847 report_fatal_error( 8848 "Functions with the interrupt attribute cannot have arguments!"); 8849 8850 StringRef Kind = 8851 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 8852 8853 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 8854 report_fatal_error( 8855 "Function interrupt attribute argument not supported!"); 8856 } 8857 8858 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8859 MVT XLenVT = Subtarget.getXLenVT(); 8860 unsigned XLenInBytes = Subtarget.getXLen() / 8; 8861 // Used with vargs to acumulate store chains. 8862 std::vector<SDValue> OutChains; 8863 8864 // Assign locations to all of the incoming arguments. 8865 SmallVector<CCValAssign, 16> ArgLocs; 8866 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 8867 8868 if (CallConv == CallingConv::GHC) 8869 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 8870 else 8871 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 8872 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 8873 : CC_RISCV); 8874 8875 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 8876 CCValAssign &VA = ArgLocs[i]; 8877 SDValue ArgValue; 8878 // Passing f64 on RV32D with a soft float ABI must be handled as a special 8879 // case. 8880 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 8881 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 8882 else if (VA.isRegLoc()) 8883 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 8884 else 8885 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 8886 8887 if (VA.getLocInfo() == CCValAssign::Indirect) { 8888 // If the original argument was split and passed by reference (e.g. i128 8889 // on RV32), we need to load all parts of it here (using the same 8890 // address). Vectors may be partly split to registers and partly to the 8891 // stack, in which case the base address is partly offset and subsequent 8892 // stores are relative to that. 8893 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 8894 MachinePointerInfo())); 8895 unsigned ArgIndex = Ins[i].OrigArgIndex; 8896 unsigned ArgPartOffset = Ins[i].PartOffset; 8897 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 8898 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 8899 CCValAssign &PartVA = ArgLocs[i + 1]; 8900 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 8901 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 8902 if (PartVA.getValVT().isScalableVector()) 8903 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 8904 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 8905 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 8906 MachinePointerInfo())); 8907 ++i; 8908 } 8909 continue; 8910 } 8911 InVals.push_back(ArgValue); 8912 } 8913 8914 if (IsVarArg) { 8915 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 8916 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 8917 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 8918 MachineFrameInfo &MFI = MF.getFrameInfo(); 8919 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8920 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 8921 8922 // Offset of the first variable argument from stack pointer, and size of 8923 // the vararg save area. For now, the varargs save area is either zero or 8924 // large enough to hold a0-a7. 8925 int VaArgOffset, VarArgsSaveSize; 8926 8927 // If all registers are allocated, then all varargs must be passed on the 8928 // stack and we don't need to save any argregs. 8929 if (ArgRegs.size() == Idx) { 8930 VaArgOffset = CCInfo.getNextStackOffset(); 8931 VarArgsSaveSize = 0; 8932 } else { 8933 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 8934 VaArgOffset = -VarArgsSaveSize; 8935 } 8936 8937 // Record the frame index of the first variable argument 8938 // which is a value necessary to VASTART. 8939 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8940 RVFI->setVarArgsFrameIndex(FI); 8941 8942 // If saving an odd number of registers then create an extra stack slot to 8943 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 8944 // offsets to even-numbered registered remain 2*XLEN-aligned. 8945 if (Idx % 2) { 8946 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 8947 VarArgsSaveSize += XLenInBytes; 8948 } 8949 8950 // Copy the integer registers that may have been used for passing varargs 8951 // to the vararg save area. 8952 for (unsigned I = Idx; I < ArgRegs.size(); 8953 ++I, VaArgOffset += XLenInBytes) { 8954 const Register Reg = RegInfo.createVirtualRegister(RC); 8955 RegInfo.addLiveIn(ArgRegs[I], Reg); 8956 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 8957 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 8958 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 8959 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 8960 MachinePointerInfo::getFixedStack(MF, FI)); 8961 cast<StoreSDNode>(Store.getNode()) 8962 ->getMemOperand() 8963 ->setValue((Value *)nullptr); 8964 OutChains.push_back(Store); 8965 } 8966 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 8967 } 8968 8969 // All stores are grouped in one node to allow the matching between 8970 // the size of Ins and InVals. This only happens for vararg functions. 8971 if (!OutChains.empty()) { 8972 OutChains.push_back(Chain); 8973 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 8974 } 8975 8976 return Chain; 8977 } 8978 8979 /// isEligibleForTailCallOptimization - Check whether the call is eligible 8980 /// for tail call optimization. 8981 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 8982 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 8983 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 8984 const SmallVector<CCValAssign, 16> &ArgLocs) const { 8985 8986 auto &Callee = CLI.Callee; 8987 auto CalleeCC = CLI.CallConv; 8988 auto &Outs = CLI.Outs; 8989 auto &Caller = MF.getFunction(); 8990 auto CallerCC = Caller.getCallingConv(); 8991 8992 // Exception-handling functions need a special set of instructions to 8993 // indicate a return to the hardware. Tail-calling another function would 8994 // probably break this. 8995 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 8996 // should be expanded as new function attributes are introduced. 8997 if (Caller.hasFnAttribute("interrupt")) 8998 return false; 8999 9000 // Do not tail call opt if the stack is used to pass parameters. 9001 if (CCInfo.getNextStackOffset() != 0) 9002 return false; 9003 9004 // Do not tail call opt if any parameters need to be passed indirectly. 9005 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 9006 // passed indirectly. So the address of the value will be passed in a 9007 // register, or if not available, then the address is put on the stack. In 9008 // order to pass indirectly, space on the stack often needs to be allocated 9009 // in order to store the value. In this case the CCInfo.getNextStackOffset() 9010 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 9011 // are passed CCValAssign::Indirect. 9012 for (auto &VA : ArgLocs) 9013 if (VA.getLocInfo() == CCValAssign::Indirect) 9014 return false; 9015 9016 // Do not tail call opt if either caller or callee uses struct return 9017 // semantics. 9018 auto IsCallerStructRet = Caller.hasStructRetAttr(); 9019 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 9020 if (IsCallerStructRet || IsCalleeStructRet) 9021 return false; 9022 9023 // Externally-defined functions with weak linkage should not be 9024 // tail-called. The behaviour of branch instructions in this situation (as 9025 // used for tail calls) is implementation-defined, so we cannot rely on the 9026 // linker replacing the tail call with a return. 9027 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 9028 const GlobalValue *GV = G->getGlobal(); 9029 if (GV->hasExternalWeakLinkage()) 9030 return false; 9031 } 9032 9033 // The callee has to preserve all registers the caller needs to preserve. 9034 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9035 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 9036 if (CalleeCC != CallerCC) { 9037 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 9038 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 9039 return false; 9040 } 9041 9042 // Byval parameters hand the function a pointer directly into the stack area 9043 // we want to reuse during a tail call. Working around this *is* possible 9044 // but less efficient and uglier in LowerCall. 9045 for (auto &Arg : Outs) 9046 if (Arg.Flags.isByVal()) 9047 return false; 9048 9049 return true; 9050 } 9051 9052 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 9053 return DAG.getDataLayout().getPrefTypeAlign( 9054 VT.getTypeForEVT(*DAG.getContext())); 9055 } 9056 9057 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 9058 // and output parameter nodes. 9059 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 9060 SmallVectorImpl<SDValue> &InVals) const { 9061 SelectionDAG &DAG = CLI.DAG; 9062 SDLoc &DL = CLI.DL; 9063 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 9064 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 9065 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 9066 SDValue Chain = CLI.Chain; 9067 SDValue Callee = CLI.Callee; 9068 bool &IsTailCall = CLI.IsTailCall; 9069 CallingConv::ID CallConv = CLI.CallConv; 9070 bool IsVarArg = CLI.IsVarArg; 9071 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9072 MVT XLenVT = Subtarget.getXLenVT(); 9073 9074 MachineFunction &MF = DAG.getMachineFunction(); 9075 9076 // Analyze the operands of the call, assigning locations to each operand. 9077 SmallVector<CCValAssign, 16> ArgLocs; 9078 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9079 9080 if (CallConv == CallingConv::GHC) 9081 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 9082 else 9083 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 9084 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9085 : CC_RISCV); 9086 9087 // Check if it's really possible to do a tail call. 9088 if (IsTailCall) 9089 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 9090 9091 if (IsTailCall) 9092 ++NumTailCalls; 9093 else if (CLI.CB && CLI.CB->isMustTailCall()) 9094 report_fatal_error("failed to perform tail call elimination on a call " 9095 "site marked musttail"); 9096 9097 // Get a count of how many bytes are to be pushed on the stack. 9098 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 9099 9100 // Create local copies for byval args 9101 SmallVector<SDValue, 8> ByValArgs; 9102 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9103 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9104 if (!Flags.isByVal()) 9105 continue; 9106 9107 SDValue Arg = OutVals[i]; 9108 unsigned Size = Flags.getByValSize(); 9109 Align Alignment = Flags.getNonZeroByValAlign(); 9110 9111 int FI = 9112 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 9113 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9114 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 9115 9116 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 9117 /*IsVolatile=*/false, 9118 /*AlwaysInline=*/false, IsTailCall, 9119 MachinePointerInfo(), MachinePointerInfo()); 9120 ByValArgs.push_back(FIPtr); 9121 } 9122 9123 if (!IsTailCall) 9124 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 9125 9126 // Copy argument values to their designated locations. 9127 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 9128 SmallVector<SDValue, 8> MemOpChains; 9129 SDValue StackPtr; 9130 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 9131 CCValAssign &VA = ArgLocs[i]; 9132 SDValue ArgValue = OutVals[i]; 9133 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9134 9135 // Handle passing f64 on RV32D with a soft float ABI as a special case. 9136 bool IsF64OnRV32DSoftABI = 9137 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 9138 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 9139 SDValue SplitF64 = DAG.getNode( 9140 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 9141 SDValue Lo = SplitF64.getValue(0); 9142 SDValue Hi = SplitF64.getValue(1); 9143 9144 Register RegLo = VA.getLocReg(); 9145 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 9146 9147 if (RegLo == RISCV::X17) { 9148 // Second half of f64 is passed on the stack. 9149 // Work out the address of the stack slot. 9150 if (!StackPtr.getNode()) 9151 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9152 // Emit the store. 9153 MemOpChains.push_back( 9154 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 9155 } else { 9156 // Second half of f64 is passed in another GPR. 9157 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9158 Register RegHigh = RegLo + 1; 9159 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 9160 } 9161 continue; 9162 } 9163 9164 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 9165 // as any other MemLoc. 9166 9167 // Promote the value if needed. 9168 // For now, only handle fully promoted and indirect arguments. 9169 if (VA.getLocInfo() == CCValAssign::Indirect) { 9170 // Store the argument in a stack slot and pass its address. 9171 Align StackAlign = 9172 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 9173 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 9174 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 9175 // If the original argument was split (e.g. i128), we need 9176 // to store the required parts of it here (and pass just one address). 9177 // Vectors may be partly split to registers and partly to the stack, in 9178 // which case the base address is partly offset and subsequent stores are 9179 // relative to that. 9180 unsigned ArgIndex = Outs[i].OrigArgIndex; 9181 unsigned ArgPartOffset = Outs[i].PartOffset; 9182 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9183 // Calculate the total size to store. We don't have access to what we're 9184 // actually storing other than performing the loop and collecting the 9185 // info. 9186 SmallVector<std::pair<SDValue, SDValue>> Parts; 9187 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 9188 SDValue PartValue = OutVals[i + 1]; 9189 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 9190 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9191 EVT PartVT = PartValue.getValueType(); 9192 if (PartVT.isScalableVector()) 9193 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9194 StoredSize += PartVT.getStoreSize(); 9195 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 9196 Parts.push_back(std::make_pair(PartValue, Offset)); 9197 ++i; 9198 } 9199 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 9200 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 9201 MemOpChains.push_back( 9202 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 9203 MachinePointerInfo::getFixedStack(MF, FI))); 9204 for (const auto &Part : Parts) { 9205 SDValue PartValue = Part.first; 9206 SDValue PartOffset = Part.second; 9207 SDValue Address = 9208 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 9209 MemOpChains.push_back( 9210 DAG.getStore(Chain, DL, PartValue, Address, 9211 MachinePointerInfo::getFixedStack(MF, FI))); 9212 } 9213 ArgValue = SpillSlot; 9214 } else { 9215 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 9216 } 9217 9218 // Use local copy if it is a byval arg. 9219 if (Flags.isByVal()) 9220 ArgValue = ByValArgs[j++]; 9221 9222 if (VA.isRegLoc()) { 9223 // Queue up the argument copies and emit them at the end. 9224 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 9225 } else { 9226 assert(VA.isMemLoc() && "Argument not register or memory"); 9227 assert(!IsTailCall && "Tail call not allowed if stack is used " 9228 "for passing parameters"); 9229 9230 // Work out the address of the stack slot. 9231 if (!StackPtr.getNode()) 9232 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9233 SDValue Address = 9234 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9235 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9236 9237 // Emit the store. 9238 MemOpChains.push_back( 9239 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9240 } 9241 } 9242 9243 // Join the stores, which are independent of one another. 9244 if (!MemOpChains.empty()) 9245 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9246 9247 SDValue Glue; 9248 9249 // Build a sequence of copy-to-reg nodes, chained and glued together. 9250 for (auto &Reg : RegsToPass) { 9251 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9252 Glue = Chain.getValue(1); 9253 } 9254 9255 // Validate that none of the argument registers have been marked as 9256 // reserved, if so report an error. Do the same for the return address if this 9257 // is not a tailcall. 9258 validateCCReservedRegs(RegsToPass, MF); 9259 if (!IsTailCall && 9260 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9261 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9262 MF.getFunction(), 9263 "Return address register required, but has been reserved."}); 9264 9265 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9266 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9267 // split it and then direct call can be matched by PseudoCALL. 9268 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 9269 const GlobalValue *GV = S->getGlobal(); 9270 9271 unsigned OpFlags = RISCVII::MO_CALL; 9272 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 9273 OpFlags = RISCVII::MO_PLT; 9274 9275 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 9276 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 9277 unsigned OpFlags = RISCVII::MO_CALL; 9278 9279 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 9280 nullptr)) 9281 OpFlags = RISCVII::MO_PLT; 9282 9283 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 9284 } 9285 9286 // The first call operand is the chain and the second is the target address. 9287 SmallVector<SDValue, 8> Ops; 9288 Ops.push_back(Chain); 9289 Ops.push_back(Callee); 9290 9291 // Add argument registers to the end of the list so that they are 9292 // known live into the call. 9293 for (auto &Reg : RegsToPass) 9294 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 9295 9296 if (!IsTailCall) { 9297 // Add a register mask operand representing the call-preserved registers. 9298 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9299 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 9300 assert(Mask && "Missing call preserved mask for calling convention"); 9301 Ops.push_back(DAG.getRegisterMask(Mask)); 9302 } 9303 9304 // Glue the call to the argument copies, if any. 9305 if (Glue.getNode()) 9306 Ops.push_back(Glue); 9307 9308 // Emit the call. 9309 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9310 9311 if (IsTailCall) { 9312 MF.getFrameInfo().setHasTailCall(); 9313 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 9314 } 9315 9316 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 9317 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 9318 Glue = Chain.getValue(1); 9319 9320 // Mark the end of the call, which is glued to the call itself. 9321 Chain = DAG.getCALLSEQ_END(Chain, 9322 DAG.getConstant(NumBytes, DL, PtrVT, true), 9323 DAG.getConstant(0, DL, PtrVT, true), 9324 Glue, DL); 9325 Glue = Chain.getValue(1); 9326 9327 // Assign locations to each value returned by this call. 9328 SmallVector<CCValAssign, 16> RVLocs; 9329 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9330 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9331 9332 // Copy all of the result registers out of their specified physreg. 9333 for (auto &VA : RVLocs) { 9334 // Copy the value out 9335 SDValue RetValue = 9336 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9337 // Glue the RetValue to the end of the call sequence 9338 Chain = RetValue.getValue(1); 9339 Glue = RetValue.getValue(2); 9340 9341 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9342 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9343 SDValue RetValue2 = 9344 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9345 Chain = RetValue2.getValue(1); 9346 Glue = RetValue2.getValue(2); 9347 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9348 RetValue2); 9349 } 9350 9351 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9352 9353 InVals.push_back(RetValue); 9354 } 9355 9356 return Chain; 9357 } 9358 9359 bool RISCVTargetLowering::CanLowerReturn( 9360 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9361 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9362 SmallVector<CCValAssign, 16> RVLocs; 9363 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9364 9365 Optional<unsigned> FirstMaskArgument; 9366 if (Subtarget.hasVInstructions()) 9367 FirstMaskArgument = preAssignMask(Outs); 9368 9369 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9370 MVT VT = Outs[i].VT; 9371 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9372 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9373 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9374 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9375 *this, FirstMaskArgument)) 9376 return false; 9377 } 9378 return true; 9379 } 9380 9381 SDValue 9382 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9383 bool IsVarArg, 9384 const SmallVectorImpl<ISD::OutputArg> &Outs, 9385 const SmallVectorImpl<SDValue> &OutVals, 9386 const SDLoc &DL, SelectionDAG &DAG) const { 9387 const MachineFunction &MF = DAG.getMachineFunction(); 9388 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9389 9390 // Stores the assignment of the return value to a location. 9391 SmallVector<CCValAssign, 16> RVLocs; 9392 9393 // Info about the registers and stack slot. 9394 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9395 *DAG.getContext()); 9396 9397 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9398 nullptr, CC_RISCV); 9399 9400 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9401 report_fatal_error("GHC functions return void only"); 9402 9403 SDValue Glue; 9404 SmallVector<SDValue, 4> RetOps(1, Chain); 9405 9406 // Copy the result values into the output registers. 9407 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9408 SDValue Val = OutVals[i]; 9409 CCValAssign &VA = RVLocs[i]; 9410 assert(VA.isRegLoc() && "Can only return in registers!"); 9411 9412 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9413 // Handle returning f64 on RV32D with a soft float ABI. 9414 assert(VA.isRegLoc() && "Expected return via registers"); 9415 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9416 DAG.getVTList(MVT::i32, MVT::i32), Val); 9417 SDValue Lo = SplitF64.getValue(0); 9418 SDValue Hi = SplitF64.getValue(1); 9419 Register RegLo = VA.getLocReg(); 9420 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9421 Register RegHi = RegLo + 1; 9422 9423 if (STI.isRegisterReservedByUser(RegLo) || 9424 STI.isRegisterReservedByUser(RegHi)) 9425 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9426 MF.getFunction(), 9427 "Return value register required, but has been reserved."}); 9428 9429 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9430 Glue = Chain.getValue(1); 9431 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9432 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9433 Glue = Chain.getValue(1); 9434 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9435 } else { 9436 // Handle a 'normal' return. 9437 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9438 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9439 9440 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9441 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9442 MF.getFunction(), 9443 "Return value register required, but has been reserved."}); 9444 9445 // Guarantee that all emitted copies are stuck together. 9446 Glue = Chain.getValue(1); 9447 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9448 } 9449 } 9450 9451 RetOps[0] = Chain; // Update chain. 9452 9453 // Add the glue node if we have it. 9454 if (Glue.getNode()) { 9455 RetOps.push_back(Glue); 9456 } 9457 9458 unsigned RetOpc = RISCVISD::RET_FLAG; 9459 // Interrupt service routines use different return instructions. 9460 const Function &Func = DAG.getMachineFunction().getFunction(); 9461 if (Func.hasFnAttribute("interrupt")) { 9462 if (!Func.getReturnType()->isVoidTy()) 9463 report_fatal_error( 9464 "Functions with the interrupt attribute must have void return type!"); 9465 9466 MachineFunction &MF = DAG.getMachineFunction(); 9467 StringRef Kind = 9468 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9469 9470 if (Kind == "user") 9471 RetOpc = RISCVISD::URET_FLAG; 9472 else if (Kind == "supervisor") 9473 RetOpc = RISCVISD::SRET_FLAG; 9474 else 9475 RetOpc = RISCVISD::MRET_FLAG; 9476 } 9477 9478 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9479 } 9480 9481 void RISCVTargetLowering::validateCCReservedRegs( 9482 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 9483 MachineFunction &MF) const { 9484 const Function &F = MF.getFunction(); 9485 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9486 9487 if (llvm::any_of(Regs, [&STI](auto Reg) { 9488 return STI.isRegisterReservedByUser(Reg.first); 9489 })) 9490 F.getContext().diagnose(DiagnosticInfoUnsupported{ 9491 F, "Argument register required, but has been reserved."}); 9492 } 9493 9494 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 9495 return CI->isTailCall(); 9496 } 9497 9498 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 9499 #define NODE_NAME_CASE(NODE) \ 9500 case RISCVISD::NODE: \ 9501 return "RISCVISD::" #NODE; 9502 // clang-format off 9503 switch ((RISCVISD::NodeType)Opcode) { 9504 case RISCVISD::FIRST_NUMBER: 9505 break; 9506 NODE_NAME_CASE(RET_FLAG) 9507 NODE_NAME_CASE(URET_FLAG) 9508 NODE_NAME_CASE(SRET_FLAG) 9509 NODE_NAME_CASE(MRET_FLAG) 9510 NODE_NAME_CASE(CALL) 9511 NODE_NAME_CASE(SELECT_CC) 9512 NODE_NAME_CASE(BR_CC) 9513 NODE_NAME_CASE(BuildPairF64) 9514 NODE_NAME_CASE(SplitF64) 9515 NODE_NAME_CASE(TAIL) 9516 NODE_NAME_CASE(MULHSU) 9517 NODE_NAME_CASE(SLLW) 9518 NODE_NAME_CASE(SRAW) 9519 NODE_NAME_CASE(SRLW) 9520 NODE_NAME_CASE(DIVW) 9521 NODE_NAME_CASE(DIVUW) 9522 NODE_NAME_CASE(REMUW) 9523 NODE_NAME_CASE(ROLW) 9524 NODE_NAME_CASE(RORW) 9525 NODE_NAME_CASE(CLZW) 9526 NODE_NAME_CASE(CTZW) 9527 NODE_NAME_CASE(FSLW) 9528 NODE_NAME_CASE(FSRW) 9529 NODE_NAME_CASE(FSL) 9530 NODE_NAME_CASE(FSR) 9531 NODE_NAME_CASE(FMV_H_X) 9532 NODE_NAME_CASE(FMV_X_ANYEXTH) 9533 NODE_NAME_CASE(FMV_W_X_RV64) 9534 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 9535 NODE_NAME_CASE(FCVT_X_RTZ) 9536 NODE_NAME_CASE(FCVT_XU_RTZ) 9537 NODE_NAME_CASE(FCVT_W_RTZ_RV64) 9538 NODE_NAME_CASE(FCVT_WU_RTZ_RV64) 9539 NODE_NAME_CASE(STRICT_FCVT_W_RTZ_RV64) 9540 NODE_NAME_CASE(STRICT_FCVT_WU_RTZ_RV64) 9541 NODE_NAME_CASE(READ_CYCLE_WIDE) 9542 NODE_NAME_CASE(GREV) 9543 NODE_NAME_CASE(GREVW) 9544 NODE_NAME_CASE(GORC) 9545 NODE_NAME_CASE(GORCW) 9546 NODE_NAME_CASE(SHFL) 9547 NODE_NAME_CASE(SHFLW) 9548 NODE_NAME_CASE(UNSHFL) 9549 NODE_NAME_CASE(UNSHFLW) 9550 NODE_NAME_CASE(BCOMPRESS) 9551 NODE_NAME_CASE(BCOMPRESSW) 9552 NODE_NAME_CASE(BDECOMPRESS) 9553 NODE_NAME_CASE(BDECOMPRESSW) 9554 NODE_NAME_CASE(VMV_V_X_VL) 9555 NODE_NAME_CASE(VFMV_V_F_VL) 9556 NODE_NAME_CASE(VMV_X_S) 9557 NODE_NAME_CASE(VMV_S_X_VL) 9558 NODE_NAME_CASE(VFMV_S_F_VL) 9559 NODE_NAME_CASE(SPLAT_VECTOR_I64) 9560 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 9561 NODE_NAME_CASE(READ_VLENB) 9562 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 9563 NODE_NAME_CASE(VSLIDEUP_VL) 9564 NODE_NAME_CASE(VSLIDE1UP_VL) 9565 NODE_NAME_CASE(VSLIDEDOWN_VL) 9566 NODE_NAME_CASE(VSLIDE1DOWN_VL) 9567 NODE_NAME_CASE(VID_VL) 9568 NODE_NAME_CASE(VFNCVT_ROD_VL) 9569 NODE_NAME_CASE(VECREDUCE_ADD_VL) 9570 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 9571 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 9572 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 9573 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 9574 NODE_NAME_CASE(VECREDUCE_AND_VL) 9575 NODE_NAME_CASE(VECREDUCE_OR_VL) 9576 NODE_NAME_CASE(VECREDUCE_XOR_VL) 9577 NODE_NAME_CASE(VECREDUCE_FADD_VL) 9578 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 9579 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 9580 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 9581 NODE_NAME_CASE(ADD_VL) 9582 NODE_NAME_CASE(AND_VL) 9583 NODE_NAME_CASE(MUL_VL) 9584 NODE_NAME_CASE(OR_VL) 9585 NODE_NAME_CASE(SDIV_VL) 9586 NODE_NAME_CASE(SHL_VL) 9587 NODE_NAME_CASE(SREM_VL) 9588 NODE_NAME_CASE(SRA_VL) 9589 NODE_NAME_CASE(SRL_VL) 9590 NODE_NAME_CASE(SUB_VL) 9591 NODE_NAME_CASE(UDIV_VL) 9592 NODE_NAME_CASE(UREM_VL) 9593 NODE_NAME_CASE(XOR_VL) 9594 NODE_NAME_CASE(SADDSAT_VL) 9595 NODE_NAME_CASE(UADDSAT_VL) 9596 NODE_NAME_CASE(SSUBSAT_VL) 9597 NODE_NAME_CASE(USUBSAT_VL) 9598 NODE_NAME_CASE(FADD_VL) 9599 NODE_NAME_CASE(FSUB_VL) 9600 NODE_NAME_CASE(FMUL_VL) 9601 NODE_NAME_CASE(FDIV_VL) 9602 NODE_NAME_CASE(FNEG_VL) 9603 NODE_NAME_CASE(FABS_VL) 9604 NODE_NAME_CASE(FSQRT_VL) 9605 NODE_NAME_CASE(FMA_VL) 9606 NODE_NAME_CASE(FCOPYSIGN_VL) 9607 NODE_NAME_CASE(SMIN_VL) 9608 NODE_NAME_CASE(SMAX_VL) 9609 NODE_NAME_CASE(UMIN_VL) 9610 NODE_NAME_CASE(UMAX_VL) 9611 NODE_NAME_CASE(FMINNUM_VL) 9612 NODE_NAME_CASE(FMAXNUM_VL) 9613 NODE_NAME_CASE(MULHS_VL) 9614 NODE_NAME_CASE(MULHU_VL) 9615 NODE_NAME_CASE(FP_TO_SINT_VL) 9616 NODE_NAME_CASE(FP_TO_UINT_VL) 9617 NODE_NAME_CASE(SINT_TO_FP_VL) 9618 NODE_NAME_CASE(UINT_TO_FP_VL) 9619 NODE_NAME_CASE(FP_EXTEND_VL) 9620 NODE_NAME_CASE(FP_ROUND_VL) 9621 NODE_NAME_CASE(VWMUL_VL) 9622 NODE_NAME_CASE(VWMULU_VL) 9623 NODE_NAME_CASE(SETCC_VL) 9624 NODE_NAME_CASE(VSELECT_VL) 9625 NODE_NAME_CASE(VMAND_VL) 9626 NODE_NAME_CASE(VMOR_VL) 9627 NODE_NAME_CASE(VMXOR_VL) 9628 NODE_NAME_CASE(VMCLR_VL) 9629 NODE_NAME_CASE(VMSET_VL) 9630 NODE_NAME_CASE(VRGATHER_VX_VL) 9631 NODE_NAME_CASE(VRGATHER_VV_VL) 9632 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 9633 NODE_NAME_CASE(VSEXT_VL) 9634 NODE_NAME_CASE(VZEXT_VL) 9635 NODE_NAME_CASE(VCPOP_VL) 9636 NODE_NAME_CASE(VLE_VL) 9637 NODE_NAME_CASE(VSE_VL) 9638 NODE_NAME_CASE(READ_CSR) 9639 NODE_NAME_CASE(WRITE_CSR) 9640 NODE_NAME_CASE(SWAP_CSR) 9641 } 9642 // clang-format on 9643 return nullptr; 9644 #undef NODE_NAME_CASE 9645 } 9646 9647 /// getConstraintType - Given a constraint letter, return the type of 9648 /// constraint it is for this target. 9649 RISCVTargetLowering::ConstraintType 9650 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 9651 if (Constraint.size() == 1) { 9652 switch (Constraint[0]) { 9653 default: 9654 break; 9655 case 'f': 9656 return C_RegisterClass; 9657 case 'I': 9658 case 'J': 9659 case 'K': 9660 return C_Immediate; 9661 case 'A': 9662 return C_Memory; 9663 case 'S': // A symbolic address 9664 return C_Other; 9665 } 9666 } else { 9667 if (Constraint == "vr" || Constraint == "vm") 9668 return C_RegisterClass; 9669 } 9670 return TargetLowering::getConstraintType(Constraint); 9671 } 9672 9673 std::pair<unsigned, const TargetRegisterClass *> 9674 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9675 StringRef Constraint, 9676 MVT VT) const { 9677 // First, see if this is a constraint that directly corresponds to a 9678 // RISCV register class. 9679 if (Constraint.size() == 1) { 9680 switch (Constraint[0]) { 9681 case 'r': 9682 // TODO: Support fixed vectors up to XLen for P extension? 9683 if (VT.isVector()) 9684 break; 9685 return std::make_pair(0U, &RISCV::GPRRegClass); 9686 case 'f': 9687 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 9688 return std::make_pair(0U, &RISCV::FPR16RegClass); 9689 if (Subtarget.hasStdExtF() && VT == MVT::f32) 9690 return std::make_pair(0U, &RISCV::FPR32RegClass); 9691 if (Subtarget.hasStdExtD() && VT == MVT::f64) 9692 return std::make_pair(0U, &RISCV::FPR64RegClass); 9693 break; 9694 default: 9695 break; 9696 } 9697 } else if (Constraint == "vr") { 9698 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 9699 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9700 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 9701 return std::make_pair(0U, RC); 9702 } 9703 } else if (Constraint == "vm") { 9704 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 9705 return std::make_pair(0U, &RISCV::VMV0RegClass); 9706 } 9707 9708 // Clang will correctly decode the usage of register name aliases into their 9709 // official names. However, other frontends like `rustc` do not. This allows 9710 // users of these frontends to use the ABI names for registers in LLVM-style 9711 // register constraints. 9712 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 9713 .Case("{zero}", RISCV::X0) 9714 .Case("{ra}", RISCV::X1) 9715 .Case("{sp}", RISCV::X2) 9716 .Case("{gp}", RISCV::X3) 9717 .Case("{tp}", RISCV::X4) 9718 .Case("{t0}", RISCV::X5) 9719 .Case("{t1}", RISCV::X6) 9720 .Case("{t2}", RISCV::X7) 9721 .Cases("{s0}", "{fp}", RISCV::X8) 9722 .Case("{s1}", RISCV::X9) 9723 .Case("{a0}", RISCV::X10) 9724 .Case("{a1}", RISCV::X11) 9725 .Case("{a2}", RISCV::X12) 9726 .Case("{a3}", RISCV::X13) 9727 .Case("{a4}", RISCV::X14) 9728 .Case("{a5}", RISCV::X15) 9729 .Case("{a6}", RISCV::X16) 9730 .Case("{a7}", RISCV::X17) 9731 .Case("{s2}", RISCV::X18) 9732 .Case("{s3}", RISCV::X19) 9733 .Case("{s4}", RISCV::X20) 9734 .Case("{s5}", RISCV::X21) 9735 .Case("{s6}", RISCV::X22) 9736 .Case("{s7}", RISCV::X23) 9737 .Case("{s8}", RISCV::X24) 9738 .Case("{s9}", RISCV::X25) 9739 .Case("{s10}", RISCV::X26) 9740 .Case("{s11}", RISCV::X27) 9741 .Case("{t3}", RISCV::X28) 9742 .Case("{t4}", RISCV::X29) 9743 .Case("{t5}", RISCV::X30) 9744 .Case("{t6}", RISCV::X31) 9745 .Default(RISCV::NoRegister); 9746 if (XRegFromAlias != RISCV::NoRegister) 9747 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 9748 9749 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 9750 // TableGen record rather than the AsmName to choose registers for InlineAsm 9751 // constraints, plus we want to match those names to the widest floating point 9752 // register type available, manually select floating point registers here. 9753 // 9754 // The second case is the ABI name of the register, so that frontends can also 9755 // use the ABI names in register constraint lists. 9756 if (Subtarget.hasStdExtF()) { 9757 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 9758 .Cases("{f0}", "{ft0}", RISCV::F0_F) 9759 .Cases("{f1}", "{ft1}", RISCV::F1_F) 9760 .Cases("{f2}", "{ft2}", RISCV::F2_F) 9761 .Cases("{f3}", "{ft3}", RISCV::F3_F) 9762 .Cases("{f4}", "{ft4}", RISCV::F4_F) 9763 .Cases("{f5}", "{ft5}", RISCV::F5_F) 9764 .Cases("{f6}", "{ft6}", RISCV::F6_F) 9765 .Cases("{f7}", "{ft7}", RISCV::F7_F) 9766 .Cases("{f8}", "{fs0}", RISCV::F8_F) 9767 .Cases("{f9}", "{fs1}", RISCV::F9_F) 9768 .Cases("{f10}", "{fa0}", RISCV::F10_F) 9769 .Cases("{f11}", "{fa1}", RISCV::F11_F) 9770 .Cases("{f12}", "{fa2}", RISCV::F12_F) 9771 .Cases("{f13}", "{fa3}", RISCV::F13_F) 9772 .Cases("{f14}", "{fa4}", RISCV::F14_F) 9773 .Cases("{f15}", "{fa5}", RISCV::F15_F) 9774 .Cases("{f16}", "{fa6}", RISCV::F16_F) 9775 .Cases("{f17}", "{fa7}", RISCV::F17_F) 9776 .Cases("{f18}", "{fs2}", RISCV::F18_F) 9777 .Cases("{f19}", "{fs3}", RISCV::F19_F) 9778 .Cases("{f20}", "{fs4}", RISCV::F20_F) 9779 .Cases("{f21}", "{fs5}", RISCV::F21_F) 9780 .Cases("{f22}", "{fs6}", RISCV::F22_F) 9781 .Cases("{f23}", "{fs7}", RISCV::F23_F) 9782 .Cases("{f24}", "{fs8}", RISCV::F24_F) 9783 .Cases("{f25}", "{fs9}", RISCV::F25_F) 9784 .Cases("{f26}", "{fs10}", RISCV::F26_F) 9785 .Cases("{f27}", "{fs11}", RISCV::F27_F) 9786 .Cases("{f28}", "{ft8}", RISCV::F28_F) 9787 .Cases("{f29}", "{ft9}", RISCV::F29_F) 9788 .Cases("{f30}", "{ft10}", RISCV::F30_F) 9789 .Cases("{f31}", "{ft11}", RISCV::F31_F) 9790 .Default(RISCV::NoRegister); 9791 if (FReg != RISCV::NoRegister) { 9792 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 9793 if (Subtarget.hasStdExtD()) { 9794 unsigned RegNo = FReg - RISCV::F0_F; 9795 unsigned DReg = RISCV::F0_D + RegNo; 9796 return std::make_pair(DReg, &RISCV::FPR64RegClass); 9797 } 9798 return std::make_pair(FReg, &RISCV::FPR32RegClass); 9799 } 9800 } 9801 9802 if (Subtarget.hasVInstructions()) { 9803 Register VReg = StringSwitch<Register>(Constraint.lower()) 9804 .Case("{v0}", RISCV::V0) 9805 .Case("{v1}", RISCV::V1) 9806 .Case("{v2}", RISCV::V2) 9807 .Case("{v3}", RISCV::V3) 9808 .Case("{v4}", RISCV::V4) 9809 .Case("{v5}", RISCV::V5) 9810 .Case("{v6}", RISCV::V6) 9811 .Case("{v7}", RISCV::V7) 9812 .Case("{v8}", RISCV::V8) 9813 .Case("{v9}", RISCV::V9) 9814 .Case("{v10}", RISCV::V10) 9815 .Case("{v11}", RISCV::V11) 9816 .Case("{v12}", RISCV::V12) 9817 .Case("{v13}", RISCV::V13) 9818 .Case("{v14}", RISCV::V14) 9819 .Case("{v15}", RISCV::V15) 9820 .Case("{v16}", RISCV::V16) 9821 .Case("{v17}", RISCV::V17) 9822 .Case("{v18}", RISCV::V18) 9823 .Case("{v19}", RISCV::V19) 9824 .Case("{v20}", RISCV::V20) 9825 .Case("{v21}", RISCV::V21) 9826 .Case("{v22}", RISCV::V22) 9827 .Case("{v23}", RISCV::V23) 9828 .Case("{v24}", RISCV::V24) 9829 .Case("{v25}", RISCV::V25) 9830 .Case("{v26}", RISCV::V26) 9831 .Case("{v27}", RISCV::V27) 9832 .Case("{v28}", RISCV::V28) 9833 .Case("{v29}", RISCV::V29) 9834 .Case("{v30}", RISCV::V30) 9835 .Case("{v31}", RISCV::V31) 9836 .Default(RISCV::NoRegister); 9837 if (VReg != RISCV::NoRegister) { 9838 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 9839 return std::make_pair(VReg, &RISCV::VMRegClass); 9840 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 9841 return std::make_pair(VReg, &RISCV::VRRegClass); 9842 for (const auto *RC : 9843 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 9844 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 9845 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 9846 return std::make_pair(VReg, RC); 9847 } 9848 } 9849 } 9850 } 9851 9852 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9853 } 9854 9855 unsigned 9856 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 9857 // Currently only support length 1 constraints. 9858 if (ConstraintCode.size() == 1) { 9859 switch (ConstraintCode[0]) { 9860 case 'A': 9861 return InlineAsm::Constraint_A; 9862 default: 9863 break; 9864 } 9865 } 9866 9867 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 9868 } 9869 9870 void RISCVTargetLowering::LowerAsmOperandForConstraint( 9871 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 9872 SelectionDAG &DAG) const { 9873 // Currently only support length 1 constraints. 9874 if (Constraint.length() == 1) { 9875 switch (Constraint[0]) { 9876 case 'I': 9877 // Validate & create a 12-bit signed immediate operand. 9878 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9879 uint64_t CVal = C->getSExtValue(); 9880 if (isInt<12>(CVal)) 9881 Ops.push_back( 9882 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9883 } 9884 return; 9885 case 'J': 9886 // Validate & create an integer zero operand. 9887 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 9888 if (C->getZExtValue() == 0) 9889 Ops.push_back( 9890 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 9891 return; 9892 case 'K': 9893 // Validate & create a 5-bit unsigned immediate operand. 9894 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 9895 uint64_t CVal = C->getZExtValue(); 9896 if (isUInt<5>(CVal)) 9897 Ops.push_back( 9898 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 9899 } 9900 return; 9901 case 'S': 9902 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9903 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 9904 GA->getValueType(0))); 9905 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 9906 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 9907 BA->getValueType(0))); 9908 } 9909 return; 9910 default: 9911 break; 9912 } 9913 } 9914 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 9915 } 9916 9917 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 9918 Instruction *Inst, 9919 AtomicOrdering Ord) const { 9920 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 9921 return Builder.CreateFence(Ord); 9922 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 9923 return Builder.CreateFence(AtomicOrdering::Release); 9924 return nullptr; 9925 } 9926 9927 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 9928 Instruction *Inst, 9929 AtomicOrdering Ord) const { 9930 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 9931 return Builder.CreateFence(AtomicOrdering::Acquire); 9932 return nullptr; 9933 } 9934 9935 TargetLowering::AtomicExpansionKind 9936 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 9937 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 9938 // point operations can't be used in an lr/sc sequence without breaking the 9939 // forward-progress guarantee. 9940 if (AI->isFloatingPointOperation()) 9941 return AtomicExpansionKind::CmpXChg; 9942 9943 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 9944 if (Size == 8 || Size == 16) 9945 return AtomicExpansionKind::MaskedIntrinsic; 9946 return AtomicExpansionKind::None; 9947 } 9948 9949 static Intrinsic::ID 9950 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 9951 if (XLen == 32) { 9952 switch (BinOp) { 9953 default: 9954 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9955 case AtomicRMWInst::Xchg: 9956 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 9957 case AtomicRMWInst::Add: 9958 return Intrinsic::riscv_masked_atomicrmw_add_i32; 9959 case AtomicRMWInst::Sub: 9960 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 9961 case AtomicRMWInst::Nand: 9962 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 9963 case AtomicRMWInst::Max: 9964 return Intrinsic::riscv_masked_atomicrmw_max_i32; 9965 case AtomicRMWInst::Min: 9966 return Intrinsic::riscv_masked_atomicrmw_min_i32; 9967 case AtomicRMWInst::UMax: 9968 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 9969 case AtomicRMWInst::UMin: 9970 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 9971 } 9972 } 9973 9974 if (XLen == 64) { 9975 switch (BinOp) { 9976 default: 9977 llvm_unreachable("Unexpected AtomicRMW BinOp"); 9978 case AtomicRMWInst::Xchg: 9979 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 9980 case AtomicRMWInst::Add: 9981 return Intrinsic::riscv_masked_atomicrmw_add_i64; 9982 case AtomicRMWInst::Sub: 9983 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 9984 case AtomicRMWInst::Nand: 9985 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 9986 case AtomicRMWInst::Max: 9987 return Intrinsic::riscv_masked_atomicrmw_max_i64; 9988 case AtomicRMWInst::Min: 9989 return Intrinsic::riscv_masked_atomicrmw_min_i64; 9990 case AtomicRMWInst::UMax: 9991 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 9992 case AtomicRMWInst::UMin: 9993 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 9994 } 9995 } 9996 9997 llvm_unreachable("Unexpected XLen\n"); 9998 } 9999 10000 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 10001 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 10002 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 10003 unsigned XLen = Subtarget.getXLen(); 10004 Value *Ordering = 10005 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 10006 Type *Tys[] = {AlignedAddr->getType()}; 10007 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 10008 AI->getModule(), 10009 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 10010 10011 if (XLen == 64) { 10012 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 10013 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10014 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 10015 } 10016 10017 Value *Result; 10018 10019 // Must pass the shift amount needed to sign extend the loaded value prior 10020 // to performing a signed comparison for min/max. ShiftAmt is the number of 10021 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 10022 // is the number of bits to left+right shift the value in order to 10023 // sign-extend. 10024 if (AI->getOperation() == AtomicRMWInst::Min || 10025 AI->getOperation() == AtomicRMWInst::Max) { 10026 const DataLayout &DL = AI->getModule()->getDataLayout(); 10027 unsigned ValWidth = 10028 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 10029 Value *SextShamt = 10030 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 10031 Result = Builder.CreateCall(LrwOpScwLoop, 10032 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 10033 } else { 10034 Result = 10035 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 10036 } 10037 10038 if (XLen == 64) 10039 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10040 return Result; 10041 } 10042 10043 TargetLowering::AtomicExpansionKind 10044 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 10045 AtomicCmpXchgInst *CI) const { 10046 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 10047 if (Size == 8 || Size == 16) 10048 return AtomicExpansionKind::MaskedIntrinsic; 10049 return AtomicExpansionKind::None; 10050 } 10051 10052 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 10053 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 10054 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 10055 unsigned XLen = Subtarget.getXLen(); 10056 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 10057 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 10058 if (XLen == 64) { 10059 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 10060 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 10061 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10062 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 10063 } 10064 Type *Tys[] = {AlignedAddr->getType()}; 10065 Function *MaskedCmpXchg = 10066 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 10067 Value *Result = Builder.CreateCall( 10068 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 10069 if (XLen == 64) 10070 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10071 return Result; 10072 } 10073 10074 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 10075 return false; 10076 } 10077 10078 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 10079 EVT VT) const { 10080 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 10081 return false; 10082 10083 switch (FPVT.getSimpleVT().SimpleTy) { 10084 case MVT::f16: 10085 return Subtarget.hasStdExtZfh(); 10086 case MVT::f32: 10087 return Subtarget.hasStdExtF(); 10088 case MVT::f64: 10089 return Subtarget.hasStdExtD(); 10090 default: 10091 return false; 10092 } 10093 } 10094 10095 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 10096 EVT VT) const { 10097 VT = VT.getScalarType(); 10098 10099 if (!VT.isSimple()) 10100 return false; 10101 10102 switch (VT.getSimpleVT().SimpleTy) { 10103 case MVT::f16: 10104 return Subtarget.hasStdExtZfh(); 10105 case MVT::f32: 10106 return Subtarget.hasStdExtF(); 10107 case MVT::f64: 10108 return Subtarget.hasStdExtD(); 10109 default: 10110 break; 10111 } 10112 10113 return false; 10114 } 10115 10116 Register RISCVTargetLowering::getExceptionPointerRegister( 10117 const Constant *PersonalityFn) const { 10118 return RISCV::X10; 10119 } 10120 10121 Register RISCVTargetLowering::getExceptionSelectorRegister( 10122 const Constant *PersonalityFn) const { 10123 return RISCV::X11; 10124 } 10125 10126 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 10127 // Return false to suppress the unnecessary extensions if the LibCall 10128 // arguments or return value is f32 type for LP64 ABI. 10129 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 10130 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 10131 return false; 10132 10133 return true; 10134 } 10135 10136 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 10137 if (Subtarget.is64Bit() && Type == MVT::i32) 10138 return true; 10139 10140 return IsSigned; 10141 } 10142 10143 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 10144 SDValue C) const { 10145 // Check integral scalar types. 10146 if (VT.isScalarInteger()) { 10147 // Omit the optimization if the sub target has the M extension and the data 10148 // size exceeds XLen. 10149 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 10150 return false; 10151 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 10152 // Break the MUL to a SLLI and an ADD/SUB. 10153 const APInt &Imm = ConstNode->getAPIntValue(); 10154 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 10155 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 10156 return true; 10157 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 10158 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 10159 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 10160 (Imm - 8).isPowerOf2())) 10161 return true; 10162 // Omit the following optimization if the sub target has the M extension 10163 // and the data size >= XLen. 10164 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 10165 return false; 10166 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 10167 // a pair of LUI/ADDI. 10168 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 10169 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 10170 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 10171 (1 - ImmS).isPowerOf2()) 10172 return true; 10173 } 10174 } 10175 } 10176 10177 return false; 10178 } 10179 10180 bool RISCVTargetLowering::isMulAddWithConstProfitable( 10181 const SDValue &AddNode, const SDValue &ConstNode) const { 10182 // Let the DAGCombiner decide for vectors. 10183 EVT VT = AddNode.getValueType(); 10184 if (VT.isVector()) 10185 return true; 10186 10187 // Let the DAGCombiner decide for larger types. 10188 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 10189 return true; 10190 10191 // It is worse if c1 is simm12 while c1*c2 is not. 10192 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 10193 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 10194 const APInt &C1 = C1Node->getAPIntValue(); 10195 const APInt &C2 = C2Node->getAPIntValue(); 10196 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 10197 return false; 10198 10199 // Default to true and let the DAGCombiner decide. 10200 return true; 10201 } 10202 10203 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 10204 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 10205 bool *Fast) const { 10206 if (!VT.isVector()) 10207 return false; 10208 10209 EVT ElemVT = VT.getVectorElementType(); 10210 if (Alignment >= ElemVT.getStoreSize()) { 10211 if (Fast) 10212 *Fast = true; 10213 return true; 10214 } 10215 10216 return false; 10217 } 10218 10219 bool RISCVTargetLowering::splitValueIntoRegisterParts( 10220 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 10221 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 10222 bool IsABIRegCopy = CC.hasValue(); 10223 EVT ValueVT = Val.getValueType(); 10224 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10225 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 10226 // and cast to f32. 10227 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 10228 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 10229 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 10230 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 10231 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 10232 Parts[0] = Val; 10233 return true; 10234 } 10235 10236 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10237 LLVMContext &Context = *DAG.getContext(); 10238 EVT ValueEltVT = ValueVT.getVectorElementType(); 10239 EVT PartEltVT = PartVT.getVectorElementType(); 10240 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10241 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10242 if (PartVTBitSize % ValueVTBitSize == 0) { 10243 assert(PartVTBitSize >= ValueVTBitSize); 10244 // If the element types are different, bitcast to the same element type of 10245 // PartVT first. 10246 // Give an example here, we want copy a <vscale x 1 x i8> value to 10247 // <vscale x 4 x i16>. 10248 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 10249 // subvector, then we can bitcast to <vscale x 4 x i16>. 10250 if (ValueEltVT != PartEltVT) { 10251 if (PartVTBitSize > ValueVTBitSize) { 10252 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10253 assert(Count != 0 && "The number of element should not be zero."); 10254 EVT SameEltTypeVT = 10255 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10256 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 10257 DAG.getUNDEF(SameEltTypeVT), Val, 10258 DAG.getVectorIdxConstant(0, DL)); 10259 } 10260 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 10261 } else { 10262 Val = 10263 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 10264 Val, DAG.getVectorIdxConstant(0, DL)); 10265 } 10266 Parts[0] = Val; 10267 return true; 10268 } 10269 } 10270 return false; 10271 } 10272 10273 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 10274 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 10275 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 10276 bool IsABIRegCopy = CC.hasValue(); 10277 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10278 SDValue Val = Parts[0]; 10279 10280 // Cast the f32 to i32, truncate to i16, and cast back to f16. 10281 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 10282 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 10283 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 10284 return Val; 10285 } 10286 10287 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10288 LLVMContext &Context = *DAG.getContext(); 10289 SDValue Val = Parts[0]; 10290 EVT ValueEltVT = ValueVT.getVectorElementType(); 10291 EVT PartEltVT = PartVT.getVectorElementType(); 10292 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10293 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10294 if (PartVTBitSize % ValueVTBitSize == 0) { 10295 assert(PartVTBitSize >= ValueVTBitSize); 10296 EVT SameEltTypeVT = ValueVT; 10297 // If the element types are different, convert it to the same element type 10298 // of PartVT. 10299 // Give an example here, we want copy a <vscale x 1 x i8> value from 10300 // <vscale x 4 x i16>. 10301 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 10302 // then we can extract <vscale x 1 x i8>. 10303 if (ValueEltVT != PartEltVT) { 10304 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10305 assert(Count != 0 && "The number of element should not be zero."); 10306 SameEltTypeVT = 10307 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10308 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 10309 } 10310 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 10311 DAG.getVectorIdxConstant(0, DL)); 10312 return Val; 10313 } 10314 } 10315 return SDValue(); 10316 } 10317 10318 #define GET_REGISTER_MATCHER 10319 #include "RISCVGenAsmMatcher.inc" 10320 10321 Register 10322 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 10323 const MachineFunction &MF) const { 10324 Register Reg = MatchRegisterAltName(RegName); 10325 if (Reg == RISCV::NoRegister) 10326 Reg = MatchRegisterName(RegName); 10327 if (Reg == RISCV::NoRegister) 10328 report_fatal_error( 10329 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 10330 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 10331 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 10332 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 10333 StringRef(RegName) + "\".")); 10334 return Reg; 10335 } 10336 10337 namespace llvm { 10338 namespace RISCVVIntrinsicsTable { 10339 10340 #define GET_RISCVVIntrinsicsTable_IMPL 10341 #include "RISCVGenSearchableTables.inc" 10342 10343 } // namespace RISCVVIntrinsicsTable 10344 10345 } // namespace llvm 10346