1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 174 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 185 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 186 187 setOperationAction(ISD::VASTART, MVT::Other, Custom); 188 setOperationAction(ISD::VAARG, MVT::Other, Expand); 189 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 190 setOperationAction(ISD::VAEND, MVT::Other, Expand); 191 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 if (!Subtarget.hasStdExtZbb()) { 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 196 } 197 198 if (Subtarget.is64Bit()) { 199 setOperationAction(ISD::ADD, MVT::i32, Custom); 200 setOperationAction(ISD::SUB, MVT::i32, Custom); 201 setOperationAction(ISD::SHL, MVT::i32, Custom); 202 setOperationAction(ISD::SRA, MVT::i32, Custom); 203 setOperationAction(ISD::SRL, MVT::i32, Custom); 204 205 setOperationAction(ISD::UADDO, MVT::i32, Custom); 206 setOperationAction(ISD::USUBO, MVT::i32, Custom); 207 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 208 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 209 } else { 210 setLibcallName(RTLIB::SHL_I128, nullptr); 211 setLibcallName(RTLIB::SRL_I128, nullptr); 212 setLibcallName(RTLIB::SRA_I128, nullptr); 213 setLibcallName(RTLIB::MUL_I128, nullptr); 214 setLibcallName(RTLIB::MULO_I64, nullptr); 215 } 216 217 if (!Subtarget.hasStdExtM()) { 218 setOperationAction(ISD::MUL, XLenVT, Expand); 219 setOperationAction(ISD::MULHS, XLenVT, Expand); 220 setOperationAction(ISD::MULHU, XLenVT, Expand); 221 setOperationAction(ISD::SDIV, XLenVT, Expand); 222 setOperationAction(ISD::UDIV, XLenVT, Expand); 223 setOperationAction(ISD::SREM, XLenVT, Expand); 224 setOperationAction(ISD::UREM, XLenVT, Expand); 225 } else { 226 if (Subtarget.is64Bit()) { 227 setOperationAction(ISD::MUL, MVT::i32, Custom); 228 setOperationAction(ISD::MUL, MVT::i128, Custom); 229 230 setOperationAction(ISD::SDIV, MVT::i8, Custom); 231 setOperationAction(ISD::UDIV, MVT::i8, Custom); 232 setOperationAction(ISD::UREM, MVT::i8, Custom); 233 setOperationAction(ISD::SDIV, MVT::i16, Custom); 234 setOperationAction(ISD::UDIV, MVT::i16, Custom); 235 setOperationAction(ISD::UREM, MVT::i16, Custom); 236 setOperationAction(ISD::SDIV, MVT::i32, Custom); 237 setOperationAction(ISD::UDIV, MVT::i32, Custom); 238 setOperationAction(ISD::UREM, MVT::i32, Custom); 239 } else { 240 setOperationAction(ISD::MUL, MVT::i64, Custom); 241 } 242 } 243 244 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 245 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 246 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 247 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 248 249 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 250 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 251 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 252 253 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 254 Subtarget.hasStdExtZbkb()) { 255 if (Subtarget.is64Bit()) { 256 setOperationAction(ISD::ROTL, MVT::i32, Custom); 257 setOperationAction(ISD::ROTR, MVT::i32, Custom); 258 } 259 } else { 260 setOperationAction(ISD::ROTL, XLenVT, Expand); 261 setOperationAction(ISD::ROTR, XLenVT, Expand); 262 } 263 264 if (Subtarget.hasStdExtZbp()) { 265 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 266 // more combining. 267 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 268 setOperationAction(ISD::BSWAP, XLenVT, Custom); 269 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 270 // BSWAP i8 doesn't exist. 271 setOperationAction(ISD::BITREVERSE, MVT::i16, Custom); 272 setOperationAction(ISD::BSWAP, MVT::i16, Custom); 273 274 if (Subtarget.is64Bit()) { 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 276 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 277 } 278 } else { 279 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 280 // pattern match it directly in isel. 281 setOperationAction(ISD::BSWAP, XLenVT, 282 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 283 ? Legal 284 : Expand); 285 // Zbkb can use rev8+brev8 to implement bitreverse. 286 setOperationAction(ISD::BITREVERSE, XLenVT, 287 Subtarget.hasStdExtZbkb() ? Custom : Expand); 288 } 289 290 if (Subtarget.hasStdExtZbb()) { 291 setOperationAction(ISD::SMIN, XLenVT, Legal); 292 setOperationAction(ISD::SMAX, XLenVT, Legal); 293 setOperationAction(ISD::UMIN, XLenVT, Legal); 294 setOperationAction(ISD::UMAX, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) { 297 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 298 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 299 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 301 } 302 } else { 303 setOperationAction(ISD::CTTZ, XLenVT, Expand); 304 setOperationAction(ISD::CTLZ, XLenVT, Expand); 305 setOperationAction(ISD::CTPOP, XLenVT, Expand); 306 } 307 308 if (Subtarget.hasStdExtZbt()) { 309 setOperationAction(ISD::FSHL, XLenVT, Custom); 310 setOperationAction(ISD::FSHR, XLenVT, Custom); 311 setOperationAction(ISD::SELECT, XLenVT, Legal); 312 313 if (Subtarget.is64Bit()) { 314 setOperationAction(ISD::FSHL, MVT::i32, Custom); 315 setOperationAction(ISD::FSHR, MVT::i32, Custom); 316 } 317 } else { 318 setOperationAction(ISD::SELECT, XLenVT, Custom); 319 } 320 321 static const ISD::CondCode FPCCToExpand[] = { 322 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 323 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 324 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 325 326 static const ISD::NodeType FPOpToExpand[] = { 327 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 328 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 329 330 if (Subtarget.hasStdExtZfh()) 331 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 332 333 if (Subtarget.hasStdExtZfh()) { 334 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 335 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 336 setOperationAction(ISD::LRINT, MVT::f16, Legal); 337 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 338 setOperationAction(ISD::LROUND, MVT::f16, Legal); 339 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 340 setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal); 341 setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal); 342 setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal); 343 setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal); 344 setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal); 345 setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal); 346 setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal); 348 setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal); 349 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 350 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 351 setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal); 352 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal); 353 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal); 354 for (auto CC : FPCCToExpand) 355 setCondCodeAction(CC, MVT::f16, Expand); 356 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 357 setOperationAction(ISD::SELECT, MVT::f16, Custom); 358 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 359 360 setOperationAction(ISD::FREM, MVT::f16, Promote); 361 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 362 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 363 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 364 setOperationAction(ISD::FRINT, MVT::f16, Promote); 365 setOperationAction(ISD::FROUND, MVT::f16, Promote); 366 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 367 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 368 setOperationAction(ISD::FPOW, MVT::f16, Promote); 369 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 370 setOperationAction(ISD::FCOS, MVT::f16, Promote); 371 setOperationAction(ISD::FSIN, MVT::f16, Promote); 372 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 373 setOperationAction(ISD::FEXP, MVT::f16, Promote); 374 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 375 setOperationAction(ISD::FLOG, MVT::f16, Promote); 376 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 377 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 378 379 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 380 // complete support for all operations in LegalizeDAG. 381 382 // We need to custom promote this. 383 if (Subtarget.is64Bit()) 384 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 385 } 386 387 if (Subtarget.hasStdExtF()) { 388 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 389 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 390 setOperationAction(ISD::LRINT, MVT::f32, Legal); 391 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 392 setOperationAction(ISD::LROUND, MVT::f32, Legal); 393 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 394 setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal); 395 setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal); 396 setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal); 397 setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal); 398 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 399 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 400 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 401 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 402 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 403 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 404 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 405 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 406 for (auto CC : FPCCToExpand) 407 setCondCodeAction(CC, MVT::f32, Expand); 408 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 409 setOperationAction(ISD::SELECT, MVT::f32, Custom); 410 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 411 for (auto Op : FPOpToExpand) 412 setOperationAction(Op, MVT::f32, Expand); 413 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 414 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 415 } 416 417 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 418 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 419 420 if (Subtarget.hasStdExtD()) { 421 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 422 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 423 setOperationAction(ISD::LRINT, MVT::f64, Legal); 424 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 425 setOperationAction(ISD::LROUND, MVT::f64, Legal); 426 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 427 setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal); 428 setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal); 429 setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal); 430 setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal); 431 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 432 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 433 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 434 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 435 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 436 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 437 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 438 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 439 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 440 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 441 for (auto CC : FPCCToExpand) 442 setCondCodeAction(CC, MVT::f64, Expand); 443 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 444 setOperationAction(ISD::SELECT, MVT::f64, Custom); 445 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 446 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 447 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 448 for (auto Op : FPOpToExpand) 449 setOperationAction(Op, MVT::f64, Expand); 450 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 451 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 452 } 453 454 if (Subtarget.is64Bit()) { 455 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 456 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 457 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 458 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 459 } 460 461 if (Subtarget.hasStdExtF()) { 462 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 463 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 464 465 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 466 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 467 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 468 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 469 470 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 471 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 472 } 473 474 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 475 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 476 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 477 setOperationAction(ISD::JumpTable, XLenVT, Custom); 478 479 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 480 481 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 482 // Unfortunately this can't be determined just from the ISA naming string. 483 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 484 Subtarget.is64Bit() ? Legal : Custom); 485 486 setOperationAction(ISD::TRAP, MVT::Other, Legal); 487 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 488 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 489 if (Subtarget.is64Bit()) 490 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 491 492 if (Subtarget.hasStdExtA()) { 493 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 494 setMinCmpXchgSizeInBits(32); 495 } else { 496 setMaxAtomicSizeInBitsSupported(0); 497 } 498 499 setBooleanContents(ZeroOrOneBooleanContent); 500 501 if (Subtarget.hasVInstructions()) { 502 setBooleanVectorContents(ZeroOrOneBooleanContent); 503 504 setOperationAction(ISD::VSCALE, XLenVT, Custom); 505 506 // RVV intrinsics may have illegal operands. 507 // We also need to custom legalize vmv.x.s. 508 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 509 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 510 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 511 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 512 if (Subtarget.is64Bit()) { 513 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 514 } else { 515 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 516 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 517 } 518 519 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 520 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 521 522 static const unsigned IntegerVPOps[] = { 523 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 524 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 525 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 526 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 527 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 528 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 529 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 530 ISD::VP_MERGE, ISD::VP_SELECT}; 531 532 static const unsigned FloatingPointVPOps[] = { 533 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 534 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 535 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, 536 ISD::VP_SELECT}; 537 538 if (!Subtarget.is64Bit()) { 539 // We must custom-lower certain vXi64 operations on RV32 due to the vector 540 // element type being illegal. 541 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 542 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 543 544 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 545 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 546 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 547 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 548 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 549 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 550 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 551 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 552 553 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 554 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 555 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 556 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 557 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 558 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 559 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 560 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 561 } 562 563 for (MVT VT : BoolVecVTs) { 564 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 565 566 // Mask VTs are custom-expanded into a series of standard nodes 567 setOperationAction(ISD::TRUNCATE, VT, Custom); 568 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 569 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 570 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 571 572 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 573 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 574 575 setOperationAction(ISD::SELECT, VT, Custom); 576 setOperationAction(ISD::SELECT_CC, VT, Expand); 577 setOperationAction(ISD::VSELECT, VT, Expand); 578 setOperationAction(ISD::VP_MERGE, VT, Expand); 579 setOperationAction(ISD::VP_SELECT, VT, Expand); 580 581 setOperationAction(ISD::VP_AND, VT, Custom); 582 setOperationAction(ISD::VP_OR, VT, Custom); 583 setOperationAction(ISD::VP_XOR, VT, Custom); 584 585 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 586 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 587 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 588 589 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 590 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 591 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 592 593 // RVV has native int->float & float->int conversions where the 594 // element type sizes are within one power-of-two of each other. Any 595 // wider distances between type sizes have to be lowered as sequences 596 // which progressively narrow the gap in stages. 597 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 598 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 599 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 600 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 601 602 // Expand all extending loads to types larger than this, and truncating 603 // stores from types larger than this. 604 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 605 setTruncStoreAction(OtherVT, VT, Expand); 606 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 607 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 608 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 609 } 610 } 611 612 for (MVT VT : IntVecVTs) { 613 if (VT.getVectorElementType() == MVT::i64 && 614 !Subtarget.hasVInstructionsI64()) 615 continue; 616 617 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 618 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 619 620 // Vectors implement MULHS/MULHU. 621 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 622 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 623 624 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 625 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 626 setOperationAction(ISD::MULHU, VT, Expand); 627 setOperationAction(ISD::MULHS, VT, Expand); 628 } 629 630 setOperationAction(ISD::SMIN, VT, Legal); 631 setOperationAction(ISD::SMAX, VT, Legal); 632 setOperationAction(ISD::UMIN, VT, Legal); 633 setOperationAction(ISD::UMAX, VT, Legal); 634 635 setOperationAction(ISD::ROTL, VT, Expand); 636 setOperationAction(ISD::ROTR, VT, Expand); 637 638 setOperationAction(ISD::CTTZ, VT, Expand); 639 setOperationAction(ISD::CTLZ, VT, Expand); 640 setOperationAction(ISD::CTPOP, VT, Expand); 641 642 setOperationAction(ISD::BSWAP, VT, Expand); 643 644 // Custom-lower extensions and truncations from/to mask types. 645 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 646 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 647 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 648 649 // RVV has native int->float & float->int conversions where the 650 // element type sizes are within one power-of-two of each other. Any 651 // wider distances between type sizes have to be lowered as sequences 652 // which progressively narrow the gap in stages. 653 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 654 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 655 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 656 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 657 658 setOperationAction(ISD::SADDSAT, VT, Legal); 659 setOperationAction(ISD::UADDSAT, VT, Legal); 660 setOperationAction(ISD::SSUBSAT, VT, Legal); 661 setOperationAction(ISD::USUBSAT, VT, Legal); 662 663 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 664 // nodes which truncate by one power of two at a time. 665 setOperationAction(ISD::TRUNCATE, VT, Custom); 666 667 // Custom-lower insert/extract operations to simplify patterns. 668 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 669 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 670 671 // Custom-lower reduction operations to set up the corresponding custom 672 // nodes' operands. 673 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 674 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 675 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 676 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 677 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 678 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 679 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 680 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 681 682 for (unsigned VPOpc : IntegerVPOps) 683 setOperationAction(VPOpc, VT, Custom); 684 685 setOperationAction(ISD::LOAD, VT, Custom); 686 setOperationAction(ISD::STORE, VT, Custom); 687 688 setOperationAction(ISD::MLOAD, VT, Custom); 689 setOperationAction(ISD::MSTORE, VT, Custom); 690 setOperationAction(ISD::MGATHER, VT, Custom); 691 setOperationAction(ISD::MSCATTER, VT, Custom); 692 693 setOperationAction(ISD::VP_LOAD, VT, Custom); 694 setOperationAction(ISD::VP_STORE, VT, Custom); 695 setOperationAction(ISD::VP_GATHER, VT, Custom); 696 setOperationAction(ISD::VP_SCATTER, VT, Custom); 697 698 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 699 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 700 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 701 702 setOperationAction(ISD::SELECT, VT, Custom); 703 setOperationAction(ISD::SELECT_CC, VT, Expand); 704 705 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 706 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 707 708 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 709 setTruncStoreAction(VT, OtherVT, Expand); 710 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 711 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 712 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 713 } 714 715 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 716 // type that can represent the value exactly. 717 if (VT.getVectorElementType() != MVT::i64) { 718 MVT FloatEltVT = 719 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 720 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 721 if (isTypeLegal(FloatVT)) { 722 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 723 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 724 } 725 } 726 } 727 728 // Expand various CCs to best match the RVV ISA, which natively supports UNE 729 // but no other unordered comparisons, and supports all ordered comparisons 730 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 731 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 732 // and we pattern-match those back to the "original", swapping operands once 733 // more. This way we catch both operations and both "vf" and "fv" forms with 734 // fewer patterns. 735 static const ISD::CondCode VFPCCToExpand[] = { 736 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 737 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 738 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 739 }; 740 741 // Sets common operation actions on RVV floating-point vector types. 742 const auto SetCommonVFPActions = [&](MVT VT) { 743 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 744 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 745 // sizes are within one power-of-two of each other. Therefore conversions 746 // between vXf16 and vXf64 must be lowered as sequences which convert via 747 // vXf32. 748 setOperationAction(ISD::FP_ROUND, VT, Custom); 749 setOperationAction(ISD::FP_EXTEND, VT, Custom); 750 // Custom-lower insert/extract operations to simplify patterns. 751 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 752 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 753 // Expand various condition codes (explained above). 754 for (auto CC : VFPCCToExpand) 755 setCondCodeAction(CC, VT, Expand); 756 757 setOperationAction(ISD::FMINNUM, VT, Legal); 758 setOperationAction(ISD::FMAXNUM, VT, Legal); 759 760 setOperationAction(ISD::FTRUNC, VT, Custom); 761 setOperationAction(ISD::FCEIL, VT, Custom); 762 setOperationAction(ISD::FFLOOR, VT, Custom); 763 764 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 765 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 766 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 767 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 768 769 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 770 771 setOperationAction(ISD::LOAD, VT, Custom); 772 setOperationAction(ISD::STORE, VT, Custom); 773 774 setOperationAction(ISD::MLOAD, VT, Custom); 775 setOperationAction(ISD::MSTORE, VT, Custom); 776 setOperationAction(ISD::MGATHER, VT, Custom); 777 setOperationAction(ISD::MSCATTER, VT, Custom); 778 779 setOperationAction(ISD::VP_LOAD, VT, Custom); 780 setOperationAction(ISD::VP_STORE, VT, Custom); 781 setOperationAction(ISD::VP_GATHER, VT, Custom); 782 setOperationAction(ISD::VP_SCATTER, VT, Custom); 783 784 setOperationAction(ISD::SELECT, VT, Custom); 785 setOperationAction(ISD::SELECT_CC, VT, Expand); 786 787 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 788 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 789 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 790 791 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 792 793 for (unsigned VPOpc : FloatingPointVPOps) 794 setOperationAction(VPOpc, VT, Custom); 795 }; 796 797 // Sets common extload/truncstore actions on RVV floating-point vector 798 // types. 799 const auto SetCommonVFPExtLoadTruncStoreActions = 800 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 801 for (auto SmallVT : SmallerVTs) { 802 setTruncStoreAction(VT, SmallVT, Expand); 803 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 804 } 805 }; 806 807 if (Subtarget.hasVInstructionsF16()) 808 for (MVT VT : F16VecVTs) 809 SetCommonVFPActions(VT); 810 811 for (MVT VT : F32VecVTs) { 812 if (Subtarget.hasVInstructionsF32()) 813 SetCommonVFPActions(VT); 814 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 815 } 816 817 for (MVT VT : F64VecVTs) { 818 if (Subtarget.hasVInstructionsF64()) 819 SetCommonVFPActions(VT); 820 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 821 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 822 } 823 824 if (Subtarget.useRVVForFixedLengthVectors()) { 825 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 826 if (!useRVVForFixedLengthVectorVT(VT)) 827 continue; 828 829 // By default everything must be expanded. 830 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 831 setOperationAction(Op, VT, Expand); 832 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 833 setTruncStoreAction(VT, OtherVT, Expand); 834 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 835 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 836 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 837 } 838 839 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 840 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 841 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 842 843 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 844 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 845 846 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 847 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 848 849 setOperationAction(ISD::LOAD, VT, Custom); 850 setOperationAction(ISD::STORE, VT, Custom); 851 852 setOperationAction(ISD::SETCC, VT, Custom); 853 854 setOperationAction(ISD::SELECT, VT, Custom); 855 856 setOperationAction(ISD::TRUNCATE, VT, Custom); 857 858 setOperationAction(ISD::BITCAST, VT, Custom); 859 860 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 861 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 862 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 863 864 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 865 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 866 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 867 868 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 869 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 870 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 871 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 872 873 // Operations below are different for between masks and other vectors. 874 if (VT.getVectorElementType() == MVT::i1) { 875 setOperationAction(ISD::VP_AND, VT, Custom); 876 setOperationAction(ISD::VP_OR, VT, Custom); 877 setOperationAction(ISD::VP_XOR, VT, Custom); 878 setOperationAction(ISD::AND, VT, Custom); 879 setOperationAction(ISD::OR, VT, Custom); 880 setOperationAction(ISD::XOR, VT, Custom); 881 continue; 882 } 883 884 // Use SPLAT_VECTOR to prevent type legalization from destroying the 885 // splats when type legalizing i64 scalar on RV32. 886 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 887 // improvements first. 888 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 889 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 890 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 891 } 892 893 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 894 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 895 896 setOperationAction(ISD::MLOAD, VT, Custom); 897 setOperationAction(ISD::MSTORE, VT, Custom); 898 setOperationAction(ISD::MGATHER, VT, Custom); 899 setOperationAction(ISD::MSCATTER, VT, Custom); 900 901 setOperationAction(ISD::VP_LOAD, VT, Custom); 902 setOperationAction(ISD::VP_STORE, VT, Custom); 903 setOperationAction(ISD::VP_GATHER, VT, Custom); 904 setOperationAction(ISD::VP_SCATTER, VT, Custom); 905 906 setOperationAction(ISD::ADD, VT, Custom); 907 setOperationAction(ISD::MUL, VT, Custom); 908 setOperationAction(ISD::SUB, VT, Custom); 909 setOperationAction(ISD::AND, VT, Custom); 910 setOperationAction(ISD::OR, VT, Custom); 911 setOperationAction(ISD::XOR, VT, Custom); 912 setOperationAction(ISD::SDIV, VT, Custom); 913 setOperationAction(ISD::SREM, VT, Custom); 914 setOperationAction(ISD::UDIV, VT, Custom); 915 setOperationAction(ISD::UREM, VT, Custom); 916 setOperationAction(ISD::SHL, VT, Custom); 917 setOperationAction(ISD::SRA, VT, Custom); 918 setOperationAction(ISD::SRL, VT, Custom); 919 920 setOperationAction(ISD::SMIN, VT, Custom); 921 setOperationAction(ISD::SMAX, VT, Custom); 922 setOperationAction(ISD::UMIN, VT, Custom); 923 setOperationAction(ISD::UMAX, VT, Custom); 924 setOperationAction(ISD::ABS, VT, Custom); 925 926 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 927 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 928 setOperationAction(ISD::MULHS, VT, Custom); 929 setOperationAction(ISD::MULHU, VT, Custom); 930 } 931 932 setOperationAction(ISD::SADDSAT, VT, Custom); 933 setOperationAction(ISD::UADDSAT, VT, Custom); 934 setOperationAction(ISD::SSUBSAT, VT, Custom); 935 setOperationAction(ISD::USUBSAT, VT, Custom); 936 937 setOperationAction(ISD::VSELECT, VT, Custom); 938 setOperationAction(ISD::SELECT_CC, VT, Expand); 939 940 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 941 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 942 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 943 944 // Custom-lower reduction operations to set up the corresponding custom 945 // nodes' operands. 946 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 947 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 948 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 949 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 950 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 951 952 for (unsigned VPOpc : IntegerVPOps) 953 setOperationAction(VPOpc, VT, Custom); 954 955 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 956 // type that can represent the value exactly. 957 if (VT.getVectorElementType() != MVT::i64) { 958 MVT FloatEltVT = 959 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 960 EVT FloatVT = 961 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 962 if (isTypeLegal(FloatVT)) { 963 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 964 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 965 } 966 } 967 } 968 969 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 970 if (!useRVVForFixedLengthVectorVT(VT)) 971 continue; 972 973 // By default everything must be expanded. 974 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 975 setOperationAction(Op, VT, Expand); 976 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 977 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 978 setTruncStoreAction(VT, OtherVT, Expand); 979 } 980 981 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 982 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 983 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 984 985 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 986 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 987 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 988 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 990 991 setOperationAction(ISD::LOAD, VT, Custom); 992 setOperationAction(ISD::STORE, VT, Custom); 993 setOperationAction(ISD::MLOAD, VT, Custom); 994 setOperationAction(ISD::MSTORE, VT, Custom); 995 setOperationAction(ISD::MGATHER, VT, Custom); 996 setOperationAction(ISD::MSCATTER, VT, Custom); 997 998 setOperationAction(ISD::VP_LOAD, VT, Custom); 999 setOperationAction(ISD::VP_STORE, VT, Custom); 1000 setOperationAction(ISD::VP_GATHER, VT, Custom); 1001 setOperationAction(ISD::VP_SCATTER, VT, Custom); 1002 1003 setOperationAction(ISD::FADD, VT, Custom); 1004 setOperationAction(ISD::FSUB, VT, Custom); 1005 setOperationAction(ISD::FMUL, VT, Custom); 1006 setOperationAction(ISD::FDIV, VT, Custom); 1007 setOperationAction(ISD::FNEG, VT, Custom); 1008 setOperationAction(ISD::FABS, VT, Custom); 1009 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 1010 setOperationAction(ISD::FSQRT, VT, Custom); 1011 setOperationAction(ISD::FMA, VT, Custom); 1012 setOperationAction(ISD::FMINNUM, VT, Custom); 1013 setOperationAction(ISD::FMAXNUM, VT, Custom); 1014 1015 setOperationAction(ISD::FP_ROUND, VT, Custom); 1016 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1017 1018 setOperationAction(ISD::FTRUNC, VT, Custom); 1019 setOperationAction(ISD::FCEIL, VT, Custom); 1020 setOperationAction(ISD::FFLOOR, VT, Custom); 1021 1022 for (auto CC : VFPCCToExpand) 1023 setCondCodeAction(CC, VT, Expand); 1024 1025 setOperationAction(ISD::VSELECT, VT, Custom); 1026 setOperationAction(ISD::SELECT, VT, Custom); 1027 setOperationAction(ISD::SELECT_CC, VT, Expand); 1028 1029 setOperationAction(ISD::BITCAST, VT, Custom); 1030 1031 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1032 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1033 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1034 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1035 1036 for (unsigned VPOpc : FloatingPointVPOps) 1037 setOperationAction(VPOpc, VT, Custom); 1038 } 1039 1040 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1041 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1042 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1043 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1044 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1045 if (Subtarget.hasStdExtZfh()) 1046 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1047 if (Subtarget.hasStdExtF()) 1048 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1049 if (Subtarget.hasStdExtD()) 1050 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1051 } 1052 } 1053 1054 // Function alignments. 1055 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1056 setMinFunctionAlignment(FunctionAlignment); 1057 setPrefFunctionAlignment(FunctionAlignment); 1058 1059 setMinimumJumpTableEntries(5); 1060 1061 // Jumps are expensive, compared to logic 1062 setJumpIsExpensive(); 1063 1064 setTargetDAGCombine(ISD::ADD); 1065 setTargetDAGCombine(ISD::SUB); 1066 setTargetDAGCombine(ISD::AND); 1067 setTargetDAGCombine(ISD::OR); 1068 setTargetDAGCombine(ISD::XOR); 1069 setTargetDAGCombine(ISD::ANY_EXTEND); 1070 if (Subtarget.hasStdExtF()) { 1071 setTargetDAGCombine(ISD::ZERO_EXTEND); 1072 setTargetDAGCombine(ISD::FP_TO_SINT); 1073 setTargetDAGCombine(ISD::FP_TO_UINT); 1074 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1075 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1076 } 1077 if (Subtarget.hasVInstructions()) { 1078 setTargetDAGCombine(ISD::FCOPYSIGN); 1079 setTargetDAGCombine(ISD::MGATHER); 1080 setTargetDAGCombine(ISD::MSCATTER); 1081 setTargetDAGCombine(ISD::VP_GATHER); 1082 setTargetDAGCombine(ISD::VP_SCATTER); 1083 setTargetDAGCombine(ISD::SRA); 1084 setTargetDAGCombine(ISD::SRL); 1085 setTargetDAGCombine(ISD::SHL); 1086 setTargetDAGCombine(ISD::STORE); 1087 } 1088 1089 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1090 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1091 } 1092 1093 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1094 LLVMContext &Context, 1095 EVT VT) const { 1096 if (!VT.isVector()) 1097 return getPointerTy(DL); 1098 if (Subtarget.hasVInstructions() && 1099 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1100 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1101 return VT.changeVectorElementTypeToInteger(); 1102 } 1103 1104 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1105 return Subtarget.getXLenVT(); 1106 } 1107 1108 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1109 const CallInst &I, 1110 MachineFunction &MF, 1111 unsigned Intrinsic) const { 1112 auto &DL = I.getModule()->getDataLayout(); 1113 switch (Intrinsic) { 1114 default: 1115 return false; 1116 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1117 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1118 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1119 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1120 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1121 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1122 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1123 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1124 case Intrinsic::riscv_masked_cmpxchg_i32: 1125 Info.opc = ISD::INTRINSIC_W_CHAIN; 1126 Info.memVT = MVT::i32; 1127 Info.ptrVal = I.getArgOperand(0); 1128 Info.offset = 0; 1129 Info.align = Align(4); 1130 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1131 MachineMemOperand::MOVolatile; 1132 return true; 1133 case Intrinsic::riscv_masked_strided_load: 1134 Info.opc = ISD::INTRINSIC_W_CHAIN; 1135 Info.ptrVal = I.getArgOperand(1); 1136 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1137 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1138 Info.size = MemoryLocation::UnknownSize; 1139 Info.flags |= MachineMemOperand::MOLoad; 1140 return true; 1141 case Intrinsic::riscv_masked_strided_store: 1142 Info.opc = ISD::INTRINSIC_VOID; 1143 Info.ptrVal = I.getArgOperand(1); 1144 Info.memVT = 1145 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1146 Info.align = Align( 1147 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1148 8); 1149 Info.size = MemoryLocation::UnknownSize; 1150 Info.flags |= MachineMemOperand::MOStore; 1151 return true; 1152 } 1153 } 1154 1155 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1156 const AddrMode &AM, Type *Ty, 1157 unsigned AS, 1158 Instruction *I) const { 1159 // No global is ever allowed as a base. 1160 if (AM.BaseGV) 1161 return false; 1162 1163 // Require a 12-bit signed offset. 1164 if (!isInt<12>(AM.BaseOffs)) 1165 return false; 1166 1167 switch (AM.Scale) { 1168 case 0: // "r+i" or just "i", depending on HasBaseReg. 1169 break; 1170 case 1: 1171 if (!AM.HasBaseReg) // allow "r+i". 1172 break; 1173 return false; // disallow "r+r" or "r+r+i". 1174 default: 1175 return false; 1176 } 1177 1178 return true; 1179 } 1180 1181 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1182 return isInt<12>(Imm); 1183 } 1184 1185 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1186 return isInt<12>(Imm); 1187 } 1188 1189 // On RV32, 64-bit integers are split into their high and low parts and held 1190 // in two different registers, so the trunc is free since the low register can 1191 // just be used. 1192 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1193 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1194 return false; 1195 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1196 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1197 return (SrcBits == 64 && DestBits == 32); 1198 } 1199 1200 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1201 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1202 !SrcVT.isInteger() || !DstVT.isInteger()) 1203 return false; 1204 unsigned SrcBits = SrcVT.getSizeInBits(); 1205 unsigned DestBits = DstVT.getSizeInBits(); 1206 return (SrcBits == 64 && DestBits == 32); 1207 } 1208 1209 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1210 // Zexts are free if they can be combined with a load. 1211 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1212 // poorly with type legalization of compares preferring sext. 1213 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1214 EVT MemVT = LD->getMemoryVT(); 1215 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1216 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1217 LD->getExtensionType() == ISD::ZEXTLOAD)) 1218 return true; 1219 } 1220 1221 return TargetLowering::isZExtFree(Val, VT2); 1222 } 1223 1224 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1225 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1226 } 1227 1228 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1229 return Subtarget.hasStdExtZbb(); 1230 } 1231 1232 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1233 return Subtarget.hasStdExtZbb(); 1234 } 1235 1236 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1237 EVT VT = Y.getValueType(); 1238 1239 // FIXME: Support vectors once we have tests. 1240 if (VT.isVector()) 1241 return false; 1242 1243 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1244 Subtarget.hasStdExtZbkb()) && 1245 !isa<ConstantSDNode>(Y); 1246 } 1247 1248 /// Check if sinking \p I's operands to I's basic block is profitable, because 1249 /// the operands can be folded into a target instruction, e.g. 1250 /// splats of scalars can fold into vector instructions. 1251 bool RISCVTargetLowering::shouldSinkOperands( 1252 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1253 using namespace llvm::PatternMatch; 1254 1255 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1256 return false; 1257 1258 auto IsSinker = [&](Instruction *I, int Operand) { 1259 switch (I->getOpcode()) { 1260 case Instruction::Add: 1261 case Instruction::Sub: 1262 case Instruction::Mul: 1263 case Instruction::And: 1264 case Instruction::Or: 1265 case Instruction::Xor: 1266 case Instruction::FAdd: 1267 case Instruction::FSub: 1268 case Instruction::FMul: 1269 case Instruction::FDiv: 1270 case Instruction::ICmp: 1271 case Instruction::FCmp: 1272 return true; 1273 case Instruction::Shl: 1274 case Instruction::LShr: 1275 case Instruction::AShr: 1276 case Instruction::UDiv: 1277 case Instruction::SDiv: 1278 case Instruction::URem: 1279 case Instruction::SRem: 1280 return Operand == 1; 1281 case Instruction::Call: 1282 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1283 switch (II->getIntrinsicID()) { 1284 case Intrinsic::fma: 1285 return Operand == 0 || Operand == 1; 1286 // FIXME: Our patterns can only match vx/vf instructions when the splat 1287 // it on the RHS, because TableGen doesn't recognize our VP operations 1288 // as commutative. 1289 case Intrinsic::vp_add: 1290 case Intrinsic::vp_mul: 1291 case Intrinsic::vp_and: 1292 case Intrinsic::vp_or: 1293 case Intrinsic::vp_xor: 1294 case Intrinsic::vp_fadd: 1295 case Intrinsic::vp_fmul: 1296 case Intrinsic::vp_shl: 1297 case Intrinsic::vp_lshr: 1298 case Intrinsic::vp_ashr: 1299 case Intrinsic::vp_udiv: 1300 case Intrinsic::vp_sdiv: 1301 case Intrinsic::vp_urem: 1302 case Intrinsic::vp_srem: 1303 return Operand == 1; 1304 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1305 // explicit patterns for both LHS and RHS (as 'vr' versions). 1306 case Intrinsic::vp_sub: 1307 case Intrinsic::vp_fsub: 1308 case Intrinsic::vp_fdiv: 1309 return Operand == 0 || Operand == 1; 1310 default: 1311 return false; 1312 } 1313 } 1314 return false; 1315 default: 1316 return false; 1317 } 1318 }; 1319 1320 for (auto OpIdx : enumerate(I->operands())) { 1321 if (!IsSinker(I, OpIdx.index())) 1322 continue; 1323 1324 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1325 // Make sure we are not already sinking this operand 1326 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1327 continue; 1328 1329 // We are looking for a splat that can be sunk. 1330 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1331 m_Undef(), m_ZeroMask()))) 1332 continue; 1333 1334 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1335 // and vector registers 1336 for (Use &U : Op->uses()) { 1337 Instruction *Insn = cast<Instruction>(U.getUser()); 1338 if (!IsSinker(Insn, U.getOperandNo())) 1339 return false; 1340 } 1341 1342 Ops.push_back(&Op->getOperandUse(0)); 1343 Ops.push_back(&OpIdx.value()); 1344 } 1345 return true; 1346 } 1347 1348 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1349 bool ForCodeSize) const { 1350 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1351 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1352 return false; 1353 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1354 return false; 1355 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1356 return false; 1357 return Imm.isZero(); 1358 } 1359 1360 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1361 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1362 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1363 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1364 } 1365 1366 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1367 CallingConv::ID CC, 1368 EVT VT) const { 1369 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1370 // We might still end up using a GPR but that will be decided based on ABI. 1371 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1372 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1373 return MVT::f32; 1374 1375 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1376 } 1377 1378 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1379 CallingConv::ID CC, 1380 EVT VT) const { 1381 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1382 // We might still end up using a GPR but that will be decided based on ABI. 1383 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1384 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1385 return 1; 1386 1387 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1388 } 1389 1390 // Changes the condition code and swaps operands if necessary, so the SetCC 1391 // operation matches one of the comparisons supported directly by branches 1392 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1393 // with 1/-1. 1394 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1395 ISD::CondCode &CC, SelectionDAG &DAG) { 1396 // Convert X > -1 to X >= 0. 1397 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1398 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1399 CC = ISD::SETGE; 1400 return; 1401 } 1402 // Convert X < 1 to 0 >= X. 1403 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1404 RHS = LHS; 1405 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1406 CC = ISD::SETGE; 1407 return; 1408 } 1409 1410 switch (CC) { 1411 default: 1412 break; 1413 case ISD::SETGT: 1414 case ISD::SETLE: 1415 case ISD::SETUGT: 1416 case ISD::SETULE: 1417 CC = ISD::getSetCCSwappedOperands(CC); 1418 std::swap(LHS, RHS); 1419 break; 1420 } 1421 } 1422 1423 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1424 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1425 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1426 if (VT.getVectorElementType() == MVT::i1) 1427 KnownSize *= 8; 1428 1429 switch (KnownSize) { 1430 default: 1431 llvm_unreachable("Invalid LMUL."); 1432 case 8: 1433 return RISCVII::VLMUL::LMUL_F8; 1434 case 16: 1435 return RISCVII::VLMUL::LMUL_F4; 1436 case 32: 1437 return RISCVII::VLMUL::LMUL_F2; 1438 case 64: 1439 return RISCVII::VLMUL::LMUL_1; 1440 case 128: 1441 return RISCVII::VLMUL::LMUL_2; 1442 case 256: 1443 return RISCVII::VLMUL::LMUL_4; 1444 case 512: 1445 return RISCVII::VLMUL::LMUL_8; 1446 } 1447 } 1448 1449 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1450 switch (LMul) { 1451 default: 1452 llvm_unreachable("Invalid LMUL."); 1453 case RISCVII::VLMUL::LMUL_F8: 1454 case RISCVII::VLMUL::LMUL_F4: 1455 case RISCVII::VLMUL::LMUL_F2: 1456 case RISCVII::VLMUL::LMUL_1: 1457 return RISCV::VRRegClassID; 1458 case RISCVII::VLMUL::LMUL_2: 1459 return RISCV::VRM2RegClassID; 1460 case RISCVII::VLMUL::LMUL_4: 1461 return RISCV::VRM4RegClassID; 1462 case RISCVII::VLMUL::LMUL_8: 1463 return RISCV::VRM8RegClassID; 1464 } 1465 } 1466 1467 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1468 RISCVII::VLMUL LMUL = getLMUL(VT); 1469 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1470 LMUL == RISCVII::VLMUL::LMUL_F4 || 1471 LMUL == RISCVII::VLMUL::LMUL_F2 || 1472 LMUL == RISCVII::VLMUL::LMUL_1) { 1473 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1474 "Unexpected subreg numbering"); 1475 return RISCV::sub_vrm1_0 + Index; 1476 } 1477 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1478 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1479 "Unexpected subreg numbering"); 1480 return RISCV::sub_vrm2_0 + Index; 1481 } 1482 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1483 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1484 "Unexpected subreg numbering"); 1485 return RISCV::sub_vrm4_0 + Index; 1486 } 1487 llvm_unreachable("Invalid vector type."); 1488 } 1489 1490 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1491 if (VT.getVectorElementType() == MVT::i1) 1492 return RISCV::VRRegClassID; 1493 return getRegClassIDForLMUL(getLMUL(VT)); 1494 } 1495 1496 // Attempt to decompose a subvector insert/extract between VecVT and 1497 // SubVecVT via subregister indices. Returns the subregister index that 1498 // can perform the subvector insert/extract with the given element index, as 1499 // well as the index corresponding to any leftover subvectors that must be 1500 // further inserted/extracted within the register class for SubVecVT. 1501 std::pair<unsigned, unsigned> 1502 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1503 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1504 const RISCVRegisterInfo *TRI) { 1505 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1506 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1507 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1508 "Register classes not ordered"); 1509 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1510 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1511 // Try to compose a subregister index that takes us from the incoming 1512 // LMUL>1 register class down to the outgoing one. At each step we half 1513 // the LMUL: 1514 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1515 // Note that this is not guaranteed to find a subregister index, such as 1516 // when we are extracting from one VR type to another. 1517 unsigned SubRegIdx = RISCV::NoSubRegister; 1518 for (const unsigned RCID : 1519 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1520 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1521 VecVT = VecVT.getHalfNumVectorElementsVT(); 1522 bool IsHi = 1523 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1524 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1525 getSubregIndexByMVT(VecVT, IsHi)); 1526 if (IsHi) 1527 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1528 } 1529 return {SubRegIdx, InsertExtractIdx}; 1530 } 1531 1532 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1533 // stores for those types. 1534 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1535 return !Subtarget.useRVVForFixedLengthVectors() || 1536 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1537 } 1538 1539 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1540 if (ScalarTy->isPointerTy()) 1541 return true; 1542 1543 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1544 ScalarTy->isIntegerTy(32)) 1545 return true; 1546 1547 if (ScalarTy->isIntegerTy(64)) 1548 return Subtarget.hasVInstructionsI64(); 1549 1550 if (ScalarTy->isHalfTy()) 1551 return Subtarget.hasVInstructionsF16(); 1552 if (ScalarTy->isFloatTy()) 1553 return Subtarget.hasVInstructionsF32(); 1554 if (ScalarTy->isDoubleTy()) 1555 return Subtarget.hasVInstructionsF64(); 1556 1557 return false; 1558 } 1559 1560 static SDValue getVLOperand(SDValue Op) { 1561 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1562 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1563 "Unexpected opcode"); 1564 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1565 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1566 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1567 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1568 if (!II) 1569 return SDValue(); 1570 return Op.getOperand(II->VLOperand + 1 + HasChain); 1571 } 1572 1573 static bool useRVVForFixedLengthVectorVT(MVT VT, 1574 const RISCVSubtarget &Subtarget) { 1575 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1576 if (!Subtarget.useRVVForFixedLengthVectors()) 1577 return false; 1578 1579 // We only support a set of vector types with a consistent maximum fixed size 1580 // across all supported vector element types to avoid legalization issues. 1581 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1582 // fixed-length vector type we support is 1024 bytes. 1583 if (VT.getFixedSizeInBits() > 1024 * 8) 1584 return false; 1585 1586 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1587 1588 MVT EltVT = VT.getVectorElementType(); 1589 1590 // Don't use RVV for vectors we cannot scalarize if required. 1591 switch (EltVT.SimpleTy) { 1592 // i1 is supported but has different rules. 1593 default: 1594 return false; 1595 case MVT::i1: 1596 // Masks can only use a single register. 1597 if (VT.getVectorNumElements() > MinVLen) 1598 return false; 1599 MinVLen /= 8; 1600 break; 1601 case MVT::i8: 1602 case MVT::i16: 1603 case MVT::i32: 1604 break; 1605 case MVT::i64: 1606 if (!Subtarget.hasVInstructionsI64()) 1607 return false; 1608 break; 1609 case MVT::f16: 1610 if (!Subtarget.hasVInstructionsF16()) 1611 return false; 1612 break; 1613 case MVT::f32: 1614 if (!Subtarget.hasVInstructionsF32()) 1615 return false; 1616 break; 1617 case MVT::f64: 1618 if (!Subtarget.hasVInstructionsF64()) 1619 return false; 1620 break; 1621 } 1622 1623 // Reject elements larger than ELEN. 1624 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1625 return false; 1626 1627 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1628 // Don't use RVV for types that don't fit. 1629 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1630 return false; 1631 1632 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1633 // the base fixed length RVV support in place. 1634 if (!VT.isPow2VectorType()) 1635 return false; 1636 1637 return true; 1638 } 1639 1640 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1641 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1642 } 1643 1644 // Return the largest legal scalable vector type that matches VT's element type. 1645 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1646 const RISCVSubtarget &Subtarget) { 1647 // This may be called before legal types are setup. 1648 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1649 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1650 "Expected legal fixed length vector!"); 1651 1652 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1653 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1654 1655 MVT EltVT = VT.getVectorElementType(); 1656 switch (EltVT.SimpleTy) { 1657 default: 1658 llvm_unreachable("unexpected element type for RVV container"); 1659 case MVT::i1: 1660 case MVT::i8: 1661 case MVT::i16: 1662 case MVT::i32: 1663 case MVT::i64: 1664 case MVT::f16: 1665 case MVT::f32: 1666 case MVT::f64: { 1667 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1668 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1669 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1670 unsigned NumElts = 1671 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1672 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1673 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1674 return MVT::getScalableVectorVT(EltVT, NumElts); 1675 } 1676 } 1677 } 1678 1679 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1680 const RISCVSubtarget &Subtarget) { 1681 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1682 Subtarget); 1683 } 1684 1685 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1686 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1687 } 1688 1689 // Grow V to consume an entire RVV register. 1690 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1691 const RISCVSubtarget &Subtarget) { 1692 assert(VT.isScalableVector() && 1693 "Expected to convert into a scalable vector!"); 1694 assert(V.getValueType().isFixedLengthVector() && 1695 "Expected a fixed length vector operand!"); 1696 SDLoc DL(V); 1697 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1698 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1699 } 1700 1701 // Shrink V so it's just big enough to maintain a VT's worth of data. 1702 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1703 const RISCVSubtarget &Subtarget) { 1704 assert(VT.isFixedLengthVector() && 1705 "Expected to convert into a fixed length vector!"); 1706 assert(V.getValueType().isScalableVector() && 1707 "Expected a scalable vector operand!"); 1708 SDLoc DL(V); 1709 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1710 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1711 } 1712 1713 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1714 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1715 // the vector type that it is contained in. 1716 static std::pair<SDValue, SDValue> 1717 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1718 const RISCVSubtarget &Subtarget) { 1719 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1720 MVT XLenVT = Subtarget.getXLenVT(); 1721 SDValue VL = VecVT.isFixedLengthVector() 1722 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1723 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1724 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1725 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1726 return {Mask, VL}; 1727 } 1728 1729 // As above but assuming the given type is a scalable vector type. 1730 static std::pair<SDValue, SDValue> 1731 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1732 const RISCVSubtarget &Subtarget) { 1733 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1734 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1735 } 1736 1737 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1738 // of either is (currently) supported. This can get us into an infinite loop 1739 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1740 // as a ..., etc. 1741 // Until either (or both) of these can reliably lower any node, reporting that 1742 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1743 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1744 // which is not desirable. 1745 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1746 EVT VT, unsigned DefinedValues) const { 1747 return false; 1748 } 1749 1750 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1751 // Only splats are currently supported. 1752 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1753 return true; 1754 1755 return false; 1756 } 1757 1758 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1759 const RISCVSubtarget &Subtarget) { 1760 // RISCV FP-to-int conversions saturate to the destination register size, but 1761 // don't produce 0 for nan. We can use a conversion instruction and fix the 1762 // nan case with a compare and a select. 1763 SDValue Src = Op.getOperand(0); 1764 1765 EVT DstVT = Op.getValueType(); 1766 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1767 1768 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1769 unsigned Opc; 1770 if (SatVT == DstVT) 1771 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1772 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1773 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1774 else 1775 return SDValue(); 1776 // FIXME: Support other SatVTs by clamping before or after the conversion. 1777 1778 SDLoc DL(Op); 1779 SDValue FpToInt = DAG.getNode( 1780 Opc, DL, DstVT, Src, 1781 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1782 1783 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1784 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1785 } 1786 1787 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1788 // and back. Taking care to avoid converting values that are nan or already 1789 // correct. 1790 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1791 // have FRM dependencies modeled yet. 1792 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1793 MVT VT = Op.getSimpleValueType(); 1794 assert(VT.isVector() && "Unexpected type"); 1795 1796 SDLoc DL(Op); 1797 1798 // Freeze the source since we are increasing the number of uses. 1799 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1800 1801 // Truncate to integer and convert back to FP. 1802 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1803 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1804 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1805 1806 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1807 1808 if (Op.getOpcode() == ISD::FCEIL) { 1809 // If the truncated value is the greater than or equal to the original 1810 // value, we've computed the ceil. Otherwise, we went the wrong way and 1811 // need to increase by 1. 1812 // FIXME: This should use a masked operation. Handle here or in isel? 1813 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1814 DAG.getConstantFP(1.0, DL, VT)); 1815 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1816 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1817 } else if (Op.getOpcode() == ISD::FFLOOR) { 1818 // If the truncated value is the less than or equal to the original value, 1819 // we've computed the floor. Otherwise, we went the wrong way and need to 1820 // decrease by 1. 1821 // FIXME: This should use a masked operation. Handle here or in isel? 1822 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1823 DAG.getConstantFP(1.0, DL, VT)); 1824 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1825 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1826 } 1827 1828 // Restore the original sign so that -0.0 is preserved. 1829 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1830 1831 // Determine the largest integer that can be represented exactly. This and 1832 // values larger than it don't have any fractional bits so don't need to 1833 // be converted. 1834 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1835 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1836 APFloat MaxVal = APFloat(FltSem); 1837 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1838 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1839 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1840 1841 // If abs(Src) was larger than MaxVal or nan, keep it. 1842 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1843 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1844 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1845 } 1846 1847 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1848 const RISCVSubtarget &Subtarget) { 1849 MVT VT = Op.getSimpleValueType(); 1850 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1851 1852 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1853 1854 SDLoc DL(Op); 1855 SDValue Mask, VL; 1856 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1857 1858 unsigned Opc = 1859 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1860 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1861 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1862 } 1863 1864 struct VIDSequence { 1865 int64_t StepNumerator; 1866 unsigned StepDenominator; 1867 int64_t Addend; 1868 }; 1869 1870 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1871 // to the (non-zero) step S and start value X. This can be then lowered as the 1872 // RVV sequence (VID * S) + X, for example. 1873 // The step S is represented as an integer numerator divided by a positive 1874 // denominator. Note that the implementation currently only identifies 1875 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1876 // cannot detect 2/3, for example. 1877 // Note that this method will also match potentially unappealing index 1878 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1879 // determine whether this is worth generating code for. 1880 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1881 unsigned NumElts = Op.getNumOperands(); 1882 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1883 if (!Op.getValueType().isInteger()) 1884 return None; 1885 1886 Optional<unsigned> SeqStepDenom; 1887 Optional<int64_t> SeqStepNum, SeqAddend; 1888 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1889 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1890 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1891 // Assume undef elements match the sequence; we just have to be careful 1892 // when interpolating across them. 1893 if (Op.getOperand(Idx).isUndef()) 1894 continue; 1895 // The BUILD_VECTOR must be all constants. 1896 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1897 return None; 1898 1899 uint64_t Val = Op.getConstantOperandVal(Idx) & 1900 maskTrailingOnes<uint64_t>(EltSizeInBits); 1901 1902 if (PrevElt) { 1903 // Calculate the step since the last non-undef element, and ensure 1904 // it's consistent across the entire sequence. 1905 unsigned IdxDiff = Idx - PrevElt->second; 1906 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1907 1908 // A zero-value value difference means that we're somewhere in the middle 1909 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1910 // step change before evaluating the sequence. 1911 if (ValDiff != 0) { 1912 int64_t Remainder = ValDiff % IdxDiff; 1913 // Normalize the step if it's greater than 1. 1914 if (Remainder != ValDiff) { 1915 // The difference must cleanly divide the element span. 1916 if (Remainder != 0) 1917 return None; 1918 ValDiff /= IdxDiff; 1919 IdxDiff = 1; 1920 } 1921 1922 if (!SeqStepNum) 1923 SeqStepNum = ValDiff; 1924 else if (ValDiff != SeqStepNum) 1925 return None; 1926 1927 if (!SeqStepDenom) 1928 SeqStepDenom = IdxDiff; 1929 else if (IdxDiff != *SeqStepDenom) 1930 return None; 1931 } 1932 } 1933 1934 // Record and/or check any addend. 1935 if (SeqStepNum && SeqStepDenom) { 1936 uint64_t ExpectedVal = 1937 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1938 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1939 if (!SeqAddend) 1940 SeqAddend = Addend; 1941 else if (SeqAddend != Addend) 1942 return None; 1943 } 1944 1945 // Record this non-undef element for later. 1946 if (!PrevElt || PrevElt->first != Val) 1947 PrevElt = std::make_pair(Val, Idx); 1948 } 1949 // We need to have logged both a step and an addend for this to count as 1950 // a legal index sequence. 1951 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1952 return None; 1953 1954 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1955 } 1956 1957 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1958 const RISCVSubtarget &Subtarget) { 1959 MVT VT = Op.getSimpleValueType(); 1960 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1961 1962 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1963 1964 SDLoc DL(Op); 1965 SDValue Mask, VL; 1966 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1967 1968 MVT XLenVT = Subtarget.getXLenVT(); 1969 unsigned NumElts = Op.getNumOperands(); 1970 1971 if (VT.getVectorElementType() == MVT::i1) { 1972 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1973 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1974 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1975 } 1976 1977 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1978 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1979 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1980 } 1981 1982 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1983 // scalar integer chunks whose bit-width depends on the number of mask 1984 // bits and XLEN. 1985 // First, determine the most appropriate scalar integer type to use. This 1986 // is at most XLenVT, but may be shrunk to a smaller vector element type 1987 // according to the size of the final vector - use i8 chunks rather than 1988 // XLenVT if we're producing a v8i1. This results in more consistent 1989 // codegen across RV32 and RV64. 1990 unsigned NumViaIntegerBits = 1991 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1992 NumViaIntegerBits = std::min(NumViaIntegerBits, 1993 Subtarget.getMaxELENForFixedLengthVectors()); 1994 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1995 // If we have to use more than one INSERT_VECTOR_ELT then this 1996 // optimization is likely to increase code size; avoid peforming it in 1997 // such a case. We can use a load from a constant pool in this case. 1998 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1999 return SDValue(); 2000 // Now we can create our integer vector type. Note that it may be larger 2001 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2002 MVT IntegerViaVecVT = 2003 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2004 divideCeil(NumElts, NumViaIntegerBits)); 2005 2006 uint64_t Bits = 0; 2007 unsigned BitPos = 0, IntegerEltIdx = 0; 2008 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2009 2010 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2011 // Once we accumulate enough bits to fill our scalar type, insert into 2012 // our vector and clear our accumulated data. 2013 if (I != 0 && I % NumViaIntegerBits == 0) { 2014 if (NumViaIntegerBits <= 32) 2015 Bits = SignExtend64(Bits, 32); 2016 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2017 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2018 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2019 Bits = 0; 2020 BitPos = 0; 2021 IntegerEltIdx++; 2022 } 2023 SDValue V = Op.getOperand(I); 2024 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2025 Bits |= ((uint64_t)BitValue << BitPos); 2026 } 2027 2028 // Insert the (remaining) scalar value into position in our integer 2029 // vector type. 2030 if (NumViaIntegerBits <= 32) 2031 Bits = SignExtend64(Bits, 32); 2032 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2033 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2034 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2035 2036 if (NumElts < NumViaIntegerBits) { 2037 // If we're producing a smaller vector than our minimum legal integer 2038 // type, bitcast to the equivalent (known-legal) mask type, and extract 2039 // our final mask. 2040 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2041 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2042 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2043 DAG.getConstant(0, DL, XLenVT)); 2044 } else { 2045 // Else we must have produced an integer type with the same size as the 2046 // mask type; bitcast for the final result. 2047 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2048 Vec = DAG.getBitcast(VT, Vec); 2049 } 2050 2051 return Vec; 2052 } 2053 2054 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2055 // vector type, we have a legal equivalently-sized i8 type, so we can use 2056 // that. 2057 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2058 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2059 2060 SDValue WideVec; 2061 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2062 // For a splat, perform a scalar truncate before creating the wider 2063 // vector. 2064 assert(Splat.getValueType() == XLenVT && 2065 "Unexpected type for i1 splat value"); 2066 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2067 DAG.getConstant(1, DL, XLenVT)); 2068 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2069 } else { 2070 SmallVector<SDValue, 8> Ops(Op->op_values()); 2071 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2072 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2073 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2074 } 2075 2076 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2077 } 2078 2079 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2080 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2081 : RISCVISD::VMV_V_X_VL; 2082 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 2083 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2084 } 2085 2086 // Try and match index sequences, which we can lower to the vid instruction 2087 // with optional modifications. An all-undef vector is matched by 2088 // getSplatValue, above. 2089 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2090 int64_t StepNumerator = SimpleVID->StepNumerator; 2091 unsigned StepDenominator = SimpleVID->StepDenominator; 2092 int64_t Addend = SimpleVID->Addend; 2093 2094 assert(StepNumerator != 0 && "Invalid step"); 2095 bool Negate = false; 2096 int64_t SplatStepVal = StepNumerator; 2097 unsigned StepOpcode = ISD::MUL; 2098 if (StepNumerator != 1) { 2099 if (isPowerOf2_64(std::abs(StepNumerator))) { 2100 Negate = StepNumerator < 0; 2101 StepOpcode = ISD::SHL; 2102 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2103 } 2104 } 2105 2106 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2107 // threshold since it's the immediate value many RVV instructions accept. 2108 // There is no vmul.vi instruction so ensure multiply constant can fit in 2109 // a single addi instruction. 2110 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2111 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2112 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2113 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2114 // Convert right out of the scalable type so we can use standard ISD 2115 // nodes for the rest of the computation. If we used scalable types with 2116 // these, we'd lose the fixed-length vector info and generate worse 2117 // vsetvli code. 2118 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2119 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2120 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2121 SDValue SplatStep = DAG.getSplatVector( 2122 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2123 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2124 } 2125 if (StepDenominator != 1) { 2126 SDValue SplatStep = DAG.getSplatVector( 2127 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2128 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2129 } 2130 if (Addend != 0 || Negate) { 2131 SDValue SplatAddend = 2132 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2133 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2134 } 2135 return VID; 2136 } 2137 } 2138 2139 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2140 // when re-interpreted as a vector with a larger element type. For example, 2141 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2142 // could be instead splat as 2143 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2144 // TODO: This optimization could also work on non-constant splats, but it 2145 // would require bit-manipulation instructions to construct the splat value. 2146 SmallVector<SDValue> Sequence; 2147 unsigned EltBitSize = VT.getScalarSizeInBits(); 2148 const auto *BV = cast<BuildVectorSDNode>(Op); 2149 if (VT.isInteger() && EltBitSize < 64 && 2150 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2151 BV->getRepeatedSequence(Sequence) && 2152 (Sequence.size() * EltBitSize) <= 64) { 2153 unsigned SeqLen = Sequence.size(); 2154 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2155 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2156 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2157 ViaIntVT == MVT::i64) && 2158 "Unexpected sequence type"); 2159 2160 unsigned EltIdx = 0; 2161 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2162 uint64_t SplatValue = 0; 2163 // Construct the amalgamated value which can be splatted as this larger 2164 // vector type. 2165 for (const auto &SeqV : Sequence) { 2166 if (!SeqV.isUndef()) 2167 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2168 << (EltIdx * EltBitSize)); 2169 EltIdx++; 2170 } 2171 2172 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2173 // achieve better constant materializion. 2174 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2175 SplatValue = SignExtend64(SplatValue, 32); 2176 2177 // Since we can't introduce illegal i64 types at this stage, we can only 2178 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2179 // way we can use RVV instructions to splat. 2180 assert((ViaIntVT.bitsLE(XLenVT) || 2181 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2182 "Unexpected bitcast sequence"); 2183 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2184 SDValue ViaVL = 2185 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2186 MVT ViaContainerVT = 2187 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2188 SDValue Splat = 2189 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2190 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2191 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2192 return DAG.getBitcast(VT, Splat); 2193 } 2194 } 2195 2196 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2197 // which constitute a large proportion of the elements. In such cases we can 2198 // splat a vector with the dominant element and make up the shortfall with 2199 // INSERT_VECTOR_ELTs. 2200 // Note that this includes vectors of 2 elements by association. The 2201 // upper-most element is the "dominant" one, allowing us to use a splat to 2202 // "insert" the upper element, and an insert of the lower element at position 2203 // 0, which improves codegen. 2204 SDValue DominantValue; 2205 unsigned MostCommonCount = 0; 2206 DenseMap<SDValue, unsigned> ValueCounts; 2207 unsigned NumUndefElts = 2208 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2209 2210 // Track the number of scalar loads we know we'd be inserting, estimated as 2211 // any non-zero floating-point constant. Other kinds of element are either 2212 // already in registers or are materialized on demand. The threshold at which 2213 // a vector load is more desirable than several scalar materializion and 2214 // vector-insertion instructions is not known. 2215 unsigned NumScalarLoads = 0; 2216 2217 for (SDValue V : Op->op_values()) { 2218 if (V.isUndef()) 2219 continue; 2220 2221 ValueCounts.insert(std::make_pair(V, 0)); 2222 unsigned &Count = ValueCounts[V]; 2223 2224 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2225 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2226 2227 // Is this value dominant? In case of a tie, prefer the highest element as 2228 // it's cheaper to insert near the beginning of a vector than it is at the 2229 // end. 2230 if (++Count >= MostCommonCount) { 2231 DominantValue = V; 2232 MostCommonCount = Count; 2233 } 2234 } 2235 2236 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2237 unsigned NumDefElts = NumElts - NumUndefElts; 2238 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2239 2240 // Don't perform this optimization when optimizing for size, since 2241 // materializing elements and inserting them tends to cause code bloat. 2242 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2243 ((MostCommonCount > DominantValueCountThreshold) || 2244 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2245 // Start by splatting the most common element. 2246 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2247 2248 DenseSet<SDValue> Processed{DominantValue}; 2249 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2250 for (const auto &OpIdx : enumerate(Op->ops())) { 2251 const SDValue &V = OpIdx.value(); 2252 if (V.isUndef() || !Processed.insert(V).second) 2253 continue; 2254 if (ValueCounts[V] == 1) { 2255 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2256 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2257 } else { 2258 // Blend in all instances of this value using a VSELECT, using a 2259 // mask where each bit signals whether that element is the one 2260 // we're after. 2261 SmallVector<SDValue> Ops; 2262 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2263 return DAG.getConstant(V == V1, DL, XLenVT); 2264 }); 2265 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2266 DAG.getBuildVector(SelMaskTy, DL, Ops), 2267 DAG.getSplatBuildVector(VT, DL, V), Vec); 2268 } 2269 } 2270 2271 return Vec; 2272 } 2273 2274 return SDValue(); 2275 } 2276 2277 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2278 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2279 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2280 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2281 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2282 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2283 // node in order to try and match RVV vector/scalar instructions. 2284 if ((LoC >> 31) == HiC) 2285 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2286 2287 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2288 // vmv.v.x whose EEW = 32 to lower it. 2289 auto *Const = dyn_cast<ConstantSDNode>(VL); 2290 if (LoC == HiC && Const && Const->isAllOnesValue() && 2291 Const->getOpcode() != ISD::TargetConstant) { 2292 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2293 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2294 // access the subtarget here now. 2295 auto InterVec = DAG.getNode( 2296 RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, 2297 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i32)); 2298 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2299 } 2300 } 2301 2302 // Fall back to a stack store and stride x0 vector load. 2303 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2304 } 2305 2306 // Called by type legalization to handle splat of i64 on RV32. 2307 // FIXME: We can optimize this when the type has sign or zero bits in one 2308 // of the halves. 2309 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2310 SDValue VL, SelectionDAG &DAG) { 2311 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2312 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2313 DAG.getConstant(0, DL, MVT::i32)); 2314 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2315 DAG.getConstant(1, DL, MVT::i32)); 2316 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2317 } 2318 2319 // This function lowers a splat of a scalar operand Splat with the vector 2320 // length VL. It ensures the final sequence is type legal, which is useful when 2321 // lowering a splat after type legalization. 2322 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2323 SelectionDAG &DAG, 2324 const RISCVSubtarget &Subtarget) { 2325 if (VT.isFloatingPoint()) { 2326 // If VL is 1, we could use vfmv.s.f. 2327 if (isOneConstant(VL)) 2328 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT), 2329 Scalar, VL); 2330 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2331 } 2332 2333 MVT XLenVT = Subtarget.getXLenVT(); 2334 2335 // Simplest case is that the operand needs to be promoted to XLenVT. 2336 if (Scalar.getValueType().bitsLE(XLenVT)) { 2337 // If the operand is a constant, sign extend to increase our chances 2338 // of being able to use a .vi instruction. ANY_EXTEND would become a 2339 // a zero extend and the simm5 check in isel would fail. 2340 // FIXME: Should we ignore the upper bits in isel instead? 2341 unsigned ExtOpc = 2342 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2343 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2344 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2345 // If VL is 1 and the scalar value won't benefit from immediate, we could 2346 // use vmv.s.x. 2347 if (isOneConstant(VL) && 2348 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2349 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar, 2350 VL); 2351 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2352 } 2353 2354 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2355 "Unexpected scalar for splat lowering!"); 2356 2357 if (isOneConstant(VL) && isNullConstant(Scalar)) 2358 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), 2359 DAG.getConstant(0, DL, XLenVT), VL); 2360 2361 // Otherwise use the more complicated splatting algorithm. 2362 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2363 } 2364 2365 // Is the mask a slidedown that shifts in undefs. 2366 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) { 2367 int Size = Mask.size(); 2368 2369 // Elements shifted in should be undef. 2370 auto CheckUndefs = [&](int Shift) { 2371 for (int i = Size - Shift; i != Size; ++i) 2372 if (Mask[i] >= 0) 2373 return false; 2374 return true; 2375 }; 2376 2377 // Elements should be shifted or undef. 2378 auto MatchShift = [&](int Shift) { 2379 for (int i = 0; i != Size - Shift; ++i) 2380 if (Mask[i] >= 0 && Mask[i] != Shift + i) 2381 return false; 2382 return true; 2383 }; 2384 2385 // Try all possible shifts. 2386 for (int Shift = 1; Shift != Size; ++Shift) 2387 if (CheckUndefs(Shift) && MatchShift(Shift)) 2388 return Shift; 2389 2390 // No match. 2391 return -1; 2392 } 2393 2394 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2395 const RISCVSubtarget &Subtarget) { 2396 // We need to be able to widen elements to the next larger integer type. 2397 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2398 return false; 2399 2400 int Size = Mask.size(); 2401 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2402 2403 int Srcs[] = {-1, -1}; 2404 for (int i = 0; i != Size; ++i) { 2405 // Ignore undef elements. 2406 if (Mask[i] < 0) 2407 continue; 2408 2409 // Is this an even or odd element. 2410 int Pol = i % 2; 2411 2412 // Ensure we consistently use the same source for this element polarity. 2413 int Src = Mask[i] / Size; 2414 if (Srcs[Pol] < 0) 2415 Srcs[Pol] = Src; 2416 if (Srcs[Pol] != Src) 2417 return false; 2418 2419 // Make sure the element within the source is appropriate for this element 2420 // in the destination. 2421 int Elt = Mask[i] % Size; 2422 if (Elt != i / 2) 2423 return false; 2424 } 2425 2426 // We need to find a source for each polarity and they can't be the same. 2427 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2428 return false; 2429 2430 // Swap the sources if the second source was in the even polarity. 2431 SwapSources = Srcs[0] > Srcs[1]; 2432 2433 return true; 2434 } 2435 2436 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2437 const RISCVSubtarget &Subtarget) { 2438 SDValue V1 = Op.getOperand(0); 2439 SDValue V2 = Op.getOperand(1); 2440 SDLoc DL(Op); 2441 MVT XLenVT = Subtarget.getXLenVT(); 2442 MVT VT = Op.getSimpleValueType(); 2443 unsigned NumElts = VT.getVectorNumElements(); 2444 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2445 2446 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2447 2448 SDValue TrueMask, VL; 2449 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2450 2451 if (SVN->isSplat()) { 2452 const int Lane = SVN->getSplatIndex(); 2453 if (Lane >= 0) { 2454 MVT SVT = VT.getVectorElementType(); 2455 2456 // Turn splatted vector load into a strided load with an X0 stride. 2457 SDValue V = V1; 2458 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2459 // with undef. 2460 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2461 int Offset = Lane; 2462 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2463 int OpElements = 2464 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2465 V = V.getOperand(Offset / OpElements); 2466 Offset %= OpElements; 2467 } 2468 2469 // We need to ensure the load isn't atomic or volatile. 2470 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2471 auto *Ld = cast<LoadSDNode>(V); 2472 Offset *= SVT.getStoreSize(); 2473 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2474 TypeSize::Fixed(Offset), DL); 2475 2476 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2477 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2478 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2479 SDValue IntID = 2480 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2481 SDValue Ops[] = {Ld->getChain(), 2482 IntID, 2483 DAG.getUNDEF(ContainerVT), 2484 NewAddr, 2485 DAG.getRegister(RISCV::X0, XLenVT), 2486 VL}; 2487 SDValue NewLoad = DAG.getMemIntrinsicNode( 2488 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2489 DAG.getMachineFunction().getMachineMemOperand( 2490 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2491 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2492 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2493 } 2494 2495 // Otherwise use a scalar load and splat. This will give the best 2496 // opportunity to fold a splat into the operation. ISel can turn it into 2497 // the x0 strided load if we aren't able to fold away the select. 2498 if (SVT.isFloatingPoint()) 2499 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2500 Ld->getPointerInfo().getWithOffset(Offset), 2501 Ld->getOriginalAlign(), 2502 Ld->getMemOperand()->getFlags()); 2503 else 2504 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2505 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2506 Ld->getOriginalAlign(), 2507 Ld->getMemOperand()->getFlags()); 2508 DAG.makeEquivalentMemoryOrdering(Ld, V); 2509 2510 unsigned Opc = 2511 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2512 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2513 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2514 } 2515 2516 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2517 assert(Lane < (int)NumElts && "Unexpected lane!"); 2518 SDValue Gather = 2519 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2520 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2521 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2522 } 2523 } 2524 2525 ArrayRef<int> Mask = SVN->getMask(); 2526 2527 // Try to match as a slidedown. 2528 int SlideAmt = matchShuffleAsSlideDown(Mask); 2529 if (SlideAmt >= 0) { 2530 // TODO: Should we reduce the VL to account for the upper undef elements? 2531 // Requires additional vsetvlis, but might be faster to execute. 2532 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2533 SDValue SlideDown = 2534 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 2535 DAG.getUNDEF(ContainerVT), V1, 2536 DAG.getConstant(SlideAmt, DL, XLenVT), 2537 TrueMask, VL); 2538 return convertFromScalableVector(VT, SlideDown, DAG, Subtarget); 2539 } 2540 2541 // Detect an interleave shuffle and lower to 2542 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2543 bool SwapSources; 2544 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2545 // Swap sources if needed. 2546 if (SwapSources) 2547 std::swap(V1, V2); 2548 2549 // Extract the lower half of the vectors. 2550 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2551 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2552 DAG.getConstant(0, DL, XLenVT)); 2553 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2554 DAG.getConstant(0, DL, XLenVT)); 2555 2556 // Double the element width and halve the number of elements in an int type. 2557 unsigned EltBits = VT.getScalarSizeInBits(); 2558 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2559 MVT WideIntVT = 2560 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2561 // Convert this to a scalable vector. We need to base this on the 2562 // destination size to ensure there's always a type with a smaller LMUL. 2563 MVT WideIntContainerVT = 2564 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2565 2566 // Convert sources to scalable vectors with the same element count as the 2567 // larger type. 2568 MVT HalfContainerVT = MVT::getVectorVT( 2569 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2570 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2571 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2572 2573 // Cast sources to integer. 2574 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2575 MVT IntHalfVT = 2576 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2577 V1 = DAG.getBitcast(IntHalfVT, V1); 2578 V2 = DAG.getBitcast(IntHalfVT, V2); 2579 2580 // Freeze V2 since we use it twice and we need to be sure that the add and 2581 // multiply see the same value. 2582 V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2); 2583 2584 // Recreate TrueMask using the widened type's element count. 2585 MVT MaskVT = 2586 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2587 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2588 2589 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2590 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2591 V2, TrueMask, VL); 2592 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2593 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2594 DAG.getAllOnesConstant(DL, XLenVT)); 2595 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2596 V2, Multiplier, TrueMask, VL); 2597 // Add the new copies to our previous addition giving us 2^eltbits copies of 2598 // V2. This is equivalent to shifting V2 left by eltbits. This should 2599 // combine with the vwmulu.vv above to form vwmaccu.vv. 2600 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2601 TrueMask, VL); 2602 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2603 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2604 // vector VT. 2605 ContainerVT = 2606 MVT::getVectorVT(VT.getVectorElementType(), 2607 WideIntContainerVT.getVectorElementCount() * 2); 2608 Add = DAG.getBitcast(ContainerVT, Add); 2609 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2610 } 2611 2612 // Detect shuffles which can be re-expressed as vector selects; these are 2613 // shuffles in which each element in the destination is taken from an element 2614 // at the corresponding index in either source vectors. 2615 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2616 int MaskIndex = MaskIdx.value(); 2617 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2618 }); 2619 2620 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2621 2622 SmallVector<SDValue> MaskVals; 2623 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2624 // merged with a second vrgather. 2625 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2626 2627 // By default we preserve the original operand order, and use a mask to 2628 // select LHS as true and RHS as false. However, since RVV vector selects may 2629 // feature splats but only on the LHS, we may choose to invert our mask and 2630 // instead select between RHS and LHS. 2631 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2632 bool InvertMask = IsSelect == SwapOps; 2633 2634 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2635 // half. 2636 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2637 2638 // Now construct the mask that will be used by the vselect or blended 2639 // vrgather operation. For vrgathers, construct the appropriate indices into 2640 // each vector. 2641 for (int MaskIndex : Mask) { 2642 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2643 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2644 if (!IsSelect) { 2645 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2646 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2647 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2648 : DAG.getUNDEF(XLenVT)); 2649 GatherIndicesRHS.push_back( 2650 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2651 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2652 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2653 ++LHSIndexCounts[MaskIndex]; 2654 if (!IsLHSOrUndefIndex) 2655 ++RHSIndexCounts[MaskIndex - NumElts]; 2656 } 2657 } 2658 2659 if (SwapOps) { 2660 std::swap(V1, V2); 2661 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2662 } 2663 2664 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2665 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2666 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2667 2668 if (IsSelect) 2669 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2670 2671 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2672 // On such a large vector we're unable to use i8 as the index type. 2673 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2674 // may involve vector splitting if we're already at LMUL=8, or our 2675 // user-supplied maximum fixed-length LMUL. 2676 return SDValue(); 2677 } 2678 2679 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2680 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2681 MVT IndexVT = VT.changeTypeToInteger(); 2682 // Since we can't introduce illegal index types at this stage, use i16 and 2683 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2684 // than XLenVT. 2685 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2686 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2687 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2688 } 2689 2690 MVT IndexContainerVT = 2691 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2692 2693 SDValue Gather; 2694 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2695 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2696 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2697 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2698 } else { 2699 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2700 // If only one index is used, we can use a "splat" vrgather. 2701 // TODO: We can splat the most-common index and fix-up any stragglers, if 2702 // that's beneficial. 2703 if (LHSIndexCounts.size() == 1) { 2704 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2705 Gather = 2706 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2707 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2708 } else { 2709 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2710 LHSIndices = 2711 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2712 2713 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2714 TrueMask, VL); 2715 } 2716 } 2717 2718 // If a second vector operand is used by this shuffle, blend it in with an 2719 // additional vrgather. 2720 if (!V2.isUndef()) { 2721 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2722 // If only one index is used, we can use a "splat" vrgather. 2723 // TODO: We can splat the most-common index and fix-up any stragglers, if 2724 // that's beneficial. 2725 if (RHSIndexCounts.size() == 1) { 2726 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2727 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2728 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2729 } else { 2730 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2731 RHSIndices = 2732 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2733 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2734 VL); 2735 } 2736 2737 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2738 SelectMask = 2739 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2740 2741 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2742 Gather, VL); 2743 } 2744 2745 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2746 } 2747 2748 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2749 SDLoc DL, SelectionDAG &DAG, 2750 const RISCVSubtarget &Subtarget) { 2751 if (VT.isScalableVector()) 2752 return DAG.getFPExtendOrRound(Op, DL, VT); 2753 assert(VT.isFixedLengthVector() && 2754 "Unexpected value type for RVV FP extend/round lowering"); 2755 SDValue Mask, VL; 2756 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2757 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2758 ? RISCVISD::FP_EXTEND_VL 2759 : RISCVISD::FP_ROUND_VL; 2760 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2761 } 2762 2763 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2764 // the exponent. 2765 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2766 MVT VT = Op.getSimpleValueType(); 2767 unsigned EltSize = VT.getScalarSizeInBits(); 2768 SDValue Src = Op.getOperand(0); 2769 SDLoc DL(Op); 2770 2771 // We need a FP type that can represent the value. 2772 // TODO: Use f16 for i8 when possible? 2773 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2774 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2775 2776 // Legal types should have been checked in the RISCVTargetLowering 2777 // constructor. 2778 // TODO: Splitting may make sense in some cases. 2779 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2780 "Expected legal float type!"); 2781 2782 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2783 // The trailing zero count is equal to log2 of this single bit value. 2784 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2785 SDValue Neg = 2786 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2787 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2788 } 2789 2790 // We have a legal FP type, convert to it. 2791 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2792 // Bitcast to integer and shift the exponent to the LSB. 2793 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2794 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2795 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2796 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2797 DAG.getConstant(ShiftAmt, DL, IntVT)); 2798 // Truncate back to original type to allow vnsrl. 2799 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2800 // The exponent contains log2 of the value in biased form. 2801 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2802 2803 // For trailing zeros, we just need to subtract the bias. 2804 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2805 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2806 DAG.getConstant(ExponentBias, DL, VT)); 2807 2808 // For leading zeros, we need to remove the bias and convert from log2 to 2809 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2810 unsigned Adjust = ExponentBias + (EltSize - 1); 2811 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2812 } 2813 2814 // While RVV has alignment restrictions, we should always be able to load as a 2815 // legal equivalently-sized byte-typed vector instead. This method is 2816 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2817 // the load is already correctly-aligned, it returns SDValue(). 2818 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2819 SelectionDAG &DAG) const { 2820 auto *Load = cast<LoadSDNode>(Op); 2821 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2822 2823 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2824 Load->getMemoryVT(), 2825 *Load->getMemOperand())) 2826 return SDValue(); 2827 2828 SDLoc DL(Op); 2829 MVT VT = Op.getSimpleValueType(); 2830 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2831 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2832 "Unexpected unaligned RVV load type"); 2833 MVT NewVT = 2834 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2835 assert(NewVT.isValid() && 2836 "Expecting equally-sized RVV vector types to be legal"); 2837 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2838 Load->getPointerInfo(), Load->getOriginalAlign(), 2839 Load->getMemOperand()->getFlags()); 2840 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2841 } 2842 2843 // While RVV has alignment restrictions, we should always be able to store as a 2844 // legal equivalently-sized byte-typed vector instead. This method is 2845 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2846 // returns SDValue() if the store is already correctly aligned. 2847 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2848 SelectionDAG &DAG) const { 2849 auto *Store = cast<StoreSDNode>(Op); 2850 assert(Store && Store->getValue().getValueType().isVector() && 2851 "Expected vector store"); 2852 2853 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2854 Store->getMemoryVT(), 2855 *Store->getMemOperand())) 2856 return SDValue(); 2857 2858 SDLoc DL(Op); 2859 SDValue StoredVal = Store->getValue(); 2860 MVT VT = StoredVal.getSimpleValueType(); 2861 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2862 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2863 "Unexpected unaligned RVV store type"); 2864 MVT NewVT = 2865 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2866 assert(NewVT.isValid() && 2867 "Expecting equally-sized RVV vector types to be legal"); 2868 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2869 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2870 Store->getPointerInfo(), Store->getOriginalAlign(), 2871 Store->getMemOperand()->getFlags()); 2872 } 2873 2874 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2875 SelectionDAG &DAG) const { 2876 switch (Op.getOpcode()) { 2877 default: 2878 report_fatal_error("unimplemented operand"); 2879 case ISD::GlobalAddress: 2880 return lowerGlobalAddress(Op, DAG); 2881 case ISD::BlockAddress: 2882 return lowerBlockAddress(Op, DAG); 2883 case ISD::ConstantPool: 2884 return lowerConstantPool(Op, DAG); 2885 case ISD::JumpTable: 2886 return lowerJumpTable(Op, DAG); 2887 case ISD::GlobalTLSAddress: 2888 return lowerGlobalTLSAddress(Op, DAG); 2889 case ISD::SELECT: 2890 return lowerSELECT(Op, DAG); 2891 case ISD::BRCOND: 2892 return lowerBRCOND(Op, DAG); 2893 case ISD::VASTART: 2894 return lowerVASTART(Op, DAG); 2895 case ISD::FRAMEADDR: 2896 return lowerFRAMEADDR(Op, DAG); 2897 case ISD::RETURNADDR: 2898 return lowerRETURNADDR(Op, DAG); 2899 case ISD::SHL_PARTS: 2900 return lowerShiftLeftParts(Op, DAG); 2901 case ISD::SRA_PARTS: 2902 return lowerShiftRightParts(Op, DAG, true); 2903 case ISD::SRL_PARTS: 2904 return lowerShiftRightParts(Op, DAG, false); 2905 case ISD::BITCAST: { 2906 SDLoc DL(Op); 2907 EVT VT = Op.getValueType(); 2908 SDValue Op0 = Op.getOperand(0); 2909 EVT Op0VT = Op0.getValueType(); 2910 MVT XLenVT = Subtarget.getXLenVT(); 2911 if (VT.isFixedLengthVector()) { 2912 // We can handle fixed length vector bitcasts with a simple replacement 2913 // in isel. 2914 if (Op0VT.isFixedLengthVector()) 2915 return Op; 2916 // When bitcasting from scalar to fixed-length vector, insert the scalar 2917 // into a one-element vector of the result type, and perform a vector 2918 // bitcast. 2919 if (!Op0VT.isVector()) { 2920 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2921 if (!isTypeLegal(BVT)) 2922 return SDValue(); 2923 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2924 DAG.getUNDEF(BVT), Op0, 2925 DAG.getConstant(0, DL, XLenVT))); 2926 } 2927 return SDValue(); 2928 } 2929 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2930 // thus: bitcast the vector to a one-element vector type whose element type 2931 // is the same as the result type, and extract the first element. 2932 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2933 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2934 if (!isTypeLegal(BVT)) 2935 return SDValue(); 2936 SDValue BVec = DAG.getBitcast(BVT, Op0); 2937 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2938 DAG.getConstant(0, DL, XLenVT)); 2939 } 2940 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2941 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2942 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2943 return FPConv; 2944 } 2945 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2946 Subtarget.hasStdExtF()) { 2947 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2948 SDValue FPConv = 2949 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2950 return FPConv; 2951 } 2952 return SDValue(); 2953 } 2954 case ISD::INTRINSIC_WO_CHAIN: 2955 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2956 case ISD::INTRINSIC_W_CHAIN: 2957 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2958 case ISD::INTRINSIC_VOID: 2959 return LowerINTRINSIC_VOID(Op, DAG); 2960 case ISD::BSWAP: 2961 case ISD::BITREVERSE: { 2962 MVT VT = Op.getSimpleValueType(); 2963 SDLoc DL(Op); 2964 if (Subtarget.hasStdExtZbp()) { 2965 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2966 // Start with the maximum immediate value which is the bitwidth - 1. 2967 unsigned Imm = VT.getSizeInBits() - 1; 2968 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2969 if (Op.getOpcode() == ISD::BSWAP) 2970 Imm &= ~0x7U; 2971 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2972 DAG.getConstant(Imm, DL, VT)); 2973 } 2974 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 2975 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 2976 // Expand bitreverse to a bswap(rev8) followed by brev8. 2977 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 2978 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 2979 // as brev8 by an isel pattern. 2980 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 2981 DAG.getConstant(7, DL, VT)); 2982 } 2983 case ISD::FSHL: 2984 case ISD::FSHR: { 2985 MVT VT = Op.getSimpleValueType(); 2986 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2987 SDLoc DL(Op); 2988 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2989 // use log(XLen) bits. Mask the shift amount accordingly to prevent 2990 // accidentally setting the extra bit. 2991 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2992 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2993 DAG.getConstant(ShAmtWidth, DL, VT)); 2994 // fshl and fshr concatenate their operands in the same order. fsr and fsl 2995 // instruction use different orders. fshl will return its first operand for 2996 // shift of zero, fshr will return its second operand. fsl and fsr both 2997 // return rs1 so the ISD nodes need to have different operand orders. 2998 // Shift amount is in rs2. 2999 SDValue Op0 = Op.getOperand(0); 3000 SDValue Op1 = Op.getOperand(1); 3001 unsigned Opc = RISCVISD::FSL; 3002 if (Op.getOpcode() == ISD::FSHR) { 3003 std::swap(Op0, Op1); 3004 Opc = RISCVISD::FSR; 3005 } 3006 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3007 } 3008 case ISD::TRUNCATE: { 3009 SDLoc DL(Op); 3010 MVT VT = Op.getSimpleValueType(); 3011 // Only custom-lower vector truncates 3012 if (!VT.isVector()) 3013 return Op; 3014 3015 // Truncates to mask types are handled differently 3016 if (VT.getVectorElementType() == MVT::i1) 3017 return lowerVectorMaskTrunc(Op, DAG); 3018 3019 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3020 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3021 // truncate by one power of two at a time. 3022 MVT DstEltVT = VT.getVectorElementType(); 3023 3024 SDValue Src = Op.getOperand(0); 3025 MVT SrcVT = Src.getSimpleValueType(); 3026 MVT SrcEltVT = SrcVT.getVectorElementType(); 3027 3028 assert(DstEltVT.bitsLT(SrcEltVT) && 3029 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3030 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3031 "Unexpected vector truncate lowering"); 3032 3033 MVT ContainerVT = SrcVT; 3034 if (SrcVT.isFixedLengthVector()) { 3035 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3036 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3037 } 3038 3039 SDValue Result = Src; 3040 SDValue Mask, VL; 3041 std::tie(Mask, VL) = 3042 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3043 LLVMContext &Context = *DAG.getContext(); 3044 const ElementCount Count = ContainerVT.getVectorElementCount(); 3045 do { 3046 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3047 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3048 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3049 Mask, VL); 3050 } while (SrcEltVT != DstEltVT); 3051 3052 if (SrcVT.isFixedLengthVector()) 3053 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3054 3055 return Result; 3056 } 3057 case ISD::ANY_EXTEND: 3058 case ISD::ZERO_EXTEND: 3059 if (Op.getOperand(0).getValueType().isVector() && 3060 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3061 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3062 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3063 case ISD::SIGN_EXTEND: 3064 if (Op.getOperand(0).getValueType().isVector() && 3065 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3066 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3067 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3068 case ISD::SPLAT_VECTOR_PARTS: 3069 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3070 case ISD::INSERT_VECTOR_ELT: 3071 return lowerINSERT_VECTOR_ELT(Op, DAG); 3072 case ISD::EXTRACT_VECTOR_ELT: 3073 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3074 case ISD::VSCALE: { 3075 MVT VT = Op.getSimpleValueType(); 3076 SDLoc DL(Op); 3077 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3078 // We define our scalable vector types for lmul=1 to use a 64 bit known 3079 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3080 // vscale as VLENB / 8. 3081 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3082 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3083 report_fatal_error("Support for VLEN==32 is incomplete."); 3084 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3085 // We assume VLENB is a multiple of 8. We manually choose the best shift 3086 // here because SimplifyDemandedBits isn't always able to simplify it. 3087 uint64_t Val = Op.getConstantOperandVal(0); 3088 if (isPowerOf2_64(Val)) { 3089 uint64_t Log2 = Log2_64(Val); 3090 if (Log2 < 3) 3091 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3092 DAG.getConstant(3 - Log2, DL, VT)); 3093 if (Log2 > 3) 3094 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3095 DAG.getConstant(Log2 - 3, DL, VT)); 3096 return VLENB; 3097 } 3098 // If the multiplier is a multiple of 8, scale it down to avoid needing 3099 // to shift the VLENB value. 3100 if ((Val % 8) == 0) 3101 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3102 DAG.getConstant(Val / 8, DL, VT)); 3103 } 3104 3105 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3106 DAG.getConstant(3, DL, VT)); 3107 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3108 } 3109 case ISD::FPOWI: { 3110 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3111 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3112 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3113 Op.getOperand(1).getValueType() == MVT::i32) { 3114 SDLoc DL(Op); 3115 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3116 SDValue Powi = 3117 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3118 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3119 DAG.getIntPtrConstant(0, DL)); 3120 } 3121 return SDValue(); 3122 } 3123 case ISD::FP_EXTEND: { 3124 // RVV can only do fp_extend to types double the size as the source. We 3125 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3126 // via f32. 3127 SDLoc DL(Op); 3128 MVT VT = Op.getSimpleValueType(); 3129 SDValue Src = Op.getOperand(0); 3130 MVT SrcVT = Src.getSimpleValueType(); 3131 3132 // Prepare any fixed-length vector operands. 3133 MVT ContainerVT = VT; 3134 if (SrcVT.isFixedLengthVector()) { 3135 ContainerVT = getContainerForFixedLengthVector(VT); 3136 MVT SrcContainerVT = 3137 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3138 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3139 } 3140 3141 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3142 SrcVT.getVectorElementType() != MVT::f16) { 3143 // For scalable vectors, we only need to close the gap between 3144 // vXf16->vXf64. 3145 if (!VT.isFixedLengthVector()) 3146 return Op; 3147 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3148 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3149 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3150 } 3151 3152 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3153 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3154 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3155 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3156 3157 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3158 DL, DAG, Subtarget); 3159 if (VT.isFixedLengthVector()) 3160 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3161 return Extend; 3162 } 3163 case ISD::FP_ROUND: { 3164 // RVV can only do fp_round to types half the size as the source. We 3165 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3166 // conversion instruction. 3167 SDLoc DL(Op); 3168 MVT VT = Op.getSimpleValueType(); 3169 SDValue Src = Op.getOperand(0); 3170 MVT SrcVT = Src.getSimpleValueType(); 3171 3172 // Prepare any fixed-length vector operands. 3173 MVT ContainerVT = VT; 3174 if (VT.isFixedLengthVector()) { 3175 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3176 ContainerVT = 3177 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3178 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3179 } 3180 3181 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3182 SrcVT.getVectorElementType() != MVT::f64) { 3183 // For scalable vectors, we only need to close the gap between 3184 // vXf64<->vXf16. 3185 if (!VT.isFixedLengthVector()) 3186 return Op; 3187 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3188 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3189 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3190 } 3191 3192 SDValue Mask, VL; 3193 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3194 3195 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3196 SDValue IntermediateRound = 3197 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3198 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3199 DL, DAG, Subtarget); 3200 3201 if (VT.isFixedLengthVector()) 3202 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3203 return Round; 3204 } 3205 case ISD::FP_TO_SINT: 3206 case ISD::FP_TO_UINT: 3207 case ISD::SINT_TO_FP: 3208 case ISD::UINT_TO_FP: { 3209 // RVV can only do fp<->int conversions to types half/double the size as 3210 // the source. We custom-lower any conversions that do two hops into 3211 // sequences. 3212 MVT VT = Op.getSimpleValueType(); 3213 if (!VT.isVector()) 3214 return Op; 3215 SDLoc DL(Op); 3216 SDValue Src = Op.getOperand(0); 3217 MVT EltVT = VT.getVectorElementType(); 3218 MVT SrcVT = Src.getSimpleValueType(); 3219 MVT SrcEltVT = SrcVT.getVectorElementType(); 3220 unsigned EltSize = EltVT.getSizeInBits(); 3221 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3222 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3223 "Unexpected vector element types"); 3224 3225 bool IsInt2FP = SrcEltVT.isInteger(); 3226 // Widening conversions 3227 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3228 if (IsInt2FP) { 3229 // Do a regular integer sign/zero extension then convert to float. 3230 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3231 VT.getVectorElementCount()); 3232 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3233 ? ISD::ZERO_EXTEND 3234 : ISD::SIGN_EXTEND; 3235 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3236 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3237 } 3238 // FP2Int 3239 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3240 // Do one doubling fp_extend then complete the operation by converting 3241 // to int. 3242 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3243 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3244 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3245 } 3246 3247 // Narrowing conversions 3248 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3249 if (IsInt2FP) { 3250 // One narrowing int_to_fp, then an fp_round. 3251 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3252 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3253 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3254 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3255 } 3256 // FP2Int 3257 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3258 // representable by the integer, the result is poison. 3259 MVT IVecVT = 3260 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3261 VT.getVectorElementCount()); 3262 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3263 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3264 } 3265 3266 // Scalable vectors can exit here. Patterns will handle equally-sized 3267 // conversions halving/doubling ones. 3268 if (!VT.isFixedLengthVector()) 3269 return Op; 3270 3271 // For fixed-length vectors we lower to a custom "VL" node. 3272 unsigned RVVOpc = 0; 3273 switch (Op.getOpcode()) { 3274 default: 3275 llvm_unreachable("Impossible opcode"); 3276 case ISD::FP_TO_SINT: 3277 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3278 break; 3279 case ISD::FP_TO_UINT: 3280 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3281 break; 3282 case ISD::SINT_TO_FP: 3283 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3284 break; 3285 case ISD::UINT_TO_FP: 3286 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3287 break; 3288 } 3289 3290 MVT ContainerVT, SrcContainerVT; 3291 // Derive the reference container type from the larger vector type. 3292 if (SrcEltSize > EltSize) { 3293 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3294 ContainerVT = 3295 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3296 } else { 3297 ContainerVT = getContainerForFixedLengthVector(VT); 3298 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3299 } 3300 3301 SDValue Mask, VL; 3302 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3303 3304 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3305 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3306 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3307 } 3308 case ISD::FP_TO_SINT_SAT: 3309 case ISD::FP_TO_UINT_SAT: 3310 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3311 case ISD::FTRUNC: 3312 case ISD::FCEIL: 3313 case ISD::FFLOOR: 3314 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3315 case ISD::VECREDUCE_ADD: 3316 case ISD::VECREDUCE_UMAX: 3317 case ISD::VECREDUCE_SMAX: 3318 case ISD::VECREDUCE_UMIN: 3319 case ISD::VECREDUCE_SMIN: 3320 return lowerVECREDUCE(Op, DAG); 3321 case ISD::VECREDUCE_AND: 3322 case ISD::VECREDUCE_OR: 3323 case ISD::VECREDUCE_XOR: 3324 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3325 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3326 return lowerVECREDUCE(Op, DAG); 3327 case ISD::VECREDUCE_FADD: 3328 case ISD::VECREDUCE_SEQ_FADD: 3329 case ISD::VECREDUCE_FMIN: 3330 case ISD::VECREDUCE_FMAX: 3331 return lowerFPVECREDUCE(Op, DAG); 3332 case ISD::VP_REDUCE_ADD: 3333 case ISD::VP_REDUCE_UMAX: 3334 case ISD::VP_REDUCE_SMAX: 3335 case ISD::VP_REDUCE_UMIN: 3336 case ISD::VP_REDUCE_SMIN: 3337 case ISD::VP_REDUCE_FADD: 3338 case ISD::VP_REDUCE_SEQ_FADD: 3339 case ISD::VP_REDUCE_FMIN: 3340 case ISD::VP_REDUCE_FMAX: 3341 return lowerVPREDUCE(Op, DAG); 3342 case ISD::VP_REDUCE_AND: 3343 case ISD::VP_REDUCE_OR: 3344 case ISD::VP_REDUCE_XOR: 3345 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3346 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3347 return lowerVPREDUCE(Op, DAG); 3348 case ISD::INSERT_SUBVECTOR: 3349 return lowerINSERT_SUBVECTOR(Op, DAG); 3350 case ISD::EXTRACT_SUBVECTOR: 3351 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3352 case ISD::STEP_VECTOR: 3353 return lowerSTEP_VECTOR(Op, DAG); 3354 case ISD::VECTOR_REVERSE: 3355 return lowerVECTOR_REVERSE(Op, DAG); 3356 case ISD::BUILD_VECTOR: 3357 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3358 case ISD::SPLAT_VECTOR: 3359 if (Op.getValueType().getVectorElementType() == MVT::i1) 3360 return lowerVectorMaskSplat(Op, DAG); 3361 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3362 case ISD::VECTOR_SHUFFLE: 3363 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3364 case ISD::CONCAT_VECTORS: { 3365 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3366 // better than going through the stack, as the default expansion does. 3367 SDLoc DL(Op); 3368 MVT VT = Op.getSimpleValueType(); 3369 unsigned NumOpElts = 3370 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3371 SDValue Vec = DAG.getUNDEF(VT); 3372 for (const auto &OpIdx : enumerate(Op->ops())) { 3373 SDValue SubVec = OpIdx.value(); 3374 // Don't insert undef subvectors. 3375 if (SubVec.isUndef()) 3376 continue; 3377 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3378 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3379 } 3380 return Vec; 3381 } 3382 case ISD::LOAD: 3383 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3384 return V; 3385 if (Op.getValueType().isFixedLengthVector()) 3386 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3387 return Op; 3388 case ISD::STORE: 3389 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3390 return V; 3391 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3392 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3393 return Op; 3394 case ISD::MLOAD: 3395 case ISD::VP_LOAD: 3396 return lowerMaskedLoad(Op, DAG); 3397 case ISD::MSTORE: 3398 case ISD::VP_STORE: 3399 return lowerMaskedStore(Op, DAG); 3400 case ISD::SETCC: 3401 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3402 case ISD::ADD: 3403 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3404 case ISD::SUB: 3405 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3406 case ISD::MUL: 3407 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3408 case ISD::MULHS: 3409 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3410 case ISD::MULHU: 3411 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3412 case ISD::AND: 3413 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3414 RISCVISD::AND_VL); 3415 case ISD::OR: 3416 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3417 RISCVISD::OR_VL); 3418 case ISD::XOR: 3419 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3420 RISCVISD::XOR_VL); 3421 case ISD::SDIV: 3422 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3423 case ISD::SREM: 3424 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3425 case ISD::UDIV: 3426 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3427 case ISD::UREM: 3428 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3429 case ISD::SHL: 3430 case ISD::SRA: 3431 case ISD::SRL: 3432 if (Op.getSimpleValueType().isFixedLengthVector()) 3433 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3434 // This can be called for an i32 shift amount that needs to be promoted. 3435 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3436 "Unexpected custom legalisation"); 3437 return SDValue(); 3438 case ISD::SADDSAT: 3439 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3440 case ISD::UADDSAT: 3441 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3442 case ISD::SSUBSAT: 3443 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3444 case ISD::USUBSAT: 3445 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3446 case ISD::FADD: 3447 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3448 case ISD::FSUB: 3449 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3450 case ISD::FMUL: 3451 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3452 case ISD::FDIV: 3453 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3454 case ISD::FNEG: 3455 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3456 case ISD::FABS: 3457 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3458 case ISD::FSQRT: 3459 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3460 case ISD::FMA: 3461 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3462 case ISD::SMIN: 3463 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3464 case ISD::SMAX: 3465 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3466 case ISD::UMIN: 3467 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3468 case ISD::UMAX: 3469 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3470 case ISD::FMINNUM: 3471 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3472 case ISD::FMAXNUM: 3473 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3474 case ISD::ABS: 3475 return lowerABS(Op, DAG); 3476 case ISD::CTLZ_ZERO_UNDEF: 3477 case ISD::CTTZ_ZERO_UNDEF: 3478 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3479 case ISD::VSELECT: 3480 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3481 case ISD::FCOPYSIGN: 3482 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3483 case ISD::MGATHER: 3484 case ISD::VP_GATHER: 3485 return lowerMaskedGather(Op, DAG); 3486 case ISD::MSCATTER: 3487 case ISD::VP_SCATTER: 3488 return lowerMaskedScatter(Op, DAG); 3489 case ISD::FLT_ROUNDS_: 3490 return lowerGET_ROUNDING(Op, DAG); 3491 case ISD::SET_ROUNDING: 3492 return lowerSET_ROUNDING(Op, DAG); 3493 case ISD::VP_SELECT: 3494 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3495 case ISD::VP_MERGE: 3496 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3497 case ISD::VP_ADD: 3498 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3499 case ISD::VP_SUB: 3500 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3501 case ISD::VP_MUL: 3502 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3503 case ISD::VP_SDIV: 3504 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3505 case ISD::VP_UDIV: 3506 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3507 case ISD::VP_SREM: 3508 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3509 case ISD::VP_UREM: 3510 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3511 case ISD::VP_AND: 3512 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3513 case ISD::VP_OR: 3514 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3515 case ISD::VP_XOR: 3516 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3517 case ISD::VP_ASHR: 3518 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3519 case ISD::VP_LSHR: 3520 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3521 case ISD::VP_SHL: 3522 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3523 case ISD::VP_FADD: 3524 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3525 case ISD::VP_FSUB: 3526 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3527 case ISD::VP_FMUL: 3528 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3529 case ISD::VP_FDIV: 3530 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3531 } 3532 } 3533 3534 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3535 SelectionDAG &DAG, unsigned Flags) { 3536 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3537 } 3538 3539 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3540 SelectionDAG &DAG, unsigned Flags) { 3541 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3542 Flags); 3543 } 3544 3545 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3546 SelectionDAG &DAG, unsigned Flags) { 3547 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3548 N->getOffset(), Flags); 3549 } 3550 3551 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3552 SelectionDAG &DAG, unsigned Flags) { 3553 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3554 } 3555 3556 template <class NodeTy> 3557 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3558 bool IsLocal) const { 3559 SDLoc DL(N); 3560 EVT Ty = getPointerTy(DAG.getDataLayout()); 3561 3562 if (isPositionIndependent()) { 3563 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3564 if (IsLocal) 3565 // Use PC-relative addressing to access the symbol. This generates the 3566 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3567 // %pcrel_lo(auipc)). 3568 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3569 3570 // Use PC-relative addressing to access the GOT for this symbol, then load 3571 // the address from the GOT. This generates the pattern (PseudoLA sym), 3572 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3573 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3574 } 3575 3576 switch (getTargetMachine().getCodeModel()) { 3577 default: 3578 report_fatal_error("Unsupported code model for lowering"); 3579 case CodeModel::Small: { 3580 // Generate a sequence for accessing addresses within the first 2 GiB of 3581 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3582 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3583 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3584 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3585 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3586 } 3587 case CodeModel::Medium: { 3588 // Generate a sequence for accessing addresses within any 2GiB range within 3589 // the address space. This generates the pattern (PseudoLLA sym), which 3590 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3591 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3592 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3593 } 3594 } 3595 } 3596 3597 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3598 SelectionDAG &DAG) const { 3599 SDLoc DL(Op); 3600 EVT Ty = Op.getValueType(); 3601 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3602 int64_t Offset = N->getOffset(); 3603 MVT XLenVT = Subtarget.getXLenVT(); 3604 3605 const GlobalValue *GV = N->getGlobal(); 3606 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3607 SDValue Addr = getAddr(N, DAG, IsLocal); 3608 3609 // In order to maximise the opportunity for common subexpression elimination, 3610 // emit a separate ADD node for the global address offset instead of folding 3611 // it in the global address node. Later peephole optimisations may choose to 3612 // fold it back in when profitable. 3613 if (Offset != 0) 3614 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3615 DAG.getConstant(Offset, DL, XLenVT)); 3616 return Addr; 3617 } 3618 3619 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3620 SelectionDAG &DAG) const { 3621 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3622 3623 return getAddr(N, DAG); 3624 } 3625 3626 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3627 SelectionDAG &DAG) const { 3628 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3629 3630 return getAddr(N, DAG); 3631 } 3632 3633 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3634 SelectionDAG &DAG) const { 3635 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3636 3637 return getAddr(N, DAG); 3638 } 3639 3640 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3641 SelectionDAG &DAG, 3642 bool UseGOT) const { 3643 SDLoc DL(N); 3644 EVT Ty = getPointerTy(DAG.getDataLayout()); 3645 const GlobalValue *GV = N->getGlobal(); 3646 MVT XLenVT = Subtarget.getXLenVT(); 3647 3648 if (UseGOT) { 3649 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3650 // load the address from the GOT and add the thread pointer. This generates 3651 // the pattern (PseudoLA_TLS_IE sym), which expands to 3652 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3653 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3654 SDValue Load = 3655 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3656 3657 // Add the thread pointer. 3658 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3659 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3660 } 3661 3662 // Generate a sequence for accessing the address relative to the thread 3663 // pointer, with the appropriate adjustment for the thread pointer offset. 3664 // This generates the pattern 3665 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3666 SDValue AddrHi = 3667 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3668 SDValue AddrAdd = 3669 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3670 SDValue AddrLo = 3671 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3672 3673 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3674 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3675 SDValue MNAdd = SDValue( 3676 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3677 0); 3678 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3679 } 3680 3681 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3682 SelectionDAG &DAG) const { 3683 SDLoc DL(N); 3684 EVT Ty = getPointerTy(DAG.getDataLayout()); 3685 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3686 const GlobalValue *GV = N->getGlobal(); 3687 3688 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3689 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3690 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3691 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3692 SDValue Load = 3693 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3694 3695 // Prepare argument list to generate call. 3696 ArgListTy Args; 3697 ArgListEntry Entry; 3698 Entry.Node = Load; 3699 Entry.Ty = CallTy; 3700 Args.push_back(Entry); 3701 3702 // Setup call to __tls_get_addr. 3703 TargetLowering::CallLoweringInfo CLI(DAG); 3704 CLI.setDebugLoc(DL) 3705 .setChain(DAG.getEntryNode()) 3706 .setLibCallee(CallingConv::C, CallTy, 3707 DAG.getExternalSymbol("__tls_get_addr", Ty), 3708 std::move(Args)); 3709 3710 return LowerCallTo(CLI).first; 3711 } 3712 3713 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3714 SelectionDAG &DAG) const { 3715 SDLoc DL(Op); 3716 EVT Ty = Op.getValueType(); 3717 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3718 int64_t Offset = N->getOffset(); 3719 MVT XLenVT = Subtarget.getXLenVT(); 3720 3721 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3722 3723 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3724 CallingConv::GHC) 3725 report_fatal_error("In GHC calling convention TLS is not supported"); 3726 3727 SDValue Addr; 3728 switch (Model) { 3729 case TLSModel::LocalExec: 3730 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3731 break; 3732 case TLSModel::InitialExec: 3733 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3734 break; 3735 case TLSModel::LocalDynamic: 3736 case TLSModel::GeneralDynamic: 3737 Addr = getDynamicTLSAddr(N, DAG); 3738 break; 3739 } 3740 3741 // In order to maximise the opportunity for common subexpression elimination, 3742 // emit a separate ADD node for the global address offset instead of folding 3743 // it in the global address node. Later peephole optimisations may choose to 3744 // fold it back in when profitable. 3745 if (Offset != 0) 3746 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3747 DAG.getConstant(Offset, DL, XLenVT)); 3748 return Addr; 3749 } 3750 3751 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3752 SDValue CondV = Op.getOperand(0); 3753 SDValue TrueV = Op.getOperand(1); 3754 SDValue FalseV = Op.getOperand(2); 3755 SDLoc DL(Op); 3756 MVT VT = Op.getSimpleValueType(); 3757 MVT XLenVT = Subtarget.getXLenVT(); 3758 3759 // Lower vector SELECTs to VSELECTs by splatting the condition. 3760 if (VT.isVector()) { 3761 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3762 SDValue CondSplat = VT.isScalableVector() 3763 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3764 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3765 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3766 } 3767 3768 // If the result type is XLenVT and CondV is the output of a SETCC node 3769 // which also operated on XLenVT inputs, then merge the SETCC node into the 3770 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3771 // compare+branch instructions. i.e.: 3772 // (select (setcc lhs, rhs, cc), truev, falsev) 3773 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3774 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3775 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3776 SDValue LHS = CondV.getOperand(0); 3777 SDValue RHS = CondV.getOperand(1); 3778 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3779 ISD::CondCode CCVal = CC->get(); 3780 3781 // Special case for a select of 2 constants that have a diffence of 1. 3782 // Normally this is done by DAGCombine, but if the select is introduced by 3783 // type legalization or op legalization, we miss it. Restricting to SETLT 3784 // case for now because that is what signed saturating add/sub need. 3785 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3786 // but we would probably want to swap the true/false values if the condition 3787 // is SETGE/SETLE to avoid an XORI. 3788 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3789 CCVal == ISD::SETLT) { 3790 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3791 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3792 if (TrueVal - 1 == FalseVal) 3793 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3794 if (TrueVal + 1 == FalseVal) 3795 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3796 } 3797 3798 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3799 3800 SDValue TargetCC = DAG.getCondCode(CCVal); 3801 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3802 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3803 } 3804 3805 // Otherwise: 3806 // (select condv, truev, falsev) 3807 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3808 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3809 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3810 3811 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3812 3813 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3814 } 3815 3816 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3817 SDValue CondV = Op.getOperand(1); 3818 SDLoc DL(Op); 3819 MVT XLenVT = Subtarget.getXLenVT(); 3820 3821 if (CondV.getOpcode() == ISD::SETCC && 3822 CondV.getOperand(0).getValueType() == XLenVT) { 3823 SDValue LHS = CondV.getOperand(0); 3824 SDValue RHS = CondV.getOperand(1); 3825 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3826 3827 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3828 3829 SDValue TargetCC = DAG.getCondCode(CCVal); 3830 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3831 LHS, RHS, TargetCC, Op.getOperand(2)); 3832 } 3833 3834 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3835 CondV, DAG.getConstant(0, DL, XLenVT), 3836 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3837 } 3838 3839 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3840 MachineFunction &MF = DAG.getMachineFunction(); 3841 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3842 3843 SDLoc DL(Op); 3844 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3845 getPointerTy(MF.getDataLayout())); 3846 3847 // vastart just stores the address of the VarArgsFrameIndex slot into the 3848 // memory location argument. 3849 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3850 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3851 MachinePointerInfo(SV)); 3852 } 3853 3854 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3855 SelectionDAG &DAG) const { 3856 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3857 MachineFunction &MF = DAG.getMachineFunction(); 3858 MachineFrameInfo &MFI = MF.getFrameInfo(); 3859 MFI.setFrameAddressIsTaken(true); 3860 Register FrameReg = RI.getFrameRegister(MF); 3861 int XLenInBytes = Subtarget.getXLen() / 8; 3862 3863 EVT VT = Op.getValueType(); 3864 SDLoc DL(Op); 3865 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3866 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3867 while (Depth--) { 3868 int Offset = -(XLenInBytes * 2); 3869 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3870 DAG.getIntPtrConstant(Offset, DL)); 3871 FrameAddr = 3872 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3873 } 3874 return FrameAddr; 3875 } 3876 3877 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3878 SelectionDAG &DAG) const { 3879 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3880 MachineFunction &MF = DAG.getMachineFunction(); 3881 MachineFrameInfo &MFI = MF.getFrameInfo(); 3882 MFI.setReturnAddressIsTaken(true); 3883 MVT XLenVT = Subtarget.getXLenVT(); 3884 int XLenInBytes = Subtarget.getXLen() / 8; 3885 3886 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3887 return SDValue(); 3888 3889 EVT VT = Op.getValueType(); 3890 SDLoc DL(Op); 3891 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3892 if (Depth) { 3893 int Off = -XLenInBytes; 3894 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3895 SDValue Offset = DAG.getConstant(Off, DL, VT); 3896 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3897 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3898 MachinePointerInfo()); 3899 } 3900 3901 // Return the value of the return address register, marking it an implicit 3902 // live-in. 3903 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3904 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3905 } 3906 3907 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3908 SelectionDAG &DAG) const { 3909 SDLoc DL(Op); 3910 SDValue Lo = Op.getOperand(0); 3911 SDValue Hi = Op.getOperand(1); 3912 SDValue Shamt = Op.getOperand(2); 3913 EVT VT = Lo.getValueType(); 3914 3915 // if Shamt-XLEN < 0: // Shamt < XLEN 3916 // Lo = Lo << Shamt 3917 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3918 // else: 3919 // Lo = 0 3920 // Hi = Lo << (Shamt-XLEN) 3921 3922 SDValue Zero = DAG.getConstant(0, DL, VT); 3923 SDValue One = DAG.getConstant(1, DL, VT); 3924 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3925 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3926 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3927 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3928 3929 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3930 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3931 SDValue ShiftRightLo = 3932 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3933 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3934 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3935 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3936 3937 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3938 3939 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3940 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3941 3942 SDValue Parts[2] = {Lo, Hi}; 3943 return DAG.getMergeValues(Parts, DL); 3944 } 3945 3946 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3947 bool IsSRA) const { 3948 SDLoc DL(Op); 3949 SDValue Lo = Op.getOperand(0); 3950 SDValue Hi = Op.getOperand(1); 3951 SDValue Shamt = Op.getOperand(2); 3952 EVT VT = Lo.getValueType(); 3953 3954 // SRA expansion: 3955 // if Shamt-XLEN < 0: // Shamt < XLEN 3956 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3957 // Hi = Hi >>s Shamt 3958 // else: 3959 // Lo = Hi >>s (Shamt-XLEN); 3960 // Hi = Hi >>s (XLEN-1) 3961 // 3962 // SRL expansion: 3963 // if Shamt-XLEN < 0: // Shamt < XLEN 3964 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3965 // Hi = Hi >>u Shamt 3966 // else: 3967 // Lo = Hi >>u (Shamt-XLEN); 3968 // Hi = 0; 3969 3970 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3971 3972 SDValue Zero = DAG.getConstant(0, DL, VT); 3973 SDValue One = DAG.getConstant(1, DL, VT); 3974 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3975 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3976 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3977 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3978 3979 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3980 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3981 SDValue ShiftLeftHi = 3982 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3983 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3984 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3985 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3986 SDValue HiFalse = 3987 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3988 3989 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3990 3991 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3992 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3993 3994 SDValue Parts[2] = {Lo, Hi}; 3995 return DAG.getMergeValues(Parts, DL); 3996 } 3997 3998 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3999 // legal equivalently-sized i8 type, so we can use that as a go-between. 4000 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4001 SelectionDAG &DAG) const { 4002 SDLoc DL(Op); 4003 MVT VT = Op.getSimpleValueType(); 4004 SDValue SplatVal = Op.getOperand(0); 4005 // All-zeros or all-ones splats are handled specially. 4006 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4007 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4008 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4009 } 4010 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4011 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4012 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4013 } 4014 MVT XLenVT = Subtarget.getXLenVT(); 4015 assert(SplatVal.getValueType() == XLenVT && 4016 "Unexpected type for i1 splat value"); 4017 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4018 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4019 DAG.getConstant(1, DL, XLenVT)); 4020 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4021 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4022 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4023 } 4024 4025 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4026 // illegal (currently only vXi64 RV32). 4027 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4028 // them to SPLAT_VECTOR_I64 4029 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4030 SelectionDAG &DAG) const { 4031 SDLoc DL(Op); 4032 MVT VecVT = Op.getSimpleValueType(); 4033 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4034 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4035 4036 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4037 SDValue Lo = Op.getOperand(0); 4038 SDValue Hi = Op.getOperand(1); 4039 4040 if (VecVT.isFixedLengthVector()) { 4041 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4042 SDLoc DL(Op); 4043 SDValue Mask, VL; 4044 std::tie(Mask, VL) = 4045 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4046 4047 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 4048 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4049 } 4050 4051 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4052 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4053 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4054 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4055 // node in order to try and match RVV vector/scalar instructions. 4056 if ((LoC >> 31) == HiC) 4057 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 4058 } 4059 4060 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4061 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4062 isa<ConstantSDNode>(Hi.getOperand(1)) && 4063 Hi.getConstantOperandVal(1) == 31) 4064 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 4065 4066 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4067 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 4068 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i32)); 4069 } 4070 4071 // Custom-lower extensions from mask vectors by using a vselect either with 1 4072 // for zero/any-extension or -1 for sign-extension: 4073 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4074 // Note that any-extension is lowered identically to zero-extension. 4075 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4076 int64_t ExtTrueVal) const { 4077 SDLoc DL(Op); 4078 MVT VecVT = Op.getSimpleValueType(); 4079 SDValue Src = Op.getOperand(0); 4080 // Only custom-lower extensions from mask types 4081 assert(Src.getValueType().isVector() && 4082 Src.getValueType().getVectorElementType() == MVT::i1); 4083 4084 MVT XLenVT = Subtarget.getXLenVT(); 4085 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4086 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4087 4088 if (VecVT.isScalableVector()) { 4089 // Be careful not to introduce illegal scalar types at this stage, and be 4090 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4091 // illegal and must be expanded. Since we know that the constants are 4092 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 4093 bool IsRV32E64 = 4094 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4095 4096 if (!IsRV32E64) { 4097 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4098 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4099 } else { 4100 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 4101 SplatTrueVal = 4102 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 4103 } 4104 4105 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4106 } 4107 4108 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4109 MVT I1ContainerVT = 4110 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4111 4112 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4113 4114 SDValue Mask, VL; 4115 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4116 4117 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 4118 SplatTrueVal = 4119 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 4120 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4121 SplatTrueVal, SplatZero, VL); 4122 4123 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4124 } 4125 4126 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4127 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4128 MVT ExtVT = Op.getSimpleValueType(); 4129 // Only custom-lower extensions from fixed-length vector types. 4130 if (!ExtVT.isFixedLengthVector()) 4131 return Op; 4132 MVT VT = Op.getOperand(0).getSimpleValueType(); 4133 // Grab the canonical container type for the extended type. Infer the smaller 4134 // type from that to ensure the same number of vector elements, as we know 4135 // the LMUL will be sufficient to hold the smaller type. 4136 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4137 // Get the extended container type manually to ensure the same number of 4138 // vector elements between source and dest. 4139 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4140 ContainerExtVT.getVectorElementCount()); 4141 4142 SDValue Op1 = 4143 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4144 4145 SDLoc DL(Op); 4146 SDValue Mask, VL; 4147 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4148 4149 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4150 4151 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4152 } 4153 4154 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4155 // setcc operation: 4156 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4157 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4158 SelectionDAG &DAG) const { 4159 SDLoc DL(Op); 4160 EVT MaskVT = Op.getValueType(); 4161 // Only expect to custom-lower truncations to mask types 4162 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4163 "Unexpected type for vector mask lowering"); 4164 SDValue Src = Op.getOperand(0); 4165 MVT VecVT = Src.getSimpleValueType(); 4166 4167 // If this is a fixed vector, we need to convert it to a scalable vector. 4168 MVT ContainerVT = VecVT; 4169 if (VecVT.isFixedLengthVector()) { 4170 ContainerVT = getContainerForFixedLengthVector(VecVT); 4171 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4172 } 4173 4174 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4175 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4176 4177 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 4178 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 4179 4180 if (VecVT.isScalableVector()) { 4181 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4182 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4183 } 4184 4185 SDValue Mask, VL; 4186 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4187 4188 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4189 SDValue Trunc = 4190 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4191 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4192 DAG.getCondCode(ISD::SETNE), Mask, VL); 4193 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4194 } 4195 4196 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4197 // first position of a vector, and that vector is slid up to the insert index. 4198 // By limiting the active vector length to index+1 and merging with the 4199 // original vector (with an undisturbed tail policy for elements >= VL), we 4200 // achieve the desired result of leaving all elements untouched except the one 4201 // at VL-1, which is replaced with the desired value. 4202 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4203 SelectionDAG &DAG) const { 4204 SDLoc DL(Op); 4205 MVT VecVT = Op.getSimpleValueType(); 4206 SDValue Vec = Op.getOperand(0); 4207 SDValue Val = Op.getOperand(1); 4208 SDValue Idx = Op.getOperand(2); 4209 4210 if (VecVT.getVectorElementType() == MVT::i1) { 4211 // FIXME: For now we just promote to an i8 vector and insert into that, 4212 // but this is probably not optimal. 4213 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4214 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4215 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4216 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4217 } 4218 4219 MVT ContainerVT = VecVT; 4220 // If the operand is a fixed-length vector, convert to a scalable one. 4221 if (VecVT.isFixedLengthVector()) { 4222 ContainerVT = getContainerForFixedLengthVector(VecVT); 4223 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4224 } 4225 4226 MVT XLenVT = Subtarget.getXLenVT(); 4227 4228 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4229 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4230 // Even i64-element vectors on RV32 can be lowered without scalar 4231 // legalization if the most-significant 32 bits of the value are not affected 4232 // by the sign-extension of the lower 32 bits. 4233 // TODO: We could also catch sign extensions of a 32-bit value. 4234 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4235 const auto *CVal = cast<ConstantSDNode>(Val); 4236 if (isInt<32>(CVal->getSExtValue())) { 4237 IsLegalInsert = true; 4238 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4239 } 4240 } 4241 4242 SDValue Mask, VL; 4243 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4244 4245 SDValue ValInVec; 4246 4247 if (IsLegalInsert) { 4248 unsigned Opc = 4249 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4250 if (isNullConstant(Idx)) { 4251 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4252 if (!VecVT.isFixedLengthVector()) 4253 return Vec; 4254 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4255 } 4256 ValInVec = 4257 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4258 } else { 4259 // On RV32, i64-element vectors must be specially handled to place the 4260 // value at element 0, by using two vslide1up instructions in sequence on 4261 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4262 // this. 4263 SDValue One = DAG.getConstant(1, DL, XLenVT); 4264 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4265 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4266 MVT I32ContainerVT = 4267 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4268 SDValue I32Mask = 4269 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4270 // Limit the active VL to two. 4271 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4272 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4273 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4274 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 4275 InsertI64VL); 4276 // First slide in the hi value, then the lo in underneath it. 4277 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4278 ValHi, I32Mask, InsertI64VL); 4279 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4280 ValLo, I32Mask, InsertI64VL); 4281 // Bitcast back to the right container type. 4282 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4283 } 4284 4285 // Now that the value is in a vector, slide it into position. 4286 SDValue InsertVL = 4287 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4288 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4289 ValInVec, Idx, Mask, InsertVL); 4290 if (!VecVT.isFixedLengthVector()) 4291 return Slideup; 4292 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4293 } 4294 4295 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4296 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4297 // types this is done using VMV_X_S to allow us to glean information about the 4298 // sign bits of the result. 4299 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4300 SelectionDAG &DAG) const { 4301 SDLoc DL(Op); 4302 SDValue Idx = Op.getOperand(1); 4303 SDValue Vec = Op.getOperand(0); 4304 EVT EltVT = Op.getValueType(); 4305 MVT VecVT = Vec.getSimpleValueType(); 4306 MVT XLenVT = Subtarget.getXLenVT(); 4307 4308 if (VecVT.getVectorElementType() == MVT::i1) { 4309 if (VecVT.isFixedLengthVector()) { 4310 unsigned NumElts = VecVT.getVectorNumElements(); 4311 if (NumElts >= 8) { 4312 MVT WideEltVT; 4313 unsigned WidenVecLen; 4314 SDValue ExtractElementIdx; 4315 SDValue ExtractBitIdx; 4316 unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors(); 4317 MVT LargestEltVT = MVT::getIntegerVT( 4318 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4319 if (NumElts <= LargestEltVT.getSizeInBits()) { 4320 assert(isPowerOf2_32(NumElts) && 4321 "the number of elements should be power of 2"); 4322 WideEltVT = MVT::getIntegerVT(NumElts); 4323 WidenVecLen = 1; 4324 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4325 ExtractBitIdx = Idx; 4326 } else { 4327 WideEltVT = LargestEltVT; 4328 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4329 // extract element index = index / element width 4330 ExtractElementIdx = DAG.getNode( 4331 ISD::SRL, DL, XLenVT, Idx, 4332 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4333 // mask bit index = index % element width 4334 ExtractBitIdx = DAG.getNode( 4335 ISD::AND, DL, XLenVT, Idx, 4336 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4337 } 4338 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4339 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4340 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4341 Vec, ExtractElementIdx); 4342 // Extract the bit from GPR. 4343 SDValue ShiftRight = 4344 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4345 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4346 DAG.getConstant(1, DL, XLenVT)); 4347 } 4348 } 4349 // Otherwise, promote to an i8 vector and extract from that. 4350 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4351 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4352 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4353 } 4354 4355 // If this is a fixed vector, we need to convert it to a scalable vector. 4356 MVT ContainerVT = VecVT; 4357 if (VecVT.isFixedLengthVector()) { 4358 ContainerVT = getContainerForFixedLengthVector(VecVT); 4359 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4360 } 4361 4362 // If the index is 0, the vector is already in the right position. 4363 if (!isNullConstant(Idx)) { 4364 // Use a VL of 1 to avoid processing more elements than we need. 4365 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4366 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4367 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4368 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4369 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4370 } 4371 4372 if (!EltVT.isInteger()) { 4373 // Floating-point extracts are handled in TableGen. 4374 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4375 DAG.getConstant(0, DL, XLenVT)); 4376 } 4377 4378 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4379 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4380 } 4381 4382 // Some RVV intrinsics may claim that they want an integer operand to be 4383 // promoted or expanded. 4384 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4385 const RISCVSubtarget &Subtarget) { 4386 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4387 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4388 "Unexpected opcode"); 4389 4390 if (!Subtarget.hasVInstructions()) 4391 return SDValue(); 4392 4393 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4394 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4395 SDLoc DL(Op); 4396 4397 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4398 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4399 if (!II || !II->hasSplatOperand()) 4400 return SDValue(); 4401 4402 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4403 assert(SplatOp < Op.getNumOperands()); 4404 4405 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4406 SDValue &ScalarOp = Operands[SplatOp]; 4407 MVT OpVT = ScalarOp.getSimpleValueType(); 4408 MVT XLenVT = Subtarget.getXLenVT(); 4409 4410 // If this isn't a scalar, or its type is XLenVT we're done. 4411 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4412 return SDValue(); 4413 4414 // Simplest case is that the operand needs to be promoted to XLenVT. 4415 if (OpVT.bitsLT(XLenVT)) { 4416 // If the operand is a constant, sign extend to increase our chances 4417 // of being able to use a .vi instruction. ANY_EXTEND would become a 4418 // a zero extend and the simm5 check in isel would fail. 4419 // FIXME: Should we ignore the upper bits in isel instead? 4420 unsigned ExtOpc = 4421 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4422 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4423 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4424 } 4425 4426 // Use the previous operand to get the vXi64 VT. The result might be a mask 4427 // VT for compares. Using the previous operand assumes that the previous 4428 // operand will never have a smaller element size than a scalar operand and 4429 // that a widening operation never uses SEW=64. 4430 // NOTE: If this fails the below assert, we can probably just find the 4431 // element count from any operand or result and use it to construct the VT. 4432 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4433 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4434 4435 // The more complex case is when the scalar is larger than XLenVT. 4436 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4437 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4438 4439 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4440 // on the instruction to sign-extend since SEW>XLEN. 4441 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4442 if (isInt<32>(CVal->getSExtValue())) { 4443 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4444 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4445 } 4446 } 4447 4448 // We need to convert the scalar to a splat vector. 4449 // FIXME: Can we implicitly truncate the scalar if it is known to 4450 // be sign extended? 4451 SDValue VL = getVLOperand(Op); 4452 assert(VL.getValueType() == XLenVT); 4453 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4454 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4455 } 4456 4457 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4458 SelectionDAG &DAG) const { 4459 unsigned IntNo = Op.getConstantOperandVal(0); 4460 SDLoc DL(Op); 4461 MVT XLenVT = Subtarget.getXLenVT(); 4462 4463 switch (IntNo) { 4464 default: 4465 break; // Don't custom lower most intrinsics. 4466 case Intrinsic::thread_pointer: { 4467 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4468 return DAG.getRegister(RISCV::X4, PtrVT); 4469 } 4470 case Intrinsic::riscv_orc_b: 4471 case Intrinsic::riscv_brev8: { 4472 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4473 unsigned Opc = 4474 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4475 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4476 DAG.getConstant(7, DL, XLenVT)); 4477 } 4478 case Intrinsic::riscv_grev: 4479 case Intrinsic::riscv_gorc: { 4480 unsigned Opc = 4481 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4482 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4483 } 4484 case Intrinsic::riscv_zip: 4485 case Intrinsic::riscv_unzip: { 4486 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4487 // For i32 the immdiate is 15. For i64 the immediate is 31. 4488 unsigned Opc = 4489 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4490 unsigned BitWidth = Op.getValueSizeInBits(); 4491 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4492 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4493 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4494 } 4495 case Intrinsic::riscv_shfl: 4496 case Intrinsic::riscv_unshfl: { 4497 unsigned Opc = 4498 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4499 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4500 } 4501 case Intrinsic::riscv_bcompress: 4502 case Intrinsic::riscv_bdecompress: { 4503 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4504 : RISCVISD::BDECOMPRESS; 4505 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4506 } 4507 case Intrinsic::riscv_bfp: 4508 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4509 Op.getOperand(2)); 4510 case Intrinsic::riscv_fsl: 4511 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4512 Op.getOperand(2), Op.getOperand(3)); 4513 case Intrinsic::riscv_fsr: 4514 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4515 Op.getOperand(2), Op.getOperand(3)); 4516 case Intrinsic::riscv_vmv_x_s: 4517 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4518 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4519 Op.getOperand(1)); 4520 case Intrinsic::riscv_vmv_v_x: 4521 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4522 Op.getSimpleValueType(), DL, DAG, Subtarget); 4523 case Intrinsic::riscv_vfmv_v_f: 4524 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4525 Op.getOperand(1), Op.getOperand(2)); 4526 case Intrinsic::riscv_vmv_s_x: { 4527 SDValue Scalar = Op.getOperand(2); 4528 4529 if (Scalar.getValueType().bitsLE(XLenVT)) { 4530 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4531 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4532 Op.getOperand(1), Scalar, Op.getOperand(3)); 4533 } 4534 4535 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4536 4537 // This is an i64 value that lives in two scalar registers. We have to 4538 // insert this in a convoluted way. First we build vXi64 splat containing 4539 // the/ two values that we assemble using some bit math. Next we'll use 4540 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4541 // to merge element 0 from our splat into the source vector. 4542 // FIXME: This is probably not the best way to do this, but it is 4543 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4544 // point. 4545 // sw lo, (a0) 4546 // sw hi, 4(a0) 4547 // vlse vX, (a0) 4548 // 4549 // vid.v vVid 4550 // vmseq.vx mMask, vVid, 0 4551 // vmerge.vvm vDest, vSrc, vVal, mMask 4552 MVT VT = Op.getSimpleValueType(); 4553 SDValue Vec = Op.getOperand(1); 4554 SDValue VL = getVLOperand(Op); 4555 4556 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4557 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4558 DAG.getConstant(0, DL, MVT::i32), VL); 4559 4560 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4561 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4562 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4563 SDValue SelectCond = 4564 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4565 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4566 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4567 Vec, VL); 4568 } 4569 case Intrinsic::riscv_vslide1up: 4570 case Intrinsic::riscv_vslide1down: 4571 case Intrinsic::riscv_vslide1up_mask: 4572 case Intrinsic::riscv_vslide1down_mask: { 4573 // We need to special case these when the scalar is larger than XLen. 4574 unsigned NumOps = Op.getNumOperands(); 4575 bool IsMasked = NumOps == 7; 4576 unsigned OpOffset = IsMasked ? 1 : 0; 4577 SDValue Scalar = Op.getOperand(2 + OpOffset); 4578 if (Scalar.getValueType().bitsLE(XLenVT)) 4579 break; 4580 4581 // Splatting a sign extended constant is fine. 4582 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4583 if (isInt<32>(CVal->getSExtValue())) 4584 break; 4585 4586 MVT VT = Op.getSimpleValueType(); 4587 assert(VT.getVectorElementType() == MVT::i64 && 4588 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4589 4590 // Convert the vector source to the equivalent nxvXi32 vector. 4591 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4592 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4593 4594 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4595 DAG.getConstant(0, DL, XLenVT)); 4596 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4597 DAG.getConstant(1, DL, XLenVT)); 4598 4599 // Double the VL since we halved SEW. 4600 SDValue VL = getVLOperand(Op); 4601 SDValue I32VL = 4602 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4603 4604 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4605 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4606 4607 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4608 // instructions. 4609 if (IntNo == Intrinsic::riscv_vslide1up || 4610 IntNo == Intrinsic::riscv_vslide1up_mask) { 4611 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4612 I32Mask, I32VL); 4613 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4614 I32Mask, I32VL); 4615 } else { 4616 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4617 I32Mask, I32VL); 4618 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4619 I32Mask, I32VL); 4620 } 4621 4622 // Convert back to nxvXi64. 4623 Vec = DAG.getBitcast(VT, Vec); 4624 4625 if (!IsMasked) 4626 return Vec; 4627 4628 // Apply mask after the operation. 4629 SDValue Mask = Op.getOperand(NumOps - 3); 4630 SDValue MaskedOff = Op.getOperand(1); 4631 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4632 } 4633 } 4634 4635 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4636 } 4637 4638 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4639 SelectionDAG &DAG) const { 4640 unsigned IntNo = Op.getConstantOperandVal(1); 4641 switch (IntNo) { 4642 default: 4643 break; 4644 case Intrinsic::riscv_masked_strided_load: { 4645 SDLoc DL(Op); 4646 MVT XLenVT = Subtarget.getXLenVT(); 4647 4648 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4649 // the selection of the masked intrinsics doesn't do this for us. 4650 SDValue Mask = Op.getOperand(5); 4651 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4652 4653 MVT VT = Op->getSimpleValueType(0); 4654 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4655 4656 SDValue PassThru = Op.getOperand(2); 4657 if (!IsUnmasked) { 4658 MVT MaskVT = 4659 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4660 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4661 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4662 } 4663 4664 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4665 4666 SDValue IntID = DAG.getTargetConstant( 4667 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4668 XLenVT); 4669 4670 auto *Load = cast<MemIntrinsicSDNode>(Op); 4671 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4672 if (IsUnmasked) 4673 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4674 else 4675 Ops.push_back(PassThru); 4676 Ops.push_back(Op.getOperand(3)); // Ptr 4677 Ops.push_back(Op.getOperand(4)); // Stride 4678 if (!IsUnmasked) 4679 Ops.push_back(Mask); 4680 Ops.push_back(VL); 4681 if (!IsUnmasked) { 4682 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4683 Ops.push_back(Policy); 4684 } 4685 4686 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4687 SDValue Result = 4688 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4689 Load->getMemoryVT(), Load->getMemOperand()); 4690 SDValue Chain = Result.getValue(1); 4691 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4692 return DAG.getMergeValues({Result, Chain}, DL); 4693 } 4694 } 4695 4696 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4697 } 4698 4699 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4700 SelectionDAG &DAG) const { 4701 unsigned IntNo = Op.getConstantOperandVal(1); 4702 switch (IntNo) { 4703 default: 4704 break; 4705 case Intrinsic::riscv_masked_strided_store: { 4706 SDLoc DL(Op); 4707 MVT XLenVT = Subtarget.getXLenVT(); 4708 4709 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4710 // the selection of the masked intrinsics doesn't do this for us. 4711 SDValue Mask = Op.getOperand(5); 4712 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4713 4714 SDValue Val = Op.getOperand(2); 4715 MVT VT = Val.getSimpleValueType(); 4716 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4717 4718 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4719 if (!IsUnmasked) { 4720 MVT MaskVT = 4721 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4722 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4723 } 4724 4725 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4726 4727 SDValue IntID = DAG.getTargetConstant( 4728 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4729 XLenVT); 4730 4731 auto *Store = cast<MemIntrinsicSDNode>(Op); 4732 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4733 Ops.push_back(Val); 4734 Ops.push_back(Op.getOperand(3)); // Ptr 4735 Ops.push_back(Op.getOperand(4)); // Stride 4736 if (!IsUnmasked) 4737 Ops.push_back(Mask); 4738 Ops.push_back(VL); 4739 4740 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4741 Ops, Store->getMemoryVT(), 4742 Store->getMemOperand()); 4743 } 4744 } 4745 4746 return SDValue(); 4747 } 4748 4749 static MVT getLMUL1VT(MVT VT) { 4750 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4751 "Unexpected vector MVT"); 4752 return MVT::getScalableVectorVT( 4753 VT.getVectorElementType(), 4754 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4755 } 4756 4757 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4758 switch (ISDOpcode) { 4759 default: 4760 llvm_unreachable("Unhandled reduction"); 4761 case ISD::VECREDUCE_ADD: 4762 return RISCVISD::VECREDUCE_ADD_VL; 4763 case ISD::VECREDUCE_UMAX: 4764 return RISCVISD::VECREDUCE_UMAX_VL; 4765 case ISD::VECREDUCE_SMAX: 4766 return RISCVISD::VECREDUCE_SMAX_VL; 4767 case ISD::VECREDUCE_UMIN: 4768 return RISCVISD::VECREDUCE_UMIN_VL; 4769 case ISD::VECREDUCE_SMIN: 4770 return RISCVISD::VECREDUCE_SMIN_VL; 4771 case ISD::VECREDUCE_AND: 4772 return RISCVISD::VECREDUCE_AND_VL; 4773 case ISD::VECREDUCE_OR: 4774 return RISCVISD::VECREDUCE_OR_VL; 4775 case ISD::VECREDUCE_XOR: 4776 return RISCVISD::VECREDUCE_XOR_VL; 4777 } 4778 } 4779 4780 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4781 SelectionDAG &DAG, 4782 bool IsVP) const { 4783 SDLoc DL(Op); 4784 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4785 MVT VecVT = Vec.getSimpleValueType(); 4786 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4787 Op.getOpcode() == ISD::VECREDUCE_OR || 4788 Op.getOpcode() == ISD::VECREDUCE_XOR || 4789 Op.getOpcode() == ISD::VP_REDUCE_AND || 4790 Op.getOpcode() == ISD::VP_REDUCE_OR || 4791 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4792 "Unexpected reduction lowering"); 4793 4794 MVT XLenVT = Subtarget.getXLenVT(); 4795 assert(Op.getValueType() == XLenVT && 4796 "Expected reduction output to be legalized to XLenVT"); 4797 4798 MVT ContainerVT = VecVT; 4799 if (VecVT.isFixedLengthVector()) { 4800 ContainerVT = getContainerForFixedLengthVector(VecVT); 4801 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4802 } 4803 4804 SDValue Mask, VL; 4805 if (IsVP) { 4806 Mask = Op.getOperand(2); 4807 VL = Op.getOperand(3); 4808 } else { 4809 std::tie(Mask, VL) = 4810 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4811 } 4812 4813 unsigned BaseOpc; 4814 ISD::CondCode CC; 4815 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4816 4817 switch (Op.getOpcode()) { 4818 default: 4819 llvm_unreachable("Unhandled reduction"); 4820 case ISD::VECREDUCE_AND: 4821 case ISD::VP_REDUCE_AND: { 4822 // vcpop ~x == 0 4823 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4824 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4825 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4826 CC = ISD::SETEQ; 4827 BaseOpc = ISD::AND; 4828 break; 4829 } 4830 case ISD::VECREDUCE_OR: 4831 case ISD::VP_REDUCE_OR: 4832 // vcpop x != 0 4833 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4834 CC = ISD::SETNE; 4835 BaseOpc = ISD::OR; 4836 break; 4837 case ISD::VECREDUCE_XOR: 4838 case ISD::VP_REDUCE_XOR: { 4839 // ((vcpop x) & 1) != 0 4840 SDValue One = DAG.getConstant(1, DL, XLenVT); 4841 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4842 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4843 CC = ISD::SETNE; 4844 BaseOpc = ISD::XOR; 4845 break; 4846 } 4847 } 4848 4849 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4850 4851 if (!IsVP) 4852 return SetCC; 4853 4854 // Now include the start value in the operation. 4855 // Note that we must return the start value when no elements are operated 4856 // upon. The vcpop instructions we've emitted in each case above will return 4857 // 0 for an inactive vector, and so we've already received the neutral value: 4858 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4859 // can simply include the start value. 4860 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4861 } 4862 4863 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4864 SelectionDAG &DAG) const { 4865 SDLoc DL(Op); 4866 SDValue Vec = Op.getOperand(0); 4867 EVT VecEVT = Vec.getValueType(); 4868 4869 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4870 4871 // Due to ordering in legalize types we may have a vector type that needs to 4872 // be split. Do that manually so we can get down to a legal type. 4873 while (getTypeAction(*DAG.getContext(), VecEVT) == 4874 TargetLowering::TypeSplitVector) { 4875 SDValue Lo, Hi; 4876 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4877 VecEVT = Lo.getValueType(); 4878 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4879 } 4880 4881 // TODO: The type may need to be widened rather than split. Or widened before 4882 // it can be split. 4883 if (!isTypeLegal(VecEVT)) 4884 return SDValue(); 4885 4886 MVT VecVT = VecEVT.getSimpleVT(); 4887 MVT VecEltVT = VecVT.getVectorElementType(); 4888 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4889 4890 MVT ContainerVT = VecVT; 4891 if (VecVT.isFixedLengthVector()) { 4892 ContainerVT = getContainerForFixedLengthVector(VecVT); 4893 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4894 } 4895 4896 MVT M1VT = getLMUL1VT(ContainerVT); 4897 MVT XLenVT = Subtarget.getXLenVT(); 4898 4899 SDValue Mask, VL; 4900 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4901 4902 SDValue NeutralElem = 4903 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4904 SDValue IdentitySplat = lowerScalarSplat( 4905 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4906 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4907 IdentitySplat, Mask, VL); 4908 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4909 DAG.getConstant(0, DL, XLenVT)); 4910 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4911 } 4912 4913 // Given a reduction op, this function returns the matching reduction opcode, 4914 // the vector SDValue and the scalar SDValue required to lower this to a 4915 // RISCVISD node. 4916 static std::tuple<unsigned, SDValue, SDValue> 4917 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4918 SDLoc DL(Op); 4919 auto Flags = Op->getFlags(); 4920 unsigned Opcode = Op.getOpcode(); 4921 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4922 switch (Opcode) { 4923 default: 4924 llvm_unreachable("Unhandled reduction"); 4925 case ISD::VECREDUCE_FADD: { 4926 // Use positive zero if we can. It is cheaper to materialize. 4927 SDValue Zero = 4928 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 4929 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 4930 } 4931 case ISD::VECREDUCE_SEQ_FADD: 4932 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4933 Op.getOperand(0)); 4934 case ISD::VECREDUCE_FMIN: 4935 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4936 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4937 case ISD::VECREDUCE_FMAX: 4938 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4939 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4940 } 4941 } 4942 4943 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4944 SelectionDAG &DAG) const { 4945 SDLoc DL(Op); 4946 MVT VecEltVT = Op.getSimpleValueType(); 4947 4948 unsigned RVVOpcode; 4949 SDValue VectorVal, ScalarVal; 4950 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4951 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4952 MVT VecVT = VectorVal.getSimpleValueType(); 4953 4954 MVT ContainerVT = VecVT; 4955 if (VecVT.isFixedLengthVector()) { 4956 ContainerVT = getContainerForFixedLengthVector(VecVT); 4957 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4958 } 4959 4960 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4961 MVT XLenVT = Subtarget.getXLenVT(); 4962 4963 SDValue Mask, VL; 4964 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4965 4966 SDValue ScalarSplat = lowerScalarSplat( 4967 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4968 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4969 VectorVal, ScalarSplat, Mask, VL); 4970 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4971 DAG.getConstant(0, DL, XLenVT)); 4972 } 4973 4974 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4975 switch (ISDOpcode) { 4976 default: 4977 llvm_unreachable("Unhandled reduction"); 4978 case ISD::VP_REDUCE_ADD: 4979 return RISCVISD::VECREDUCE_ADD_VL; 4980 case ISD::VP_REDUCE_UMAX: 4981 return RISCVISD::VECREDUCE_UMAX_VL; 4982 case ISD::VP_REDUCE_SMAX: 4983 return RISCVISD::VECREDUCE_SMAX_VL; 4984 case ISD::VP_REDUCE_UMIN: 4985 return RISCVISD::VECREDUCE_UMIN_VL; 4986 case ISD::VP_REDUCE_SMIN: 4987 return RISCVISD::VECREDUCE_SMIN_VL; 4988 case ISD::VP_REDUCE_AND: 4989 return RISCVISD::VECREDUCE_AND_VL; 4990 case ISD::VP_REDUCE_OR: 4991 return RISCVISD::VECREDUCE_OR_VL; 4992 case ISD::VP_REDUCE_XOR: 4993 return RISCVISD::VECREDUCE_XOR_VL; 4994 case ISD::VP_REDUCE_FADD: 4995 return RISCVISD::VECREDUCE_FADD_VL; 4996 case ISD::VP_REDUCE_SEQ_FADD: 4997 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4998 case ISD::VP_REDUCE_FMAX: 4999 return RISCVISD::VECREDUCE_FMAX_VL; 5000 case ISD::VP_REDUCE_FMIN: 5001 return RISCVISD::VECREDUCE_FMIN_VL; 5002 } 5003 } 5004 5005 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5006 SelectionDAG &DAG) const { 5007 SDLoc DL(Op); 5008 SDValue Vec = Op.getOperand(1); 5009 EVT VecEVT = Vec.getValueType(); 5010 5011 // TODO: The type may need to be widened rather than split. Or widened before 5012 // it can be split. 5013 if (!isTypeLegal(VecEVT)) 5014 return SDValue(); 5015 5016 MVT VecVT = VecEVT.getSimpleVT(); 5017 MVT VecEltVT = VecVT.getVectorElementType(); 5018 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5019 5020 MVT ContainerVT = VecVT; 5021 if (VecVT.isFixedLengthVector()) { 5022 ContainerVT = getContainerForFixedLengthVector(VecVT); 5023 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5024 } 5025 5026 SDValue VL = Op.getOperand(3); 5027 SDValue Mask = Op.getOperand(2); 5028 5029 MVT M1VT = getLMUL1VT(ContainerVT); 5030 MVT XLenVT = Subtarget.getXLenVT(); 5031 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5032 5033 SDValue StartSplat = 5034 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 5035 DL, DAG, Subtarget); 5036 SDValue Reduction = 5037 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5038 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5039 DAG.getConstant(0, DL, XLenVT)); 5040 if (!VecVT.isInteger()) 5041 return Elt0; 5042 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5043 } 5044 5045 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5046 SelectionDAG &DAG) const { 5047 SDValue Vec = Op.getOperand(0); 5048 SDValue SubVec = Op.getOperand(1); 5049 MVT VecVT = Vec.getSimpleValueType(); 5050 MVT SubVecVT = SubVec.getSimpleValueType(); 5051 5052 SDLoc DL(Op); 5053 MVT XLenVT = Subtarget.getXLenVT(); 5054 unsigned OrigIdx = Op.getConstantOperandVal(2); 5055 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5056 5057 // We don't have the ability to slide mask vectors up indexed by their i1 5058 // elements; the smallest we can do is i8. Often we are able to bitcast to 5059 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5060 // into a scalable one, we might not necessarily have enough scalable 5061 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5062 if (SubVecVT.getVectorElementType() == MVT::i1 && 5063 (OrigIdx != 0 || !Vec.isUndef())) { 5064 if (VecVT.getVectorMinNumElements() >= 8 && 5065 SubVecVT.getVectorMinNumElements() >= 8) { 5066 assert(OrigIdx % 8 == 0 && "Invalid index"); 5067 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5068 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5069 "Unexpected mask vector lowering"); 5070 OrigIdx /= 8; 5071 SubVecVT = 5072 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5073 SubVecVT.isScalableVector()); 5074 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5075 VecVT.isScalableVector()); 5076 Vec = DAG.getBitcast(VecVT, Vec); 5077 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5078 } else { 5079 // We can't slide this mask vector up indexed by its i1 elements. 5080 // This poses a problem when we wish to insert a scalable vector which 5081 // can't be re-expressed as a larger type. Just choose the slow path and 5082 // extend to a larger type, then truncate back down. 5083 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5084 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5085 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5086 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5087 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5088 Op.getOperand(2)); 5089 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5090 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5091 } 5092 } 5093 5094 // If the subvector vector is a fixed-length type, we cannot use subregister 5095 // manipulation to simplify the codegen; we don't know which register of a 5096 // LMUL group contains the specific subvector as we only know the minimum 5097 // register size. Therefore we must slide the vector group up the full 5098 // amount. 5099 if (SubVecVT.isFixedLengthVector()) { 5100 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5101 return Op; 5102 MVT ContainerVT = VecVT; 5103 if (VecVT.isFixedLengthVector()) { 5104 ContainerVT = getContainerForFixedLengthVector(VecVT); 5105 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5106 } 5107 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5108 DAG.getUNDEF(ContainerVT), SubVec, 5109 DAG.getConstant(0, DL, XLenVT)); 5110 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5111 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5112 return DAG.getBitcast(Op.getValueType(), SubVec); 5113 } 5114 SDValue Mask = 5115 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5116 // Set the vector length to only the number of elements we care about. Note 5117 // that for slideup this includes the offset. 5118 SDValue VL = 5119 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5120 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5121 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5122 SubVec, SlideupAmt, Mask, VL); 5123 if (VecVT.isFixedLengthVector()) 5124 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5125 return DAG.getBitcast(Op.getValueType(), Slideup); 5126 } 5127 5128 unsigned SubRegIdx, RemIdx; 5129 std::tie(SubRegIdx, RemIdx) = 5130 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5131 VecVT, SubVecVT, OrigIdx, TRI); 5132 5133 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5134 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5135 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5136 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5137 5138 // 1. If the Idx has been completely eliminated and this subvector's size is 5139 // a vector register or a multiple thereof, or the surrounding elements are 5140 // undef, then this is a subvector insert which naturally aligns to a vector 5141 // register. These can easily be handled using subregister manipulation. 5142 // 2. If the subvector is smaller than a vector register, then the insertion 5143 // must preserve the undisturbed elements of the register. We do this by 5144 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5145 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5146 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5147 // LMUL=1 type back into the larger vector (resolving to another subregister 5148 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5149 // to avoid allocating a large register group to hold our subvector. 5150 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5151 return Op; 5152 5153 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5154 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5155 // (in our case undisturbed). This means we can set up a subvector insertion 5156 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5157 // size of the subvector. 5158 MVT InterSubVT = VecVT; 5159 SDValue AlignedExtract = Vec; 5160 unsigned AlignedIdx = OrigIdx - RemIdx; 5161 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5162 InterSubVT = getLMUL1VT(VecVT); 5163 // Extract a subvector equal to the nearest full vector register type. This 5164 // should resolve to a EXTRACT_SUBREG instruction. 5165 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5166 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5167 } 5168 5169 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5170 // For scalable vectors this must be further multiplied by vscale. 5171 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5172 5173 SDValue Mask, VL; 5174 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5175 5176 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5177 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5178 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5179 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5180 5181 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5182 DAG.getUNDEF(InterSubVT), SubVec, 5183 DAG.getConstant(0, DL, XLenVT)); 5184 5185 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5186 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5187 5188 // If required, insert this subvector back into the correct vector register. 5189 // This should resolve to an INSERT_SUBREG instruction. 5190 if (VecVT.bitsGT(InterSubVT)) 5191 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5192 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5193 5194 // We might have bitcast from a mask type: cast back to the original type if 5195 // required. 5196 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5197 } 5198 5199 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5200 SelectionDAG &DAG) const { 5201 SDValue Vec = Op.getOperand(0); 5202 MVT SubVecVT = Op.getSimpleValueType(); 5203 MVT VecVT = Vec.getSimpleValueType(); 5204 5205 SDLoc DL(Op); 5206 MVT XLenVT = Subtarget.getXLenVT(); 5207 unsigned OrigIdx = Op.getConstantOperandVal(1); 5208 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5209 5210 // We don't have the ability to slide mask vectors down indexed by their i1 5211 // elements; the smallest we can do is i8. Often we are able to bitcast to 5212 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5213 // from a scalable one, we might not necessarily have enough scalable 5214 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5215 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5216 if (VecVT.getVectorMinNumElements() >= 8 && 5217 SubVecVT.getVectorMinNumElements() >= 8) { 5218 assert(OrigIdx % 8 == 0 && "Invalid index"); 5219 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5220 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5221 "Unexpected mask vector lowering"); 5222 OrigIdx /= 8; 5223 SubVecVT = 5224 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5225 SubVecVT.isScalableVector()); 5226 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5227 VecVT.isScalableVector()); 5228 Vec = DAG.getBitcast(VecVT, Vec); 5229 } else { 5230 // We can't slide this mask vector down, indexed by its i1 elements. 5231 // This poses a problem when we wish to extract a scalable vector which 5232 // can't be re-expressed as a larger type. Just choose the slow path and 5233 // extend to a larger type, then truncate back down. 5234 // TODO: We could probably improve this when extracting certain fixed 5235 // from fixed, where we can extract as i8 and shift the correct element 5236 // right to reach the desired subvector? 5237 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5238 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5239 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5240 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5241 Op.getOperand(1)); 5242 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5243 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5244 } 5245 } 5246 5247 // If the subvector vector is a fixed-length type, we cannot use subregister 5248 // manipulation to simplify the codegen; we don't know which register of a 5249 // LMUL group contains the specific subvector as we only know the minimum 5250 // register size. Therefore we must slide the vector group down the full 5251 // amount. 5252 if (SubVecVT.isFixedLengthVector()) { 5253 // With an index of 0 this is a cast-like subvector, which can be performed 5254 // with subregister operations. 5255 if (OrigIdx == 0) 5256 return Op; 5257 MVT ContainerVT = VecVT; 5258 if (VecVT.isFixedLengthVector()) { 5259 ContainerVT = getContainerForFixedLengthVector(VecVT); 5260 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5261 } 5262 SDValue Mask = 5263 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5264 // Set the vector length to only the number of elements we care about. This 5265 // avoids sliding down elements we're going to discard straight away. 5266 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5267 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5268 SDValue Slidedown = 5269 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5270 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5271 // Now we can use a cast-like subvector extract to get the result. 5272 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5273 DAG.getConstant(0, DL, XLenVT)); 5274 return DAG.getBitcast(Op.getValueType(), Slidedown); 5275 } 5276 5277 unsigned SubRegIdx, RemIdx; 5278 std::tie(SubRegIdx, RemIdx) = 5279 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5280 VecVT, SubVecVT, OrigIdx, TRI); 5281 5282 // If the Idx has been completely eliminated then this is a subvector extract 5283 // which naturally aligns to a vector register. These can easily be handled 5284 // using subregister manipulation. 5285 if (RemIdx == 0) 5286 return Op; 5287 5288 // Else we must shift our vector register directly to extract the subvector. 5289 // Do this using VSLIDEDOWN. 5290 5291 // If the vector type is an LMUL-group type, extract a subvector equal to the 5292 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5293 // instruction. 5294 MVT InterSubVT = VecVT; 5295 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5296 InterSubVT = getLMUL1VT(VecVT); 5297 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5298 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5299 } 5300 5301 // Slide this vector register down by the desired number of elements in order 5302 // to place the desired subvector starting at element 0. 5303 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5304 // For scalable vectors this must be further multiplied by vscale. 5305 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5306 5307 SDValue Mask, VL; 5308 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5309 SDValue Slidedown = 5310 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5311 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5312 5313 // Now the vector is in the right position, extract our final subvector. This 5314 // should resolve to a COPY. 5315 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5316 DAG.getConstant(0, DL, XLenVT)); 5317 5318 // We might have bitcast from a mask type: cast back to the original type if 5319 // required. 5320 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5321 } 5322 5323 // Lower step_vector to the vid instruction. Any non-identity step value must 5324 // be accounted for my manual expansion. 5325 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5326 SelectionDAG &DAG) const { 5327 SDLoc DL(Op); 5328 MVT VT = Op.getSimpleValueType(); 5329 MVT XLenVT = Subtarget.getXLenVT(); 5330 SDValue Mask, VL; 5331 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5332 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5333 uint64_t StepValImm = Op.getConstantOperandVal(0); 5334 if (StepValImm != 1) { 5335 if (isPowerOf2_64(StepValImm)) { 5336 SDValue StepVal = 5337 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 5338 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5339 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5340 } else { 5341 SDValue StepVal = lowerScalarSplat( 5342 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 5343 DL, DAG, Subtarget); 5344 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5345 } 5346 } 5347 return StepVec; 5348 } 5349 5350 // Implement vector_reverse using vrgather.vv with indices determined by 5351 // subtracting the id of each element from (VLMAX-1). This will convert 5352 // the indices like so: 5353 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5354 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5355 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5356 SelectionDAG &DAG) const { 5357 SDLoc DL(Op); 5358 MVT VecVT = Op.getSimpleValueType(); 5359 unsigned EltSize = VecVT.getScalarSizeInBits(); 5360 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5361 5362 unsigned MaxVLMAX = 0; 5363 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5364 if (VectorBitsMax != 0) 5365 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5366 5367 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5368 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5369 5370 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5371 // to use vrgatherei16.vv. 5372 // TODO: It's also possible to use vrgatherei16.vv for other types to 5373 // decrease register width for the index calculation. 5374 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5375 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5376 // Reverse each half, then reassemble them in reverse order. 5377 // NOTE: It's also possible that after splitting that VLMAX no longer 5378 // requires vrgatherei16.vv. 5379 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5380 SDValue Lo, Hi; 5381 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5382 EVT LoVT, HiVT; 5383 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5384 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5385 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5386 // Reassemble the low and high pieces reversed. 5387 // FIXME: This is a CONCAT_VECTORS. 5388 SDValue Res = 5389 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5390 DAG.getIntPtrConstant(0, DL)); 5391 return DAG.getNode( 5392 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5393 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5394 } 5395 5396 // Just promote the int type to i16 which will double the LMUL. 5397 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5398 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5399 } 5400 5401 MVT XLenVT = Subtarget.getXLenVT(); 5402 SDValue Mask, VL; 5403 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5404 5405 // Calculate VLMAX-1 for the desired SEW. 5406 unsigned MinElts = VecVT.getVectorMinNumElements(); 5407 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5408 DAG.getConstant(MinElts, DL, XLenVT)); 5409 SDValue VLMinus1 = 5410 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5411 5412 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5413 bool IsRV32E64 = 5414 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5415 SDValue SplatVL; 5416 if (!IsRV32E64) 5417 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5418 else 5419 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 5420 5421 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5422 SDValue Indices = 5423 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5424 5425 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5426 } 5427 5428 SDValue 5429 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5430 SelectionDAG &DAG) const { 5431 SDLoc DL(Op); 5432 auto *Load = cast<LoadSDNode>(Op); 5433 5434 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5435 Load->getMemoryVT(), 5436 *Load->getMemOperand()) && 5437 "Expecting a correctly-aligned load"); 5438 5439 MVT VT = Op.getSimpleValueType(); 5440 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5441 5442 SDValue VL = 5443 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5444 5445 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5446 SDValue NewLoad = DAG.getMemIntrinsicNode( 5447 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5448 Load->getMemoryVT(), Load->getMemOperand()); 5449 5450 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5451 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5452 } 5453 5454 SDValue 5455 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5456 SelectionDAG &DAG) const { 5457 SDLoc DL(Op); 5458 auto *Store = cast<StoreSDNode>(Op); 5459 5460 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5461 Store->getMemoryVT(), 5462 *Store->getMemOperand()) && 5463 "Expecting a correctly-aligned store"); 5464 5465 SDValue StoreVal = Store->getValue(); 5466 MVT VT = StoreVal.getSimpleValueType(); 5467 5468 // If the size less than a byte, we need to pad with zeros to make a byte. 5469 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5470 VT = MVT::v8i1; 5471 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5472 DAG.getConstant(0, DL, VT), StoreVal, 5473 DAG.getIntPtrConstant(0, DL)); 5474 } 5475 5476 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5477 5478 SDValue VL = 5479 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5480 5481 SDValue NewValue = 5482 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5483 return DAG.getMemIntrinsicNode( 5484 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5485 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5486 Store->getMemoryVT(), Store->getMemOperand()); 5487 } 5488 5489 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5490 SelectionDAG &DAG) const { 5491 SDLoc DL(Op); 5492 MVT VT = Op.getSimpleValueType(); 5493 5494 const auto *MemSD = cast<MemSDNode>(Op); 5495 EVT MemVT = MemSD->getMemoryVT(); 5496 MachineMemOperand *MMO = MemSD->getMemOperand(); 5497 SDValue Chain = MemSD->getChain(); 5498 SDValue BasePtr = MemSD->getBasePtr(); 5499 5500 SDValue Mask, PassThru, VL; 5501 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5502 Mask = VPLoad->getMask(); 5503 PassThru = DAG.getUNDEF(VT); 5504 VL = VPLoad->getVectorLength(); 5505 } else { 5506 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5507 Mask = MLoad->getMask(); 5508 PassThru = MLoad->getPassThru(); 5509 } 5510 5511 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5512 5513 MVT XLenVT = Subtarget.getXLenVT(); 5514 5515 MVT ContainerVT = VT; 5516 if (VT.isFixedLengthVector()) { 5517 ContainerVT = getContainerForFixedLengthVector(VT); 5518 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5519 if (!IsUnmasked) { 5520 MVT MaskVT = 5521 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5522 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5523 } 5524 } 5525 5526 if (!VL) 5527 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5528 5529 unsigned IntID = 5530 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5531 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5532 if (IsUnmasked) 5533 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5534 else 5535 Ops.push_back(PassThru); 5536 Ops.push_back(BasePtr); 5537 if (!IsUnmasked) 5538 Ops.push_back(Mask); 5539 Ops.push_back(VL); 5540 if (!IsUnmasked) 5541 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5542 5543 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5544 5545 SDValue Result = 5546 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5547 Chain = Result.getValue(1); 5548 5549 if (VT.isFixedLengthVector()) 5550 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5551 5552 return DAG.getMergeValues({Result, Chain}, DL); 5553 } 5554 5555 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5556 SelectionDAG &DAG) const { 5557 SDLoc DL(Op); 5558 5559 const auto *MemSD = cast<MemSDNode>(Op); 5560 EVT MemVT = MemSD->getMemoryVT(); 5561 MachineMemOperand *MMO = MemSD->getMemOperand(); 5562 SDValue Chain = MemSD->getChain(); 5563 SDValue BasePtr = MemSD->getBasePtr(); 5564 SDValue Val, Mask, VL; 5565 5566 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5567 Val = VPStore->getValue(); 5568 Mask = VPStore->getMask(); 5569 VL = VPStore->getVectorLength(); 5570 } else { 5571 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5572 Val = MStore->getValue(); 5573 Mask = MStore->getMask(); 5574 } 5575 5576 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5577 5578 MVT VT = Val.getSimpleValueType(); 5579 MVT XLenVT = Subtarget.getXLenVT(); 5580 5581 MVT ContainerVT = VT; 5582 if (VT.isFixedLengthVector()) { 5583 ContainerVT = getContainerForFixedLengthVector(VT); 5584 5585 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5586 if (!IsUnmasked) { 5587 MVT MaskVT = 5588 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5589 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5590 } 5591 } 5592 5593 if (!VL) 5594 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5595 5596 unsigned IntID = 5597 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5598 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5599 Ops.push_back(Val); 5600 Ops.push_back(BasePtr); 5601 if (!IsUnmasked) 5602 Ops.push_back(Mask); 5603 Ops.push_back(VL); 5604 5605 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5606 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5607 } 5608 5609 SDValue 5610 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5611 SelectionDAG &DAG) const { 5612 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5613 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5614 5615 MVT VT = Op.getSimpleValueType(); 5616 5617 SDValue Op1 = 5618 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5619 SDValue Op2 = 5620 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5621 5622 SDLoc DL(Op); 5623 SDValue VL = 5624 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5625 5626 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5627 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5628 5629 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5630 Op.getOperand(2), Mask, VL); 5631 5632 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5633 } 5634 5635 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5636 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5637 MVT VT = Op.getSimpleValueType(); 5638 5639 if (VT.getVectorElementType() == MVT::i1) 5640 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5641 5642 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5643 } 5644 5645 SDValue 5646 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5647 SelectionDAG &DAG) const { 5648 unsigned Opc; 5649 switch (Op.getOpcode()) { 5650 default: llvm_unreachable("Unexpected opcode!"); 5651 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5652 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5653 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5654 } 5655 5656 return lowerToScalableOp(Op, DAG, Opc); 5657 } 5658 5659 // Lower vector ABS to smax(X, sub(0, X)). 5660 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5661 SDLoc DL(Op); 5662 MVT VT = Op.getSimpleValueType(); 5663 SDValue X = Op.getOperand(0); 5664 5665 assert(VT.isFixedLengthVector() && "Unexpected type"); 5666 5667 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5668 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5669 5670 SDValue Mask, VL; 5671 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5672 5673 SDValue SplatZero = 5674 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5675 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5676 SDValue NegX = 5677 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5678 SDValue Max = 5679 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5680 5681 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5682 } 5683 5684 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5685 SDValue Op, SelectionDAG &DAG) const { 5686 SDLoc DL(Op); 5687 MVT VT = Op.getSimpleValueType(); 5688 SDValue Mag = Op.getOperand(0); 5689 SDValue Sign = Op.getOperand(1); 5690 assert(Mag.getValueType() == Sign.getValueType() && 5691 "Can only handle COPYSIGN with matching types."); 5692 5693 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5694 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5695 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5696 5697 SDValue Mask, VL; 5698 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5699 5700 SDValue CopySign = 5701 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5702 5703 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5704 } 5705 5706 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5707 SDValue Op, SelectionDAG &DAG) const { 5708 MVT VT = Op.getSimpleValueType(); 5709 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5710 5711 MVT I1ContainerVT = 5712 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5713 5714 SDValue CC = 5715 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5716 SDValue Op1 = 5717 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5718 SDValue Op2 = 5719 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5720 5721 SDLoc DL(Op); 5722 SDValue Mask, VL; 5723 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5724 5725 SDValue Select = 5726 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5727 5728 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5729 } 5730 5731 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5732 unsigned NewOpc, 5733 bool HasMask) const { 5734 MVT VT = Op.getSimpleValueType(); 5735 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5736 5737 // Create list of operands by converting existing ones to scalable types. 5738 SmallVector<SDValue, 6> Ops; 5739 for (const SDValue &V : Op->op_values()) { 5740 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5741 5742 // Pass through non-vector operands. 5743 if (!V.getValueType().isVector()) { 5744 Ops.push_back(V); 5745 continue; 5746 } 5747 5748 // "cast" fixed length vector to a scalable vector. 5749 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5750 "Only fixed length vectors are supported!"); 5751 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5752 } 5753 5754 SDLoc DL(Op); 5755 SDValue Mask, VL; 5756 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5757 if (HasMask) 5758 Ops.push_back(Mask); 5759 Ops.push_back(VL); 5760 5761 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5762 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5763 } 5764 5765 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5766 // * Operands of each node are assumed to be in the same order. 5767 // * The EVL operand is promoted from i32 to i64 on RV64. 5768 // * Fixed-length vectors are converted to their scalable-vector container 5769 // types. 5770 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5771 unsigned RISCVISDOpc) const { 5772 SDLoc DL(Op); 5773 MVT VT = Op.getSimpleValueType(); 5774 SmallVector<SDValue, 4> Ops; 5775 5776 for (const auto &OpIdx : enumerate(Op->ops())) { 5777 SDValue V = OpIdx.value(); 5778 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5779 // Pass through operands which aren't fixed-length vectors. 5780 if (!V.getValueType().isFixedLengthVector()) { 5781 Ops.push_back(V); 5782 continue; 5783 } 5784 // "cast" fixed length vector to a scalable vector. 5785 MVT OpVT = V.getSimpleValueType(); 5786 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5787 assert(useRVVForFixedLengthVectorVT(OpVT) && 5788 "Only fixed length vectors are supported!"); 5789 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5790 } 5791 5792 if (!VT.isFixedLengthVector()) 5793 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5794 5795 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5796 5797 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5798 5799 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5800 } 5801 5802 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 5803 unsigned MaskOpc, 5804 unsigned VecOpc) const { 5805 MVT VT = Op.getSimpleValueType(); 5806 if (VT.getVectorElementType() != MVT::i1) 5807 return lowerVPOp(Op, DAG, VecOpc); 5808 5809 // It is safe to drop mask parameter as masked-off elements are undef. 5810 SDValue Op1 = Op->getOperand(0); 5811 SDValue Op2 = Op->getOperand(1); 5812 SDValue VL = Op->getOperand(3); 5813 5814 MVT ContainerVT = VT; 5815 const bool IsFixed = VT.isFixedLengthVector(); 5816 if (IsFixed) { 5817 ContainerVT = getContainerForFixedLengthVector(VT); 5818 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 5819 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 5820 } 5821 5822 SDLoc DL(Op); 5823 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 5824 if (!IsFixed) 5825 return Val; 5826 return convertFromScalableVector(VT, Val, DAG, Subtarget); 5827 } 5828 5829 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5830 // matched to a RVV indexed load. The RVV indexed load instructions only 5831 // support the "unsigned unscaled" addressing mode; indices are implicitly 5832 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5833 // signed or scaled indexing is extended to the XLEN value type and scaled 5834 // accordingly. 5835 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5836 SelectionDAG &DAG) const { 5837 SDLoc DL(Op); 5838 MVT VT = Op.getSimpleValueType(); 5839 5840 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5841 EVT MemVT = MemSD->getMemoryVT(); 5842 MachineMemOperand *MMO = MemSD->getMemOperand(); 5843 SDValue Chain = MemSD->getChain(); 5844 SDValue BasePtr = MemSD->getBasePtr(); 5845 5846 ISD::LoadExtType LoadExtType; 5847 SDValue Index, Mask, PassThru, VL; 5848 5849 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5850 Index = VPGN->getIndex(); 5851 Mask = VPGN->getMask(); 5852 PassThru = DAG.getUNDEF(VT); 5853 VL = VPGN->getVectorLength(); 5854 // VP doesn't support extending loads. 5855 LoadExtType = ISD::NON_EXTLOAD; 5856 } else { 5857 // Else it must be a MGATHER. 5858 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5859 Index = MGN->getIndex(); 5860 Mask = MGN->getMask(); 5861 PassThru = MGN->getPassThru(); 5862 LoadExtType = MGN->getExtensionType(); 5863 } 5864 5865 MVT IndexVT = Index.getSimpleValueType(); 5866 MVT XLenVT = Subtarget.getXLenVT(); 5867 5868 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5869 "Unexpected VTs!"); 5870 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5871 // Targets have to explicitly opt-in for extending vector loads. 5872 assert(LoadExtType == ISD::NON_EXTLOAD && 5873 "Unexpected extending MGATHER/VP_GATHER"); 5874 (void)LoadExtType; 5875 5876 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5877 // the selection of the masked intrinsics doesn't do this for us. 5878 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5879 5880 MVT ContainerVT = VT; 5881 if (VT.isFixedLengthVector()) { 5882 // We need to use the larger of the result and index type to determine the 5883 // scalable type to use so we don't increase LMUL for any operand/result. 5884 if (VT.bitsGE(IndexVT)) { 5885 ContainerVT = getContainerForFixedLengthVector(VT); 5886 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5887 ContainerVT.getVectorElementCount()); 5888 } else { 5889 IndexVT = getContainerForFixedLengthVector(IndexVT); 5890 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5891 IndexVT.getVectorElementCount()); 5892 } 5893 5894 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5895 5896 if (!IsUnmasked) { 5897 MVT MaskVT = 5898 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5899 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5900 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5901 } 5902 } 5903 5904 if (!VL) 5905 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5906 5907 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5908 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5909 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 5910 VL); 5911 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 5912 TrueMask, VL); 5913 } 5914 5915 unsigned IntID = 5916 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5917 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5918 if (IsUnmasked) 5919 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5920 else 5921 Ops.push_back(PassThru); 5922 Ops.push_back(BasePtr); 5923 Ops.push_back(Index); 5924 if (!IsUnmasked) 5925 Ops.push_back(Mask); 5926 Ops.push_back(VL); 5927 if (!IsUnmasked) 5928 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5929 5930 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5931 SDValue Result = 5932 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5933 Chain = Result.getValue(1); 5934 5935 if (VT.isFixedLengthVector()) 5936 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5937 5938 return DAG.getMergeValues({Result, Chain}, DL); 5939 } 5940 5941 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5942 // matched to a RVV indexed store. The RVV indexed store instructions only 5943 // support the "unsigned unscaled" addressing mode; indices are implicitly 5944 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5945 // signed or scaled indexing is extended to the XLEN value type and scaled 5946 // accordingly. 5947 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5948 SelectionDAG &DAG) const { 5949 SDLoc DL(Op); 5950 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5951 EVT MemVT = MemSD->getMemoryVT(); 5952 MachineMemOperand *MMO = MemSD->getMemOperand(); 5953 SDValue Chain = MemSD->getChain(); 5954 SDValue BasePtr = MemSD->getBasePtr(); 5955 5956 bool IsTruncatingStore = false; 5957 SDValue Index, Mask, Val, VL; 5958 5959 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5960 Index = VPSN->getIndex(); 5961 Mask = VPSN->getMask(); 5962 Val = VPSN->getValue(); 5963 VL = VPSN->getVectorLength(); 5964 // VP doesn't support truncating stores. 5965 IsTruncatingStore = false; 5966 } else { 5967 // Else it must be a MSCATTER. 5968 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5969 Index = MSN->getIndex(); 5970 Mask = MSN->getMask(); 5971 Val = MSN->getValue(); 5972 IsTruncatingStore = MSN->isTruncatingStore(); 5973 } 5974 5975 MVT VT = Val.getSimpleValueType(); 5976 MVT IndexVT = Index.getSimpleValueType(); 5977 MVT XLenVT = Subtarget.getXLenVT(); 5978 5979 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5980 "Unexpected VTs!"); 5981 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5982 // Targets have to explicitly opt-in for extending vector loads and 5983 // truncating vector stores. 5984 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5985 (void)IsTruncatingStore; 5986 5987 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5988 // the selection of the masked intrinsics doesn't do this for us. 5989 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5990 5991 MVT ContainerVT = VT; 5992 if (VT.isFixedLengthVector()) { 5993 // We need to use the larger of the value and index type to determine the 5994 // scalable type to use so we don't increase LMUL for any operand/result. 5995 if (VT.bitsGE(IndexVT)) { 5996 ContainerVT = getContainerForFixedLengthVector(VT); 5997 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5998 ContainerVT.getVectorElementCount()); 5999 } else { 6000 IndexVT = getContainerForFixedLengthVector(IndexVT); 6001 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6002 IndexVT.getVectorElementCount()); 6003 } 6004 6005 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6006 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6007 6008 if (!IsUnmasked) { 6009 MVT MaskVT = 6010 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6011 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6012 } 6013 } 6014 6015 if (!VL) 6016 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6017 6018 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6019 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6020 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6021 VL); 6022 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6023 TrueMask, VL); 6024 } 6025 6026 unsigned IntID = 6027 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6028 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6029 Ops.push_back(Val); 6030 Ops.push_back(BasePtr); 6031 Ops.push_back(Index); 6032 if (!IsUnmasked) 6033 Ops.push_back(Mask); 6034 Ops.push_back(VL); 6035 6036 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6037 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6038 } 6039 6040 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6041 SelectionDAG &DAG) const { 6042 const MVT XLenVT = Subtarget.getXLenVT(); 6043 SDLoc DL(Op); 6044 SDValue Chain = Op->getOperand(0); 6045 SDValue SysRegNo = DAG.getTargetConstant( 6046 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6047 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6048 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6049 6050 // Encoding used for rounding mode in RISCV differs from that used in 6051 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6052 // table, which consists of a sequence of 4-bit fields, each representing 6053 // corresponding FLT_ROUNDS mode. 6054 static const int Table = 6055 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6056 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6057 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6058 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6059 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6060 6061 SDValue Shift = 6062 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6063 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6064 DAG.getConstant(Table, DL, XLenVT), Shift); 6065 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6066 DAG.getConstant(7, DL, XLenVT)); 6067 6068 return DAG.getMergeValues({Masked, Chain}, DL); 6069 } 6070 6071 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6072 SelectionDAG &DAG) const { 6073 const MVT XLenVT = Subtarget.getXLenVT(); 6074 SDLoc DL(Op); 6075 SDValue Chain = Op->getOperand(0); 6076 SDValue RMValue = Op->getOperand(1); 6077 SDValue SysRegNo = DAG.getTargetConstant( 6078 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6079 6080 // Encoding used for rounding mode in RISCV differs from that used in 6081 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6082 // a table, which consists of a sequence of 4-bit fields, each representing 6083 // corresponding RISCV mode. 6084 static const unsigned Table = 6085 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6086 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6087 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6088 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6089 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6090 6091 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6092 DAG.getConstant(2, DL, XLenVT)); 6093 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6094 DAG.getConstant(Table, DL, XLenVT), Shift); 6095 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6096 DAG.getConstant(0x7, DL, XLenVT)); 6097 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6098 RMValue); 6099 } 6100 6101 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6102 switch (IntNo) { 6103 default: 6104 llvm_unreachable("Unexpected Intrinsic"); 6105 case Intrinsic::riscv_grev: 6106 return RISCVISD::GREVW; 6107 case Intrinsic::riscv_gorc: 6108 return RISCVISD::GORCW; 6109 case Intrinsic::riscv_bcompress: 6110 return RISCVISD::BCOMPRESSW; 6111 case Intrinsic::riscv_bdecompress: 6112 return RISCVISD::BDECOMPRESSW; 6113 case Intrinsic::riscv_bfp: 6114 return RISCVISD::BFPW; 6115 case Intrinsic::riscv_fsl: 6116 return RISCVISD::FSLW; 6117 case Intrinsic::riscv_fsr: 6118 return RISCVISD::FSRW; 6119 } 6120 } 6121 6122 // Converts the given intrinsic to a i64 operation with any extension. 6123 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6124 unsigned IntNo) { 6125 SDLoc DL(N); 6126 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6127 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6128 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6129 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6130 // ReplaceNodeResults requires we maintain the same type for the return value. 6131 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6132 } 6133 6134 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6135 // form of the given Opcode. 6136 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6137 switch (Opcode) { 6138 default: 6139 llvm_unreachable("Unexpected opcode"); 6140 case ISD::SHL: 6141 return RISCVISD::SLLW; 6142 case ISD::SRA: 6143 return RISCVISD::SRAW; 6144 case ISD::SRL: 6145 return RISCVISD::SRLW; 6146 case ISD::SDIV: 6147 return RISCVISD::DIVW; 6148 case ISD::UDIV: 6149 return RISCVISD::DIVUW; 6150 case ISD::UREM: 6151 return RISCVISD::REMUW; 6152 case ISD::ROTL: 6153 return RISCVISD::ROLW; 6154 case ISD::ROTR: 6155 return RISCVISD::RORW; 6156 case RISCVISD::GREV: 6157 return RISCVISD::GREVW; 6158 case RISCVISD::GORC: 6159 return RISCVISD::GORCW; 6160 } 6161 } 6162 6163 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6164 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6165 // otherwise be promoted to i64, making it difficult to select the 6166 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6167 // type i8/i16/i32 is lost. 6168 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6169 unsigned ExtOpc = ISD::ANY_EXTEND) { 6170 SDLoc DL(N); 6171 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6172 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6173 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6174 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6175 // ReplaceNodeResults requires we maintain the same type for the return value. 6176 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6177 } 6178 6179 // Converts the given 32-bit operation to a i64 operation with signed extension 6180 // semantic to reduce the signed extension instructions. 6181 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6182 SDLoc DL(N); 6183 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6184 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6185 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6186 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6187 DAG.getValueType(MVT::i32)); 6188 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6189 } 6190 6191 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6192 SmallVectorImpl<SDValue> &Results, 6193 SelectionDAG &DAG) const { 6194 SDLoc DL(N); 6195 switch (N->getOpcode()) { 6196 default: 6197 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6198 case ISD::STRICT_FP_TO_SINT: 6199 case ISD::STRICT_FP_TO_UINT: 6200 case ISD::FP_TO_SINT: 6201 case ISD::FP_TO_UINT: { 6202 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6203 "Unexpected custom legalisation"); 6204 bool IsStrict = N->isStrictFPOpcode(); 6205 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6206 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6207 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6208 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6209 TargetLowering::TypeSoftenFloat) { 6210 if (!isTypeLegal(Op0.getValueType())) 6211 return; 6212 if (IsStrict) { 6213 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6214 : RISCVISD::STRICT_FCVT_WU_RV64; 6215 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6216 SDValue Res = DAG.getNode( 6217 Opc, DL, VTs, N->getOperand(0), Op0, 6218 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6219 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6220 Results.push_back(Res.getValue(1)); 6221 return; 6222 } 6223 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6224 SDValue Res = 6225 DAG.getNode(Opc, DL, MVT::i64, Op0, 6226 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6227 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6228 return; 6229 } 6230 // If the FP type needs to be softened, emit a library call using the 'si' 6231 // version. If we left it to default legalization we'd end up with 'di'. If 6232 // the FP type doesn't need to be softened just let generic type 6233 // legalization promote the result type. 6234 RTLIB::Libcall LC; 6235 if (IsSigned) 6236 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6237 else 6238 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6239 MakeLibCallOptions CallOptions; 6240 EVT OpVT = Op0.getValueType(); 6241 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6242 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6243 SDValue Result; 6244 std::tie(Result, Chain) = 6245 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6246 Results.push_back(Result); 6247 if (IsStrict) 6248 Results.push_back(Chain); 6249 break; 6250 } 6251 case ISD::READCYCLECOUNTER: { 6252 assert(!Subtarget.is64Bit() && 6253 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6254 6255 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6256 SDValue RCW = 6257 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6258 6259 Results.push_back( 6260 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6261 Results.push_back(RCW.getValue(2)); 6262 break; 6263 } 6264 case ISD::MUL: { 6265 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6266 unsigned XLen = Subtarget.getXLen(); 6267 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6268 if (Size > XLen) { 6269 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6270 SDValue LHS = N->getOperand(0); 6271 SDValue RHS = N->getOperand(1); 6272 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6273 6274 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6275 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6276 // We need exactly one side to be unsigned. 6277 if (LHSIsU == RHSIsU) 6278 return; 6279 6280 auto MakeMULPair = [&](SDValue S, SDValue U) { 6281 MVT XLenVT = Subtarget.getXLenVT(); 6282 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6283 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6284 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6285 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6286 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6287 }; 6288 6289 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6290 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6291 6292 // The other operand should be signed, but still prefer MULH when 6293 // possible. 6294 if (RHSIsU && LHSIsS && !RHSIsS) 6295 Results.push_back(MakeMULPair(LHS, RHS)); 6296 else if (LHSIsU && RHSIsS && !LHSIsS) 6297 Results.push_back(MakeMULPair(RHS, LHS)); 6298 6299 return; 6300 } 6301 LLVM_FALLTHROUGH; 6302 } 6303 case ISD::ADD: 6304 case ISD::SUB: 6305 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6306 "Unexpected custom legalisation"); 6307 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6308 break; 6309 case ISD::SHL: 6310 case ISD::SRA: 6311 case ISD::SRL: 6312 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6313 "Unexpected custom legalisation"); 6314 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6315 Results.push_back(customLegalizeToWOp(N, DAG)); 6316 break; 6317 } 6318 6319 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6320 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6321 // shift amount. 6322 if (N->getOpcode() == ISD::SHL) { 6323 SDLoc DL(N); 6324 SDValue NewOp0 = 6325 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6326 SDValue NewOp1 = 6327 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6328 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6329 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6330 DAG.getValueType(MVT::i32)); 6331 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6332 } 6333 6334 break; 6335 case ISD::ROTL: 6336 case ISD::ROTR: 6337 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6338 "Unexpected custom legalisation"); 6339 Results.push_back(customLegalizeToWOp(N, DAG)); 6340 break; 6341 case ISD::CTTZ: 6342 case ISD::CTTZ_ZERO_UNDEF: 6343 case ISD::CTLZ: 6344 case ISD::CTLZ_ZERO_UNDEF: { 6345 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6346 "Unexpected custom legalisation"); 6347 6348 SDValue NewOp0 = 6349 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6350 bool IsCTZ = 6351 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6352 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6353 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6354 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6355 return; 6356 } 6357 case ISD::SDIV: 6358 case ISD::UDIV: 6359 case ISD::UREM: { 6360 MVT VT = N->getSimpleValueType(0); 6361 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6362 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6363 "Unexpected custom legalisation"); 6364 // Don't promote division/remainder by constant since we should expand those 6365 // to multiply by magic constant. 6366 // FIXME: What if the expansion is disabled for minsize. 6367 if (N->getOperand(1).getOpcode() == ISD::Constant) 6368 return; 6369 6370 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6371 // the upper 32 bits. For other types we need to sign or zero extend 6372 // based on the opcode. 6373 unsigned ExtOpc = ISD::ANY_EXTEND; 6374 if (VT != MVT::i32) 6375 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6376 : ISD::ZERO_EXTEND; 6377 6378 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6379 break; 6380 } 6381 case ISD::UADDO: 6382 case ISD::USUBO: { 6383 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6384 "Unexpected custom legalisation"); 6385 bool IsAdd = N->getOpcode() == ISD::UADDO; 6386 // Create an ADDW or SUBW. 6387 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6388 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6389 SDValue Res = 6390 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6391 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6392 DAG.getValueType(MVT::i32)); 6393 6394 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6395 // Since the inputs are sign extended from i32, this is equivalent to 6396 // comparing the lower 32 bits. 6397 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6398 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6399 IsAdd ? ISD::SETULT : ISD::SETUGT); 6400 6401 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6402 Results.push_back(Overflow); 6403 return; 6404 } 6405 case ISD::UADDSAT: 6406 case ISD::USUBSAT: { 6407 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6408 "Unexpected custom legalisation"); 6409 if (Subtarget.hasStdExtZbb()) { 6410 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6411 // sign extend allows overflow of the lower 32 bits to be detected on 6412 // the promoted size. 6413 SDValue LHS = 6414 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6415 SDValue RHS = 6416 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6417 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6418 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6419 return; 6420 } 6421 6422 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6423 // promotion for UADDO/USUBO. 6424 Results.push_back(expandAddSubSat(N, DAG)); 6425 return; 6426 } 6427 case ISD::BITCAST: { 6428 EVT VT = N->getValueType(0); 6429 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6430 SDValue Op0 = N->getOperand(0); 6431 EVT Op0VT = Op0.getValueType(); 6432 MVT XLenVT = Subtarget.getXLenVT(); 6433 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6434 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6435 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6436 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6437 Subtarget.hasStdExtF()) { 6438 SDValue FPConv = 6439 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6440 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6441 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6442 isTypeLegal(Op0VT)) { 6443 // Custom-legalize bitcasts from fixed-length vector types to illegal 6444 // scalar types in order to improve codegen. Bitcast the vector to a 6445 // one-element vector type whose element type is the same as the result 6446 // type, and extract the first element. 6447 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6448 if (isTypeLegal(BVT)) { 6449 SDValue BVec = DAG.getBitcast(BVT, Op0); 6450 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6451 DAG.getConstant(0, DL, XLenVT))); 6452 } 6453 } 6454 break; 6455 } 6456 case RISCVISD::GREV: 6457 case RISCVISD::GORC: { 6458 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6459 "Unexpected custom legalisation"); 6460 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6461 // This is similar to customLegalizeToWOp, except that we pass the second 6462 // operand (a TargetConstant) straight through: it is already of type 6463 // XLenVT. 6464 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6465 SDValue NewOp0 = 6466 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6467 SDValue NewOp1 = 6468 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6469 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6470 // ReplaceNodeResults requires we maintain the same type for the return 6471 // value. 6472 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6473 break; 6474 } 6475 case RISCVISD::SHFL: { 6476 // There is no SHFLIW instruction, but we can just promote the operation. 6477 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6478 "Unexpected custom legalisation"); 6479 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6480 SDValue NewOp0 = 6481 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6482 SDValue NewOp1 = 6483 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6484 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6485 // ReplaceNodeResults requires we maintain the same type for the return 6486 // value. 6487 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6488 break; 6489 } 6490 case ISD::BSWAP: 6491 case ISD::BITREVERSE: { 6492 MVT VT = N->getSimpleValueType(0); 6493 MVT XLenVT = Subtarget.getXLenVT(); 6494 assert((VT == MVT::i8 || VT == MVT::i16 || 6495 (VT == MVT::i32 && Subtarget.is64Bit())) && 6496 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6497 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6498 unsigned Imm = VT.getSizeInBits() - 1; 6499 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6500 if (N->getOpcode() == ISD::BSWAP) 6501 Imm &= ~0x7U; 6502 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6503 SDValue GREVI = 6504 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6505 // ReplaceNodeResults requires we maintain the same type for the return 6506 // value. 6507 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6508 break; 6509 } 6510 case ISD::FSHL: 6511 case ISD::FSHR: { 6512 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6513 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6514 SDValue NewOp0 = 6515 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6516 SDValue NewOp1 = 6517 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6518 SDValue NewShAmt = 6519 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6520 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6521 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6522 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6523 DAG.getConstant(0x1f, DL, MVT::i64)); 6524 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6525 // instruction use different orders. fshl will return its first operand for 6526 // shift of zero, fshr will return its second operand. fsl and fsr both 6527 // return rs1 so the ISD nodes need to have different operand orders. 6528 // Shift amount is in rs2. 6529 unsigned Opc = RISCVISD::FSLW; 6530 if (N->getOpcode() == ISD::FSHR) { 6531 std::swap(NewOp0, NewOp1); 6532 Opc = RISCVISD::FSRW; 6533 } 6534 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6535 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6536 break; 6537 } 6538 case ISD::EXTRACT_VECTOR_ELT: { 6539 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6540 // type is illegal (currently only vXi64 RV32). 6541 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6542 // transferred to the destination register. We issue two of these from the 6543 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6544 // first element. 6545 SDValue Vec = N->getOperand(0); 6546 SDValue Idx = N->getOperand(1); 6547 6548 // The vector type hasn't been legalized yet so we can't issue target 6549 // specific nodes if it needs legalization. 6550 // FIXME: We would manually legalize if it's important. 6551 if (!isTypeLegal(Vec.getValueType())) 6552 return; 6553 6554 MVT VecVT = Vec.getSimpleValueType(); 6555 6556 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6557 VecVT.getVectorElementType() == MVT::i64 && 6558 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6559 6560 // If this is a fixed vector, we need to convert it to a scalable vector. 6561 MVT ContainerVT = VecVT; 6562 if (VecVT.isFixedLengthVector()) { 6563 ContainerVT = getContainerForFixedLengthVector(VecVT); 6564 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6565 } 6566 6567 MVT XLenVT = Subtarget.getXLenVT(); 6568 6569 // Use a VL of 1 to avoid processing more elements than we need. 6570 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6571 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6572 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6573 6574 // Unless the index is known to be 0, we must slide the vector down to get 6575 // the desired element into index 0. 6576 if (!isNullConstant(Idx)) { 6577 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6578 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6579 } 6580 6581 // Extract the lower XLEN bits of the correct vector element. 6582 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6583 6584 // To extract the upper XLEN bits of the vector element, shift the first 6585 // element right by 32 bits and re-extract the lower XLEN bits. 6586 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6587 DAG.getConstant(32, DL, XLenVT), VL); 6588 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6589 ThirtyTwoV, Mask, VL); 6590 6591 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6592 6593 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6594 break; 6595 } 6596 case ISD::INTRINSIC_WO_CHAIN: { 6597 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6598 switch (IntNo) { 6599 default: 6600 llvm_unreachable( 6601 "Don't know how to custom type legalize this intrinsic!"); 6602 case Intrinsic::riscv_grev: 6603 case Intrinsic::riscv_gorc: 6604 case Intrinsic::riscv_bcompress: 6605 case Intrinsic::riscv_bdecompress: 6606 case Intrinsic::riscv_bfp: { 6607 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6608 "Unexpected custom legalisation"); 6609 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6610 break; 6611 } 6612 case Intrinsic::riscv_fsl: 6613 case Intrinsic::riscv_fsr: { 6614 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6615 "Unexpected custom legalisation"); 6616 SDValue NewOp1 = 6617 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6618 SDValue NewOp2 = 6619 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6620 SDValue NewOp3 = 6621 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6622 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6623 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6624 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6625 break; 6626 } 6627 case Intrinsic::riscv_orc_b: { 6628 // Lower to the GORCI encoding for orc.b with the operand extended. 6629 SDValue NewOp = 6630 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6631 // If Zbp is enabled, use GORCIW which will sign extend the result. 6632 unsigned Opc = 6633 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6634 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6635 DAG.getConstant(7, DL, MVT::i64)); 6636 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6637 return; 6638 } 6639 case Intrinsic::riscv_shfl: 6640 case Intrinsic::riscv_unshfl: { 6641 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6642 "Unexpected custom legalisation"); 6643 SDValue NewOp1 = 6644 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6645 SDValue NewOp2 = 6646 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6647 unsigned Opc = 6648 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6649 // There is no (UN)SHFLIW. If the control word is a constant, we can use 6650 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 6651 // will be shuffled the same way as the lower 32 bit half, but the two 6652 // halves won't cross. 6653 if (isa<ConstantSDNode>(NewOp2)) { 6654 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6655 DAG.getConstant(0xf, DL, MVT::i64)); 6656 Opc = 6657 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6658 } 6659 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6660 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6661 break; 6662 } 6663 case Intrinsic::riscv_vmv_x_s: { 6664 EVT VT = N->getValueType(0); 6665 MVT XLenVT = Subtarget.getXLenVT(); 6666 if (VT.bitsLT(XLenVT)) { 6667 // Simple case just extract using vmv.x.s and truncate. 6668 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6669 Subtarget.getXLenVT(), N->getOperand(1)); 6670 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6671 return; 6672 } 6673 6674 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6675 "Unexpected custom legalization"); 6676 6677 // We need to do the move in two steps. 6678 SDValue Vec = N->getOperand(1); 6679 MVT VecVT = Vec.getSimpleValueType(); 6680 6681 // First extract the lower XLEN bits of the element. 6682 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6683 6684 // To extract the upper XLEN bits of the vector element, shift the first 6685 // element right by 32 bits and re-extract the lower XLEN bits. 6686 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6687 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6688 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6689 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6690 DAG.getConstant(32, DL, XLenVT), VL); 6691 SDValue LShr32 = 6692 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6693 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6694 6695 Results.push_back( 6696 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6697 break; 6698 } 6699 } 6700 break; 6701 } 6702 case ISD::VECREDUCE_ADD: 6703 case ISD::VECREDUCE_AND: 6704 case ISD::VECREDUCE_OR: 6705 case ISD::VECREDUCE_XOR: 6706 case ISD::VECREDUCE_SMAX: 6707 case ISD::VECREDUCE_UMAX: 6708 case ISD::VECREDUCE_SMIN: 6709 case ISD::VECREDUCE_UMIN: 6710 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6711 Results.push_back(V); 6712 break; 6713 case ISD::VP_REDUCE_ADD: 6714 case ISD::VP_REDUCE_AND: 6715 case ISD::VP_REDUCE_OR: 6716 case ISD::VP_REDUCE_XOR: 6717 case ISD::VP_REDUCE_SMAX: 6718 case ISD::VP_REDUCE_UMAX: 6719 case ISD::VP_REDUCE_SMIN: 6720 case ISD::VP_REDUCE_UMIN: 6721 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6722 Results.push_back(V); 6723 break; 6724 case ISD::FLT_ROUNDS_: { 6725 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6726 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6727 Results.push_back(Res.getValue(0)); 6728 Results.push_back(Res.getValue(1)); 6729 break; 6730 } 6731 } 6732 } 6733 6734 // A structure to hold one of the bit-manipulation patterns below. Together, a 6735 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6736 // (or (and (shl x, 1), 0xAAAAAAAA), 6737 // (and (srl x, 1), 0x55555555)) 6738 struct RISCVBitmanipPat { 6739 SDValue Op; 6740 unsigned ShAmt; 6741 bool IsSHL; 6742 6743 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6744 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6745 } 6746 }; 6747 6748 // Matches patterns of the form 6749 // (and (shl x, C2), (C1 << C2)) 6750 // (and (srl x, C2), C1) 6751 // (shl (and x, C1), C2) 6752 // (srl (and x, (C1 << C2)), C2) 6753 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6754 // The expected masks for each shift amount are specified in BitmanipMasks where 6755 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6756 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6757 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6758 // XLen is 64. 6759 static Optional<RISCVBitmanipPat> 6760 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6761 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6762 "Unexpected number of masks"); 6763 Optional<uint64_t> Mask; 6764 // Optionally consume a mask around the shift operation. 6765 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6766 Mask = Op.getConstantOperandVal(1); 6767 Op = Op.getOperand(0); 6768 } 6769 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6770 return None; 6771 bool IsSHL = Op.getOpcode() == ISD::SHL; 6772 6773 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6774 return None; 6775 uint64_t ShAmt = Op.getConstantOperandVal(1); 6776 6777 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6778 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6779 return None; 6780 // If we don't have enough masks for 64 bit, then we must be trying to 6781 // match SHFL so we're only allowed to shift 1/4 of the width. 6782 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6783 return None; 6784 6785 SDValue Src = Op.getOperand(0); 6786 6787 // The expected mask is shifted left when the AND is found around SHL 6788 // patterns. 6789 // ((x >> 1) & 0x55555555) 6790 // ((x << 1) & 0xAAAAAAAA) 6791 bool SHLExpMask = IsSHL; 6792 6793 if (!Mask) { 6794 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6795 // the mask is all ones: consume that now. 6796 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6797 Mask = Src.getConstantOperandVal(1); 6798 Src = Src.getOperand(0); 6799 // The expected mask is now in fact shifted left for SRL, so reverse the 6800 // decision. 6801 // ((x & 0xAAAAAAAA) >> 1) 6802 // ((x & 0x55555555) << 1) 6803 SHLExpMask = !SHLExpMask; 6804 } else { 6805 // Use a default shifted mask of all-ones if there's no AND, truncated 6806 // down to the expected width. This simplifies the logic later on. 6807 Mask = maskTrailingOnes<uint64_t>(Width); 6808 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6809 } 6810 } 6811 6812 unsigned MaskIdx = Log2_32(ShAmt); 6813 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6814 6815 if (SHLExpMask) 6816 ExpMask <<= ShAmt; 6817 6818 if (Mask != ExpMask) 6819 return None; 6820 6821 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6822 } 6823 6824 // Matches any of the following bit-manipulation patterns: 6825 // (and (shl x, 1), (0x55555555 << 1)) 6826 // (and (srl x, 1), 0x55555555) 6827 // (shl (and x, 0x55555555), 1) 6828 // (srl (and x, (0x55555555 << 1)), 1) 6829 // where the shift amount and mask may vary thus: 6830 // [1] = 0x55555555 / 0xAAAAAAAA 6831 // [2] = 0x33333333 / 0xCCCCCCCC 6832 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6833 // [8] = 0x00FF00FF / 0xFF00FF00 6834 // [16] = 0x0000FFFF / 0xFFFFFFFF 6835 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6836 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6837 // These are the unshifted masks which we use to match bit-manipulation 6838 // patterns. They may be shifted left in certain circumstances. 6839 static const uint64_t BitmanipMasks[] = { 6840 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6841 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6842 6843 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6844 } 6845 6846 // Match the following pattern as a GREVI(W) operation 6847 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6848 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6849 const RISCVSubtarget &Subtarget) { 6850 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6851 EVT VT = Op.getValueType(); 6852 6853 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6854 auto LHS = matchGREVIPat(Op.getOperand(0)); 6855 auto RHS = matchGREVIPat(Op.getOperand(1)); 6856 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6857 SDLoc DL(Op); 6858 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6859 DAG.getConstant(LHS->ShAmt, DL, VT)); 6860 } 6861 } 6862 return SDValue(); 6863 } 6864 6865 // Matches any the following pattern as a GORCI(W) operation 6866 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6867 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6868 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6869 // Note that with the variant of 3., 6870 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6871 // the inner pattern will first be matched as GREVI and then the outer 6872 // pattern will be matched to GORC via the first rule above. 6873 // 4. (or (rotl/rotr x, bitwidth/2), x) 6874 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6875 const RISCVSubtarget &Subtarget) { 6876 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6877 EVT VT = Op.getValueType(); 6878 6879 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6880 SDLoc DL(Op); 6881 SDValue Op0 = Op.getOperand(0); 6882 SDValue Op1 = Op.getOperand(1); 6883 6884 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6885 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6886 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6887 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6888 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6889 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6890 if ((Reverse.getOpcode() == ISD::ROTL || 6891 Reverse.getOpcode() == ISD::ROTR) && 6892 Reverse.getOperand(0) == X && 6893 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6894 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6895 if (RotAmt == (VT.getSizeInBits() / 2)) 6896 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6897 DAG.getConstant(RotAmt, DL, VT)); 6898 } 6899 return SDValue(); 6900 }; 6901 6902 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6903 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6904 return V; 6905 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6906 return V; 6907 6908 // OR is commutable so canonicalize its OR operand to the left 6909 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6910 std::swap(Op0, Op1); 6911 if (Op0.getOpcode() != ISD::OR) 6912 return SDValue(); 6913 SDValue OrOp0 = Op0.getOperand(0); 6914 SDValue OrOp1 = Op0.getOperand(1); 6915 auto LHS = matchGREVIPat(OrOp0); 6916 // OR is commutable so swap the operands and try again: x might have been 6917 // on the left 6918 if (!LHS) { 6919 std::swap(OrOp0, OrOp1); 6920 LHS = matchGREVIPat(OrOp0); 6921 } 6922 auto RHS = matchGREVIPat(Op1); 6923 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6924 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6925 DAG.getConstant(LHS->ShAmt, DL, VT)); 6926 } 6927 } 6928 return SDValue(); 6929 } 6930 6931 // Matches any of the following bit-manipulation patterns: 6932 // (and (shl x, 1), (0x22222222 << 1)) 6933 // (and (srl x, 1), 0x22222222) 6934 // (shl (and x, 0x22222222), 1) 6935 // (srl (and x, (0x22222222 << 1)), 1) 6936 // where the shift amount and mask may vary thus: 6937 // [1] = 0x22222222 / 0x44444444 6938 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6939 // [4] = 0x00F000F0 / 0x0F000F00 6940 // [8] = 0x0000FF00 / 0x00FF0000 6941 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6942 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6943 // These are the unshifted masks which we use to match bit-manipulation 6944 // patterns. They may be shifted left in certain circumstances. 6945 static const uint64_t BitmanipMasks[] = { 6946 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6947 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6948 6949 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6950 } 6951 6952 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6953 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6954 const RISCVSubtarget &Subtarget) { 6955 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6956 EVT VT = Op.getValueType(); 6957 6958 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6959 return SDValue(); 6960 6961 SDValue Op0 = Op.getOperand(0); 6962 SDValue Op1 = Op.getOperand(1); 6963 6964 // Or is commutable so canonicalize the second OR to the LHS. 6965 if (Op0.getOpcode() != ISD::OR) 6966 std::swap(Op0, Op1); 6967 if (Op0.getOpcode() != ISD::OR) 6968 return SDValue(); 6969 6970 // We found an inner OR, so our operands are the operands of the inner OR 6971 // and the other operand of the outer OR. 6972 SDValue A = Op0.getOperand(0); 6973 SDValue B = Op0.getOperand(1); 6974 SDValue C = Op1; 6975 6976 auto Match1 = matchSHFLPat(A); 6977 auto Match2 = matchSHFLPat(B); 6978 6979 // If neither matched, we failed. 6980 if (!Match1 && !Match2) 6981 return SDValue(); 6982 6983 // We had at least one match. if one failed, try the remaining C operand. 6984 if (!Match1) { 6985 std::swap(A, C); 6986 Match1 = matchSHFLPat(A); 6987 if (!Match1) 6988 return SDValue(); 6989 } else if (!Match2) { 6990 std::swap(B, C); 6991 Match2 = matchSHFLPat(B); 6992 if (!Match2) 6993 return SDValue(); 6994 } 6995 assert(Match1 && Match2); 6996 6997 // Make sure our matches pair up. 6998 if (!Match1->formsPairWith(*Match2)) 6999 return SDValue(); 7000 7001 // All the remains is to make sure C is an AND with the same input, that masks 7002 // out the bits that are being shuffled. 7003 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7004 C.getOperand(0) != Match1->Op) 7005 return SDValue(); 7006 7007 uint64_t Mask = C.getConstantOperandVal(1); 7008 7009 static const uint64_t BitmanipMasks[] = { 7010 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7011 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7012 }; 7013 7014 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7015 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7016 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7017 7018 if (Mask != ExpMask) 7019 return SDValue(); 7020 7021 SDLoc DL(Op); 7022 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7023 DAG.getConstant(Match1->ShAmt, DL, VT)); 7024 } 7025 7026 // Optimize (add (shl x, c0), (shl y, c1)) -> 7027 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7028 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7029 const RISCVSubtarget &Subtarget) { 7030 // Perform this optimization only in the zba extension. 7031 if (!Subtarget.hasStdExtZba()) 7032 return SDValue(); 7033 7034 // Skip for vector types and larger types. 7035 EVT VT = N->getValueType(0); 7036 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7037 return SDValue(); 7038 7039 // The two operand nodes must be SHL and have no other use. 7040 SDValue N0 = N->getOperand(0); 7041 SDValue N1 = N->getOperand(1); 7042 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7043 !N0->hasOneUse() || !N1->hasOneUse()) 7044 return SDValue(); 7045 7046 // Check c0 and c1. 7047 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7048 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7049 if (!N0C || !N1C) 7050 return SDValue(); 7051 int64_t C0 = N0C->getSExtValue(); 7052 int64_t C1 = N1C->getSExtValue(); 7053 if (C0 <= 0 || C1 <= 0) 7054 return SDValue(); 7055 7056 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7057 int64_t Bits = std::min(C0, C1); 7058 int64_t Diff = std::abs(C0 - C1); 7059 if (Diff != 1 && Diff != 2 && Diff != 3) 7060 return SDValue(); 7061 7062 // Build nodes. 7063 SDLoc DL(N); 7064 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7065 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7066 SDValue NA0 = 7067 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7068 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7069 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7070 } 7071 7072 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7073 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7074 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7075 // not undo itself, but they are redundant. 7076 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7077 SDValue Src = N->getOperand(0); 7078 7079 if (Src.getOpcode() != N->getOpcode()) 7080 return SDValue(); 7081 7082 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7083 !isa<ConstantSDNode>(Src.getOperand(1))) 7084 return SDValue(); 7085 7086 unsigned ShAmt1 = N->getConstantOperandVal(1); 7087 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7088 Src = Src.getOperand(0); 7089 7090 unsigned CombinedShAmt; 7091 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7092 CombinedShAmt = ShAmt1 | ShAmt2; 7093 else 7094 CombinedShAmt = ShAmt1 ^ ShAmt2; 7095 7096 if (CombinedShAmt == 0) 7097 return Src; 7098 7099 SDLoc DL(N); 7100 return DAG.getNode( 7101 N->getOpcode(), DL, N->getValueType(0), Src, 7102 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7103 } 7104 7105 // Combine a constant select operand into its use: 7106 // 7107 // (and (select cond, -1, c), x) 7108 // -> (select cond, x, (and x, c)) [AllOnes=1] 7109 // (or (select cond, 0, c), x) 7110 // -> (select cond, x, (or x, c)) [AllOnes=0] 7111 // (xor (select cond, 0, c), x) 7112 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7113 // (add (select cond, 0, c), x) 7114 // -> (select cond, x, (add x, c)) [AllOnes=0] 7115 // (sub x, (select cond, 0, c)) 7116 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7117 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7118 SelectionDAG &DAG, bool AllOnes) { 7119 EVT VT = N->getValueType(0); 7120 7121 // Skip vectors. 7122 if (VT.isVector()) 7123 return SDValue(); 7124 7125 if ((Slct.getOpcode() != ISD::SELECT && 7126 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7127 !Slct.hasOneUse()) 7128 return SDValue(); 7129 7130 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7131 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7132 }; 7133 7134 bool SwapSelectOps; 7135 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7136 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7137 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7138 SDValue NonConstantVal; 7139 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7140 SwapSelectOps = false; 7141 NonConstantVal = FalseVal; 7142 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7143 SwapSelectOps = true; 7144 NonConstantVal = TrueVal; 7145 } else 7146 return SDValue(); 7147 7148 // Slct is now know to be the desired identity constant when CC is true. 7149 TrueVal = OtherOp; 7150 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7151 // Unless SwapSelectOps says the condition should be false. 7152 if (SwapSelectOps) 7153 std::swap(TrueVal, FalseVal); 7154 7155 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7156 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7157 {Slct.getOperand(0), Slct.getOperand(1), 7158 Slct.getOperand(2), TrueVal, FalseVal}); 7159 7160 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7161 {Slct.getOperand(0), TrueVal, FalseVal}); 7162 } 7163 7164 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7165 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7166 bool AllOnes) { 7167 SDValue N0 = N->getOperand(0); 7168 SDValue N1 = N->getOperand(1); 7169 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7170 return Result; 7171 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7172 return Result; 7173 return SDValue(); 7174 } 7175 7176 // Transform (add (mul x, c0), c1) -> 7177 // (add (mul (add x, c1/c0), c0), c1%c0). 7178 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7179 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7180 // to an infinite loop in DAGCombine if transformed. 7181 // Or transform (add (mul x, c0), c1) -> 7182 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7183 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7184 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7185 // lead to an infinite loop in DAGCombine if transformed. 7186 // Or transform (add (mul x, c0), c1) -> 7187 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7188 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7189 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7190 // lead to an infinite loop in DAGCombine if transformed. 7191 // Or transform (add (mul x, c0), c1) -> 7192 // (mul (add x, c1/c0), c0). 7193 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7194 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7195 const RISCVSubtarget &Subtarget) { 7196 // Skip for vector types and larger types. 7197 EVT VT = N->getValueType(0); 7198 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7199 return SDValue(); 7200 // The first operand node must be a MUL and has no other use. 7201 SDValue N0 = N->getOperand(0); 7202 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7203 return SDValue(); 7204 // Check if c0 and c1 match above conditions. 7205 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7206 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7207 if (!N0C || !N1C) 7208 return SDValue(); 7209 int64_t C0 = N0C->getSExtValue(); 7210 int64_t C1 = N1C->getSExtValue(); 7211 int64_t CA, CB; 7212 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7213 return SDValue(); 7214 // Search for proper CA (non-zero) and CB that both are simm12. 7215 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7216 !isInt<12>(C0 * (C1 / C0))) { 7217 CA = C1 / C0; 7218 CB = C1 % C0; 7219 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7220 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7221 CA = C1 / C0 + 1; 7222 CB = C1 % C0 - C0; 7223 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7224 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7225 CA = C1 / C0 - 1; 7226 CB = C1 % C0 + C0; 7227 } else 7228 return SDValue(); 7229 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7230 SDLoc DL(N); 7231 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7232 DAG.getConstant(CA, DL, VT)); 7233 SDValue New1 = 7234 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7235 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7236 } 7237 7238 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7239 const RISCVSubtarget &Subtarget) { 7240 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7241 return V; 7242 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7243 return V; 7244 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7245 // (select lhs, rhs, cc, x, (add x, y)) 7246 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7247 } 7248 7249 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7250 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7251 // (select lhs, rhs, cc, x, (sub x, y)) 7252 SDValue N0 = N->getOperand(0); 7253 SDValue N1 = N->getOperand(1); 7254 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7255 } 7256 7257 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7258 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7259 // (select lhs, rhs, cc, x, (and x, y)) 7260 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7261 } 7262 7263 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7264 const RISCVSubtarget &Subtarget) { 7265 if (Subtarget.hasStdExtZbp()) { 7266 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7267 return GREV; 7268 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7269 return GORC; 7270 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7271 return SHFL; 7272 } 7273 7274 // fold (or (select cond, 0, y), x) -> 7275 // (select cond, x, (or x, y)) 7276 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7277 } 7278 7279 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7280 // fold (xor (select cond, 0, y), x) -> 7281 // (select cond, x, (xor x, y)) 7282 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7283 } 7284 7285 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7286 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7287 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7288 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7289 // ADDW/SUBW/MULW. 7290 static SDValue performANY_EXTENDCombine(SDNode *N, 7291 TargetLowering::DAGCombinerInfo &DCI, 7292 const RISCVSubtarget &Subtarget) { 7293 if (!Subtarget.is64Bit()) 7294 return SDValue(); 7295 7296 SelectionDAG &DAG = DCI.DAG; 7297 7298 SDValue Src = N->getOperand(0); 7299 EVT VT = N->getValueType(0); 7300 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7301 return SDValue(); 7302 7303 // The opcode must be one that can implicitly sign_extend. 7304 // FIXME: Additional opcodes. 7305 switch (Src.getOpcode()) { 7306 default: 7307 return SDValue(); 7308 case ISD::MUL: 7309 if (!Subtarget.hasStdExtM()) 7310 return SDValue(); 7311 LLVM_FALLTHROUGH; 7312 case ISD::ADD: 7313 case ISD::SUB: 7314 break; 7315 } 7316 7317 // Only handle cases where the result is used by a CopyToReg. That likely 7318 // means the value is a liveout of the basic block. This helps prevent 7319 // infinite combine loops like PR51206. 7320 if (none_of(N->uses(), 7321 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7322 return SDValue(); 7323 7324 SmallVector<SDNode *, 4> SetCCs; 7325 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7326 UE = Src.getNode()->use_end(); 7327 UI != UE; ++UI) { 7328 SDNode *User = *UI; 7329 if (User == N) 7330 continue; 7331 if (UI.getUse().getResNo() != Src.getResNo()) 7332 continue; 7333 // All i32 setccs are legalized by sign extending operands. 7334 if (User->getOpcode() == ISD::SETCC) { 7335 SetCCs.push_back(User); 7336 continue; 7337 } 7338 // We don't know if we can extend this user. 7339 break; 7340 } 7341 7342 // If we don't have any SetCCs, this isn't worthwhile. 7343 if (SetCCs.empty()) 7344 return SDValue(); 7345 7346 SDLoc DL(N); 7347 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7348 DCI.CombineTo(N, SExt); 7349 7350 // Promote all the setccs. 7351 for (SDNode *SetCC : SetCCs) { 7352 SmallVector<SDValue, 4> Ops; 7353 7354 for (unsigned j = 0; j != 2; ++j) { 7355 SDValue SOp = SetCC->getOperand(j); 7356 if (SOp == Src) 7357 Ops.push_back(SExt); 7358 else 7359 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7360 } 7361 7362 Ops.push_back(SetCC->getOperand(2)); 7363 DCI.CombineTo(SetCC, 7364 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7365 } 7366 return SDValue(N, 0); 7367 } 7368 7369 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7370 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7371 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7372 bool Commute = false) { 7373 assert((N->getOpcode() == RISCVISD::ADD_VL || 7374 N->getOpcode() == RISCVISD::SUB_VL) && 7375 "Unexpected opcode"); 7376 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7377 SDValue Op0 = N->getOperand(0); 7378 SDValue Op1 = N->getOperand(1); 7379 if (Commute) 7380 std::swap(Op0, Op1); 7381 7382 MVT VT = N->getSimpleValueType(0); 7383 7384 // Determine the narrow size for a widening add/sub. 7385 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7386 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7387 VT.getVectorElementCount()); 7388 7389 SDValue Mask = N->getOperand(2); 7390 SDValue VL = N->getOperand(3); 7391 7392 SDLoc DL(N); 7393 7394 // If the RHS is a sext or zext, we can form a widening op. 7395 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7396 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7397 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7398 unsigned ExtOpc = Op1.getOpcode(); 7399 Op1 = Op1.getOperand(0); 7400 // Re-introduce narrower extends if needed. 7401 if (Op1.getValueType() != NarrowVT) 7402 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7403 7404 unsigned WOpc; 7405 if (ExtOpc == RISCVISD::VSEXT_VL) 7406 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7407 else 7408 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7409 7410 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7411 } 7412 7413 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7414 // sext/zext? 7415 7416 return SDValue(); 7417 } 7418 7419 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7420 // vwsub(u).vv/vx. 7421 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 7422 SDValue Op0 = N->getOperand(0); 7423 SDValue Op1 = N->getOperand(1); 7424 SDValue Mask = N->getOperand(2); 7425 SDValue VL = N->getOperand(3); 7426 7427 MVT VT = N->getSimpleValueType(0); 7428 MVT NarrowVT = Op1.getSimpleValueType(); 7429 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 7430 7431 unsigned VOpc; 7432 switch (N->getOpcode()) { 7433 default: llvm_unreachable("Unexpected opcode"); 7434 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 7435 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 7436 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 7437 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 7438 } 7439 7440 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 7441 N->getOpcode() == RISCVISD::VWSUB_W_VL; 7442 7443 SDLoc DL(N); 7444 7445 // If the LHS is a sext or zext, we can narrow this op to the same size as 7446 // the RHS. 7447 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 7448 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 7449 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 7450 unsigned ExtOpc = Op0.getOpcode(); 7451 Op0 = Op0.getOperand(0); 7452 // Re-introduce narrower extends if needed. 7453 if (Op0.getValueType() != NarrowVT) 7454 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7455 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 7456 } 7457 7458 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 7459 N->getOpcode() == RISCVISD::VWADDU_W_VL; 7460 7461 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 7462 // to commute and use a vwadd(u).vx instead. 7463 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 7464 Op0.getOperand(1) == VL) { 7465 Op0 = Op0.getOperand(0); 7466 7467 // See if have enough sign bits or zero bits in the scalar to use a 7468 // widening add/sub by splatting to smaller element size. 7469 unsigned EltBits = VT.getScalarSizeInBits(); 7470 unsigned ScalarBits = Op0.getValueSizeInBits(); 7471 // Make sure we're getting all element bits from the scalar register. 7472 // FIXME: Support implicit sign extension of vmv.v.x? 7473 if (ScalarBits < EltBits) 7474 return SDValue(); 7475 7476 if (IsSigned) { 7477 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 7478 return SDValue(); 7479 } else { 7480 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7481 if (!DAG.MaskedValueIsZero(Op0, Mask)) 7482 return SDValue(); 7483 } 7484 7485 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op0, VL); 7486 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 7487 } 7488 7489 return SDValue(); 7490 } 7491 7492 // Try to form VWMUL, VWMULU or VWMULSU. 7493 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7494 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7495 bool Commute) { 7496 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7497 SDValue Op0 = N->getOperand(0); 7498 SDValue Op1 = N->getOperand(1); 7499 if (Commute) 7500 std::swap(Op0, Op1); 7501 7502 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7503 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7504 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7505 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7506 return SDValue(); 7507 7508 SDValue Mask = N->getOperand(2); 7509 SDValue VL = N->getOperand(3); 7510 7511 // Make sure the mask and VL match. 7512 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7513 return SDValue(); 7514 7515 MVT VT = N->getSimpleValueType(0); 7516 7517 // Determine the narrow size for a widening multiply. 7518 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7519 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7520 VT.getVectorElementCount()); 7521 7522 SDLoc DL(N); 7523 7524 // See if the other operand is the same opcode. 7525 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7526 if (!Op1.hasOneUse()) 7527 return SDValue(); 7528 7529 // Make sure the mask and VL match. 7530 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7531 return SDValue(); 7532 7533 Op1 = Op1.getOperand(0); 7534 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7535 // The operand is a splat of a scalar. 7536 7537 // The VL must be the same. 7538 if (Op1.getOperand(1) != VL) 7539 return SDValue(); 7540 7541 // Get the scalar value. 7542 Op1 = Op1.getOperand(0); 7543 7544 // See if have enough sign bits or zero bits in the scalar to use a 7545 // widening multiply by splatting to smaller element size. 7546 unsigned EltBits = VT.getScalarSizeInBits(); 7547 unsigned ScalarBits = Op1.getValueSizeInBits(); 7548 // Make sure we're getting all element bits from the scalar register. 7549 // FIXME: Support implicit sign extension of vmv.v.x? 7550 if (ScalarBits < EltBits) 7551 return SDValue(); 7552 7553 if (IsSignExt) { 7554 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 7555 return SDValue(); 7556 } else { 7557 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7558 if (!DAG.MaskedValueIsZero(Op1, Mask)) 7559 return SDValue(); 7560 } 7561 7562 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 7563 } else 7564 return SDValue(); 7565 7566 Op0 = Op0.getOperand(0); 7567 7568 // Re-introduce narrower extends if needed. 7569 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7570 if (Op0.getValueType() != NarrowVT) 7571 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7572 if (Op1.getValueType() != NarrowVT) 7573 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7574 7575 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7576 if (!IsVWMULSU) 7577 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7578 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7579 } 7580 7581 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7582 switch (Op.getOpcode()) { 7583 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7584 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7585 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7586 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7587 case ISD::FROUND: return RISCVFPRndMode::RMM; 7588 } 7589 7590 return RISCVFPRndMode::Invalid; 7591 } 7592 7593 // Fold 7594 // (fp_to_int (froundeven X)) -> fcvt X, rne 7595 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7596 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7597 // (fp_to_int (fceil X)) -> fcvt X, rup 7598 // (fp_to_int (fround X)) -> fcvt X, rmm 7599 static SDValue performFP_TO_INTCombine(SDNode *N, 7600 TargetLowering::DAGCombinerInfo &DCI, 7601 const RISCVSubtarget &Subtarget) { 7602 SelectionDAG &DAG = DCI.DAG; 7603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7604 MVT XLenVT = Subtarget.getXLenVT(); 7605 7606 // Only handle XLen or i32 types. Other types narrower than XLen will 7607 // eventually be legalized to XLenVT. 7608 EVT VT = N->getValueType(0); 7609 if (VT != MVT::i32 && VT != XLenVT) 7610 return SDValue(); 7611 7612 SDValue Src = N->getOperand(0); 7613 7614 // Ensure the FP type is also legal. 7615 if (!TLI.isTypeLegal(Src.getValueType())) 7616 return SDValue(); 7617 7618 // Don't do this for f16 with Zfhmin and not Zfh. 7619 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7620 return SDValue(); 7621 7622 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7623 if (FRM == RISCVFPRndMode::Invalid) 7624 return SDValue(); 7625 7626 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7627 7628 unsigned Opc; 7629 if (VT == XLenVT) 7630 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7631 else 7632 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7633 7634 SDLoc DL(N); 7635 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7636 DAG.getTargetConstant(FRM, DL, XLenVT)); 7637 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7638 } 7639 7640 // Fold 7641 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7642 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 7643 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 7644 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 7645 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 7646 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 7647 TargetLowering::DAGCombinerInfo &DCI, 7648 const RISCVSubtarget &Subtarget) { 7649 SelectionDAG &DAG = DCI.DAG; 7650 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7651 MVT XLenVT = Subtarget.getXLenVT(); 7652 7653 // Only handle XLen types. Other types narrower than XLen will eventually be 7654 // legalized to XLenVT. 7655 EVT DstVT = N->getValueType(0); 7656 if (DstVT != XLenVT) 7657 return SDValue(); 7658 7659 SDValue Src = N->getOperand(0); 7660 7661 // Ensure the FP type is also legal. 7662 if (!TLI.isTypeLegal(Src.getValueType())) 7663 return SDValue(); 7664 7665 // Don't do this for f16 with Zfhmin and not Zfh. 7666 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7667 return SDValue(); 7668 7669 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7670 7671 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7672 if (FRM == RISCVFPRndMode::Invalid) 7673 return SDValue(); 7674 7675 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 7676 7677 unsigned Opc; 7678 if (SatVT == DstVT) 7679 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7680 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 7681 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7682 else 7683 return SDValue(); 7684 // FIXME: Support other SatVTs by clamping before or after the conversion. 7685 7686 Src = Src.getOperand(0); 7687 7688 SDLoc DL(N); 7689 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 7690 DAG.getTargetConstant(FRM, DL, XLenVT)); 7691 7692 // RISCV FP-to-int conversions saturate to the destination register size, but 7693 // don't produce 0 for nan. 7694 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 7695 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 7696 } 7697 7698 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7699 DAGCombinerInfo &DCI) const { 7700 SelectionDAG &DAG = DCI.DAG; 7701 7702 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7703 // bits are demanded. N will be added to the Worklist if it was not deleted. 7704 // Caller should return SDValue(N, 0) if this returns true. 7705 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7706 SDValue Op = N->getOperand(OpNo); 7707 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7708 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7709 return false; 7710 7711 if (N->getOpcode() != ISD::DELETED_NODE) 7712 DCI.AddToWorklist(N); 7713 return true; 7714 }; 7715 7716 switch (N->getOpcode()) { 7717 default: 7718 break; 7719 case RISCVISD::SplitF64: { 7720 SDValue Op0 = N->getOperand(0); 7721 // If the input to SplitF64 is just BuildPairF64 then the operation is 7722 // redundant. Instead, use BuildPairF64's operands directly. 7723 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7724 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7725 7726 SDLoc DL(N); 7727 7728 // It's cheaper to materialise two 32-bit integers than to load a double 7729 // from the constant pool and transfer it to integer registers through the 7730 // stack. 7731 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7732 APInt V = C->getValueAPF().bitcastToAPInt(); 7733 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 7734 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 7735 return DCI.CombineTo(N, Lo, Hi); 7736 } 7737 7738 // This is a target-specific version of a DAGCombine performed in 7739 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7740 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7741 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7742 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7743 !Op0.getNode()->hasOneUse()) 7744 break; 7745 SDValue NewSplitF64 = 7746 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 7747 Op0.getOperand(0)); 7748 SDValue Lo = NewSplitF64.getValue(0); 7749 SDValue Hi = NewSplitF64.getValue(1); 7750 APInt SignBit = APInt::getSignMask(32); 7751 if (Op0.getOpcode() == ISD::FNEG) { 7752 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 7753 DAG.getConstant(SignBit, DL, MVT::i32)); 7754 return DCI.CombineTo(N, Lo, NewHi); 7755 } 7756 assert(Op0.getOpcode() == ISD::FABS); 7757 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 7758 DAG.getConstant(~SignBit, DL, MVT::i32)); 7759 return DCI.CombineTo(N, Lo, NewHi); 7760 } 7761 case RISCVISD::SLLW: 7762 case RISCVISD::SRAW: 7763 case RISCVISD::SRLW: 7764 case RISCVISD::ROLW: 7765 case RISCVISD::RORW: { 7766 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7767 if (SimplifyDemandedLowBitsHelper(0, 32) || 7768 SimplifyDemandedLowBitsHelper(1, 5)) 7769 return SDValue(N, 0); 7770 break; 7771 } 7772 case RISCVISD::CLZW: 7773 case RISCVISD::CTZW: { 7774 // Only the lower 32 bits of the first operand are read 7775 if (SimplifyDemandedLowBitsHelper(0, 32)) 7776 return SDValue(N, 0); 7777 break; 7778 } 7779 case RISCVISD::GREV: 7780 case RISCVISD::GORC: { 7781 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 7782 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7783 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7784 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 7785 return SDValue(N, 0); 7786 7787 return combineGREVI_GORCI(N, DAG); 7788 } 7789 case RISCVISD::GREVW: 7790 case RISCVISD::GORCW: { 7791 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7792 if (SimplifyDemandedLowBitsHelper(0, 32) || 7793 SimplifyDemandedLowBitsHelper(1, 5)) 7794 return SDValue(N, 0); 7795 7796 return combineGREVI_GORCI(N, DAG); 7797 } 7798 case RISCVISD::SHFL: 7799 case RISCVISD::UNSHFL: { 7800 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 7801 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7802 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7803 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 7804 return SDValue(N, 0); 7805 7806 break; 7807 } 7808 case RISCVISD::SHFLW: 7809 case RISCVISD::UNSHFLW: { 7810 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 7811 if (SimplifyDemandedLowBitsHelper(0, 32) || 7812 SimplifyDemandedLowBitsHelper(1, 4)) 7813 return SDValue(N, 0); 7814 7815 break; 7816 } 7817 case RISCVISD::BCOMPRESSW: 7818 case RISCVISD::BDECOMPRESSW: { 7819 // Only the lower 32 bits of LHS and RHS are read. 7820 if (SimplifyDemandedLowBitsHelper(0, 32) || 7821 SimplifyDemandedLowBitsHelper(1, 32)) 7822 return SDValue(N, 0); 7823 7824 break; 7825 } 7826 case RISCVISD::FMV_X_ANYEXTH: 7827 case RISCVISD::FMV_X_ANYEXTW_RV64: { 7828 SDLoc DL(N); 7829 SDValue Op0 = N->getOperand(0); 7830 MVT VT = N->getSimpleValueType(0); 7831 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 7832 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 7833 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 7834 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 7835 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 7836 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7837 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 7838 assert(Op0.getOperand(0).getValueType() == VT && 7839 "Unexpected value type!"); 7840 return Op0.getOperand(0); 7841 } 7842 7843 // This is a target-specific version of a DAGCombine performed in 7844 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7845 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7846 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7847 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7848 !Op0.getNode()->hasOneUse()) 7849 break; 7850 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 7851 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 7852 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7853 if (Op0.getOpcode() == ISD::FNEG) 7854 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7855 DAG.getConstant(SignBit, DL, VT)); 7856 7857 assert(Op0.getOpcode() == ISD::FABS); 7858 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7859 DAG.getConstant(~SignBit, DL, VT)); 7860 } 7861 case ISD::ADD: 7862 return performADDCombine(N, DAG, Subtarget); 7863 case ISD::SUB: 7864 return performSUBCombine(N, DAG); 7865 case ISD::AND: 7866 return performANDCombine(N, DAG); 7867 case ISD::OR: 7868 return performORCombine(N, DAG, Subtarget); 7869 case ISD::XOR: 7870 return performXORCombine(N, DAG); 7871 case ISD::ANY_EXTEND: 7872 return performANY_EXTENDCombine(N, DCI, Subtarget); 7873 case ISD::ZERO_EXTEND: 7874 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7875 // type legalization. This is safe because fp_to_uint produces poison if 7876 // it overflows. 7877 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 7878 SDValue Src = N->getOperand(0); 7879 if (Src.getOpcode() == ISD::FP_TO_UINT && 7880 isTypeLegal(Src.getOperand(0).getValueType())) 7881 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7882 Src.getOperand(0)); 7883 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 7884 isTypeLegal(Src.getOperand(1).getValueType())) { 7885 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7886 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 7887 Src.getOperand(0), Src.getOperand(1)); 7888 DCI.CombineTo(N, Res); 7889 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 7890 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 7891 return SDValue(N, 0); // Return N so it doesn't get rechecked. 7892 } 7893 } 7894 return SDValue(); 7895 case RISCVISD::SELECT_CC: { 7896 // Transform 7897 SDValue LHS = N->getOperand(0); 7898 SDValue RHS = N->getOperand(1); 7899 SDValue TrueV = N->getOperand(3); 7900 SDValue FalseV = N->getOperand(4); 7901 7902 // If the True and False values are the same, we don't need a select_cc. 7903 if (TrueV == FalseV) 7904 return TrueV; 7905 7906 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7907 if (!ISD::isIntEqualitySetCC(CCVal)) 7908 break; 7909 7910 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7911 // (select_cc X, Y, lt, trueV, falseV) 7912 // Sometimes the setcc is introduced after select_cc has been formed. 7913 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7914 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7915 // If we're looking for eq 0 instead of ne 0, we need to invert the 7916 // condition. 7917 bool Invert = CCVal == ISD::SETEQ; 7918 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7919 if (Invert) 7920 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7921 7922 SDLoc DL(N); 7923 RHS = LHS.getOperand(1); 7924 LHS = LHS.getOperand(0); 7925 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7926 7927 SDValue TargetCC = DAG.getCondCode(CCVal); 7928 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7929 {LHS, RHS, TargetCC, TrueV, FalseV}); 7930 } 7931 7932 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7933 // (select_cc X, Y, eq/ne, trueV, falseV) 7934 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7935 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7936 {LHS.getOperand(0), LHS.getOperand(1), 7937 N->getOperand(2), TrueV, FalseV}); 7938 // (select_cc X, 1, setne, trueV, falseV) -> 7939 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7940 // This can occur when legalizing some floating point comparisons. 7941 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7942 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7943 SDLoc DL(N); 7944 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7945 SDValue TargetCC = DAG.getCondCode(CCVal); 7946 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7947 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7948 {LHS, RHS, TargetCC, TrueV, FalseV}); 7949 } 7950 7951 break; 7952 } 7953 case RISCVISD::BR_CC: { 7954 SDValue LHS = N->getOperand(1); 7955 SDValue RHS = N->getOperand(2); 7956 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7957 if (!ISD::isIntEqualitySetCC(CCVal)) 7958 break; 7959 7960 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7961 // (br_cc X, Y, lt, dest) 7962 // Sometimes the setcc is introduced after br_cc has been formed. 7963 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7964 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7965 // If we're looking for eq 0 instead of ne 0, we need to invert the 7966 // condition. 7967 bool Invert = CCVal == ISD::SETEQ; 7968 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7969 if (Invert) 7970 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7971 7972 SDLoc DL(N); 7973 RHS = LHS.getOperand(1); 7974 LHS = LHS.getOperand(0); 7975 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7976 7977 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7978 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7979 N->getOperand(4)); 7980 } 7981 7982 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7983 // (br_cc X, Y, eq/ne, trueV, falseV) 7984 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7985 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7986 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7987 N->getOperand(3), N->getOperand(4)); 7988 7989 // (br_cc X, 1, setne, br_cc) -> 7990 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7991 // This can occur when legalizing some floating point comparisons. 7992 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7993 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7994 SDLoc DL(N); 7995 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7996 SDValue TargetCC = DAG.getCondCode(CCVal); 7997 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7998 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7999 N->getOperand(0), LHS, RHS, TargetCC, 8000 N->getOperand(4)); 8001 } 8002 break; 8003 } 8004 case ISD::FP_TO_SINT: 8005 case ISD::FP_TO_UINT: 8006 return performFP_TO_INTCombine(N, DCI, Subtarget); 8007 case ISD::FP_TO_SINT_SAT: 8008 case ISD::FP_TO_UINT_SAT: 8009 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8010 case ISD::FCOPYSIGN: { 8011 EVT VT = N->getValueType(0); 8012 if (!VT.isVector()) 8013 break; 8014 // There is a form of VFSGNJ which injects the negated sign of its second 8015 // operand. Try and bubble any FNEG up after the extend/round to produce 8016 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8017 // TRUNC=1. 8018 SDValue In2 = N->getOperand(1); 8019 // Avoid cases where the extend/round has multiple uses, as duplicating 8020 // those is typically more expensive than removing a fneg. 8021 if (!In2.hasOneUse()) 8022 break; 8023 if (In2.getOpcode() != ISD::FP_EXTEND && 8024 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8025 break; 8026 In2 = In2.getOperand(0); 8027 if (In2.getOpcode() != ISD::FNEG) 8028 break; 8029 SDLoc DL(N); 8030 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8031 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8032 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8033 } 8034 case ISD::MGATHER: 8035 case ISD::MSCATTER: 8036 case ISD::VP_GATHER: 8037 case ISD::VP_SCATTER: { 8038 if (!DCI.isBeforeLegalize()) 8039 break; 8040 SDValue Index, ScaleOp; 8041 bool IsIndexScaled = false; 8042 bool IsIndexSigned = false; 8043 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8044 Index = VPGSN->getIndex(); 8045 ScaleOp = VPGSN->getScale(); 8046 IsIndexScaled = VPGSN->isIndexScaled(); 8047 IsIndexSigned = VPGSN->isIndexSigned(); 8048 } else { 8049 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8050 Index = MGSN->getIndex(); 8051 ScaleOp = MGSN->getScale(); 8052 IsIndexScaled = MGSN->isIndexScaled(); 8053 IsIndexSigned = MGSN->isIndexSigned(); 8054 } 8055 EVT IndexVT = Index.getValueType(); 8056 MVT XLenVT = Subtarget.getXLenVT(); 8057 // RISCV indexed loads only support the "unsigned unscaled" addressing 8058 // mode, so anything else must be manually legalized. 8059 bool NeedsIdxLegalization = 8060 IsIndexScaled || 8061 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8062 if (!NeedsIdxLegalization) 8063 break; 8064 8065 SDLoc DL(N); 8066 8067 // Any index legalization should first promote to XLenVT, so we don't lose 8068 // bits when scaling. This may create an illegal index type so we let 8069 // LLVM's legalization take care of the splitting. 8070 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8071 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8072 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8073 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8074 DL, IndexVT, Index); 8075 } 8076 8077 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8078 if (IsIndexScaled && Scale != 1) { 8079 // Manually scale the indices by the element size. 8080 // TODO: Sanitize the scale operand here? 8081 // TODO: For VP nodes, should we use VP_SHL here? 8082 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8083 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8084 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8085 } 8086 8087 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8088 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8089 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8090 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8091 VPGN->getScale(), VPGN->getMask(), 8092 VPGN->getVectorLength()}, 8093 VPGN->getMemOperand(), NewIndexTy); 8094 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8095 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8096 {VPSN->getChain(), VPSN->getValue(), 8097 VPSN->getBasePtr(), Index, VPSN->getScale(), 8098 VPSN->getMask(), VPSN->getVectorLength()}, 8099 VPSN->getMemOperand(), NewIndexTy); 8100 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8101 return DAG.getMaskedGather( 8102 N->getVTList(), MGN->getMemoryVT(), DL, 8103 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8104 MGN->getBasePtr(), Index, MGN->getScale()}, 8105 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8106 const auto *MSN = cast<MaskedScatterSDNode>(N); 8107 return DAG.getMaskedScatter( 8108 N->getVTList(), MSN->getMemoryVT(), DL, 8109 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8110 Index, MSN->getScale()}, 8111 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8112 } 8113 case RISCVISD::SRA_VL: 8114 case RISCVISD::SRL_VL: 8115 case RISCVISD::SHL_VL: { 8116 SDValue ShAmt = N->getOperand(1); 8117 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8118 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8119 SDLoc DL(N); 8120 SDValue VL = N->getOperand(3); 8121 EVT VT = N->getValueType(0); 8122 ShAmt = 8123 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 8124 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8125 N->getOperand(2), N->getOperand(3)); 8126 } 8127 break; 8128 } 8129 case ISD::SRA: 8130 case ISD::SRL: 8131 case ISD::SHL: { 8132 SDValue ShAmt = N->getOperand(1); 8133 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8134 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8135 SDLoc DL(N); 8136 EVT VT = N->getValueType(0); 8137 ShAmt = 8138 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 8139 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8140 } 8141 break; 8142 } 8143 case RISCVISD::ADD_VL: 8144 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8145 return V; 8146 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8147 case RISCVISD::SUB_VL: 8148 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8149 case RISCVISD::VWADD_W_VL: 8150 case RISCVISD::VWADDU_W_VL: 8151 case RISCVISD::VWSUB_W_VL: 8152 case RISCVISD::VWSUBU_W_VL: 8153 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8154 case RISCVISD::MUL_VL: 8155 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8156 return V; 8157 // Mul is commutative. 8158 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8159 case ISD::STORE: { 8160 auto *Store = cast<StoreSDNode>(N); 8161 SDValue Val = Store->getValue(); 8162 // Combine store of vmv.x.s to vse with VL of 1. 8163 // FIXME: Support FP. 8164 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8165 SDValue Src = Val.getOperand(0); 8166 EVT VecVT = Src.getValueType(); 8167 EVT MemVT = Store->getMemoryVT(); 8168 // The memory VT and the element type must match. 8169 if (VecVT.getVectorElementType() == MemVT) { 8170 SDLoc DL(N); 8171 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 8172 return DAG.getStoreVP( 8173 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8174 DAG.getConstant(1, DL, MaskVT), 8175 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8176 Store->getMemOperand(), Store->getAddressingMode(), 8177 Store->isTruncatingStore(), /*IsCompress*/ false); 8178 } 8179 } 8180 8181 break; 8182 } 8183 } 8184 8185 return SDValue(); 8186 } 8187 8188 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8189 const SDNode *N, CombineLevel Level) const { 8190 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8191 // materialised in fewer instructions than `(OP _, c1)`: 8192 // 8193 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8194 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8195 SDValue N0 = N->getOperand(0); 8196 EVT Ty = N0.getValueType(); 8197 if (Ty.isScalarInteger() && 8198 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8199 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8200 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8201 if (C1 && C2) { 8202 const APInt &C1Int = C1->getAPIntValue(); 8203 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8204 8205 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8206 // and the combine should happen, to potentially allow further combines 8207 // later. 8208 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8209 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8210 return true; 8211 8212 // We can materialise `c1` in an add immediate, so it's "free", and the 8213 // combine should be prevented. 8214 if (C1Int.getMinSignedBits() <= 64 && 8215 isLegalAddImmediate(C1Int.getSExtValue())) 8216 return false; 8217 8218 // Neither constant will fit into an immediate, so find materialisation 8219 // costs. 8220 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8221 Subtarget.getFeatureBits(), 8222 /*CompressionCost*/true); 8223 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8224 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8225 /*CompressionCost*/true); 8226 8227 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8228 // combine should be prevented. 8229 if (C1Cost < ShiftedC1Cost) 8230 return false; 8231 } 8232 } 8233 return true; 8234 } 8235 8236 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8237 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8238 TargetLoweringOpt &TLO) const { 8239 // Delay this optimization as late as possible. 8240 if (!TLO.LegalOps) 8241 return false; 8242 8243 EVT VT = Op.getValueType(); 8244 if (VT.isVector()) 8245 return false; 8246 8247 // Only handle AND for now. 8248 if (Op.getOpcode() != ISD::AND) 8249 return false; 8250 8251 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8252 if (!C) 8253 return false; 8254 8255 const APInt &Mask = C->getAPIntValue(); 8256 8257 // Clear all non-demanded bits initially. 8258 APInt ShrunkMask = Mask & DemandedBits; 8259 8260 // Try to make a smaller immediate by setting undemanded bits. 8261 8262 APInt ExpandedMask = Mask | ~DemandedBits; 8263 8264 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8265 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8266 }; 8267 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8268 if (NewMask == Mask) 8269 return true; 8270 SDLoc DL(Op); 8271 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8272 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8273 return TLO.CombineTo(Op, NewOp); 8274 }; 8275 8276 // If the shrunk mask fits in sign extended 12 bits, let the target 8277 // independent code apply it. 8278 if (ShrunkMask.isSignedIntN(12)) 8279 return false; 8280 8281 // Preserve (and X, 0xffff) when zext.h is supported. 8282 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8283 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8284 if (IsLegalMask(NewMask)) 8285 return UseMask(NewMask); 8286 } 8287 8288 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8289 if (VT == MVT::i64) { 8290 APInt NewMask = APInt(64, 0xffffffff); 8291 if (IsLegalMask(NewMask)) 8292 return UseMask(NewMask); 8293 } 8294 8295 // For the remaining optimizations, we need to be able to make a negative 8296 // number through a combination of mask and undemanded bits. 8297 if (!ExpandedMask.isNegative()) 8298 return false; 8299 8300 // What is the fewest number of bits we need to represent the negative number. 8301 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8302 8303 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8304 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8305 APInt NewMask = ShrunkMask; 8306 if (MinSignedBits <= 12) 8307 NewMask.setBitsFrom(11); 8308 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8309 NewMask.setBitsFrom(31); 8310 else 8311 return false; 8312 8313 // Check that our new mask is a subset of the demanded mask. 8314 assert(IsLegalMask(NewMask)); 8315 return UseMask(NewMask); 8316 } 8317 8318 static void computeGREV(APInt &Src, unsigned ShAmt) { 8319 ShAmt &= Src.getBitWidth() - 1; 8320 uint64_t x = Src.getZExtValue(); 8321 if (ShAmt & 1) 8322 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8323 if (ShAmt & 2) 8324 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8325 if (ShAmt & 4) 8326 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8327 if (ShAmt & 8) 8328 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8329 if (ShAmt & 16) 8330 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8331 if (ShAmt & 32) 8332 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8333 Src = x; 8334 } 8335 8336 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8337 KnownBits &Known, 8338 const APInt &DemandedElts, 8339 const SelectionDAG &DAG, 8340 unsigned Depth) const { 8341 unsigned BitWidth = Known.getBitWidth(); 8342 unsigned Opc = Op.getOpcode(); 8343 assert((Opc >= ISD::BUILTIN_OP_END || 8344 Opc == ISD::INTRINSIC_WO_CHAIN || 8345 Opc == ISD::INTRINSIC_W_CHAIN || 8346 Opc == ISD::INTRINSIC_VOID) && 8347 "Should use MaskedValueIsZero if you don't know whether Op" 8348 " is a target node!"); 8349 8350 Known.resetAll(); 8351 switch (Opc) { 8352 default: break; 8353 case RISCVISD::SELECT_CC: { 8354 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8355 // If we don't know any bits, early out. 8356 if (Known.isUnknown()) 8357 break; 8358 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8359 8360 // Only known if known in both the LHS and RHS. 8361 Known = KnownBits::commonBits(Known, Known2); 8362 break; 8363 } 8364 case RISCVISD::REMUW: { 8365 KnownBits Known2; 8366 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8367 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8368 // We only care about the lower 32 bits. 8369 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8370 // Restore the original width by sign extending. 8371 Known = Known.sext(BitWidth); 8372 break; 8373 } 8374 case RISCVISD::DIVUW: { 8375 KnownBits Known2; 8376 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8377 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8378 // We only care about the lower 32 bits. 8379 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8380 // Restore the original width by sign extending. 8381 Known = Known.sext(BitWidth); 8382 break; 8383 } 8384 case RISCVISD::CTZW: { 8385 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8386 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8387 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8388 Known.Zero.setBitsFrom(LowBits); 8389 break; 8390 } 8391 case RISCVISD::CLZW: { 8392 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8393 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8394 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8395 Known.Zero.setBitsFrom(LowBits); 8396 break; 8397 } 8398 case RISCVISD::GREV: 8399 case RISCVISD::GREVW: { 8400 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8401 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8402 if (Opc == RISCVISD::GREVW) 8403 Known = Known.trunc(32); 8404 unsigned ShAmt = C->getZExtValue(); 8405 computeGREV(Known.Zero, ShAmt); 8406 computeGREV(Known.One, ShAmt); 8407 if (Opc == RISCVISD::GREVW) 8408 Known = Known.sext(BitWidth); 8409 } 8410 break; 8411 } 8412 case RISCVISD::READ_VLENB: { 8413 // If we know the minimum VLen from Zvl extensions, we can use that to 8414 // determine the trailing zeros of VLENB. 8415 // FIXME: Limit to 128 bit vectors until we have more testing. 8416 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 8417 if (MinVLenB > 0) 8418 Known.Zero.setLowBits(Log2_32(MinVLenB)); 8419 // We assume VLENB is no more than 65536 / 8 bytes. 8420 Known.Zero.setBitsFrom(14); 8421 break; 8422 } 8423 case ISD::INTRINSIC_W_CHAIN: 8424 case ISD::INTRINSIC_WO_CHAIN: { 8425 unsigned IntNo = 8426 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8427 switch (IntNo) { 8428 default: 8429 // We can't do anything for most intrinsics. 8430 break; 8431 case Intrinsic::riscv_vsetvli: 8432 case Intrinsic::riscv_vsetvlimax: 8433 case Intrinsic::riscv_vsetvli_opt: 8434 case Intrinsic::riscv_vsetvlimax_opt: 8435 // Assume that VL output is positive and would fit in an int32_t. 8436 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8437 if (BitWidth >= 32) 8438 Known.Zero.setBitsFrom(31); 8439 break; 8440 } 8441 break; 8442 } 8443 } 8444 } 8445 8446 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8447 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8448 unsigned Depth) const { 8449 switch (Op.getOpcode()) { 8450 default: 8451 break; 8452 case RISCVISD::SELECT_CC: { 8453 unsigned Tmp = 8454 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8455 if (Tmp == 1) return 1; // Early out. 8456 unsigned Tmp2 = 8457 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8458 return std::min(Tmp, Tmp2); 8459 } 8460 case RISCVISD::SLLW: 8461 case RISCVISD::SRAW: 8462 case RISCVISD::SRLW: 8463 case RISCVISD::DIVW: 8464 case RISCVISD::DIVUW: 8465 case RISCVISD::REMUW: 8466 case RISCVISD::ROLW: 8467 case RISCVISD::RORW: 8468 case RISCVISD::GREVW: 8469 case RISCVISD::GORCW: 8470 case RISCVISD::FSLW: 8471 case RISCVISD::FSRW: 8472 case RISCVISD::SHFLW: 8473 case RISCVISD::UNSHFLW: 8474 case RISCVISD::BCOMPRESSW: 8475 case RISCVISD::BDECOMPRESSW: 8476 case RISCVISD::BFPW: 8477 case RISCVISD::FCVT_W_RV64: 8478 case RISCVISD::FCVT_WU_RV64: 8479 case RISCVISD::STRICT_FCVT_W_RV64: 8480 case RISCVISD::STRICT_FCVT_WU_RV64: 8481 // TODO: As the result is sign-extended, this is conservatively correct. A 8482 // more precise answer could be calculated for SRAW depending on known 8483 // bits in the shift amount. 8484 return 33; 8485 case RISCVISD::SHFL: 8486 case RISCVISD::UNSHFL: { 8487 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8488 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8489 // will stay within the upper 32 bits. If there were more than 32 sign bits 8490 // before there will be at least 33 sign bits after. 8491 if (Op.getValueType() == MVT::i64 && 8492 isa<ConstantSDNode>(Op.getOperand(1)) && 8493 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8494 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8495 if (Tmp > 32) 8496 return 33; 8497 } 8498 break; 8499 } 8500 case RISCVISD::VMV_X_S: { 8501 // The number of sign bits of the scalar result is computed by obtaining the 8502 // element type of the input vector operand, subtracting its width from the 8503 // XLEN, and then adding one (sign bit within the element type). If the 8504 // element type is wider than XLen, the least-significant XLEN bits are 8505 // taken. 8506 unsigned XLen = Subtarget.getXLen(); 8507 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 8508 if (EltBits <= XLen) 8509 return XLen - EltBits + 1; 8510 break; 8511 } 8512 } 8513 8514 return 1; 8515 } 8516 8517 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8518 MachineBasicBlock *BB) { 8519 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8520 8521 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8522 // Should the count have wrapped while it was being read, we need to try 8523 // again. 8524 // ... 8525 // read: 8526 // rdcycleh x3 # load high word of cycle 8527 // rdcycle x2 # load low word of cycle 8528 // rdcycleh x4 # load high word of cycle 8529 // bne x3, x4, read # check if high word reads match, otherwise try again 8530 // ... 8531 8532 MachineFunction &MF = *BB->getParent(); 8533 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8534 MachineFunction::iterator It = ++BB->getIterator(); 8535 8536 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8537 MF.insert(It, LoopMBB); 8538 8539 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8540 MF.insert(It, DoneMBB); 8541 8542 // Transfer the remainder of BB and its successor edges to DoneMBB. 8543 DoneMBB->splice(DoneMBB->begin(), BB, 8544 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8545 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8546 8547 BB->addSuccessor(LoopMBB); 8548 8549 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8550 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8551 Register LoReg = MI.getOperand(0).getReg(); 8552 Register HiReg = MI.getOperand(1).getReg(); 8553 DebugLoc DL = MI.getDebugLoc(); 8554 8555 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8556 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8557 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8558 .addReg(RISCV::X0); 8559 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8560 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8561 .addReg(RISCV::X0); 8562 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8563 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8564 .addReg(RISCV::X0); 8565 8566 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8567 .addReg(HiReg) 8568 .addReg(ReadAgainReg) 8569 .addMBB(LoopMBB); 8570 8571 LoopMBB->addSuccessor(LoopMBB); 8572 LoopMBB->addSuccessor(DoneMBB); 8573 8574 MI.eraseFromParent(); 8575 8576 return DoneMBB; 8577 } 8578 8579 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8580 MachineBasicBlock *BB) { 8581 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8582 8583 MachineFunction &MF = *BB->getParent(); 8584 DebugLoc DL = MI.getDebugLoc(); 8585 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8586 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8587 Register LoReg = MI.getOperand(0).getReg(); 8588 Register HiReg = MI.getOperand(1).getReg(); 8589 Register SrcReg = MI.getOperand(2).getReg(); 8590 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8591 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8592 8593 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8594 RI); 8595 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8596 MachineMemOperand *MMOLo = 8597 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8598 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8599 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8600 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8601 .addFrameIndex(FI) 8602 .addImm(0) 8603 .addMemOperand(MMOLo); 8604 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8605 .addFrameIndex(FI) 8606 .addImm(4) 8607 .addMemOperand(MMOHi); 8608 MI.eraseFromParent(); // The pseudo instruction is gone now. 8609 return BB; 8610 } 8611 8612 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8613 MachineBasicBlock *BB) { 8614 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8615 "Unexpected instruction"); 8616 8617 MachineFunction &MF = *BB->getParent(); 8618 DebugLoc DL = MI.getDebugLoc(); 8619 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8620 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8621 Register DstReg = MI.getOperand(0).getReg(); 8622 Register LoReg = MI.getOperand(1).getReg(); 8623 Register HiReg = MI.getOperand(2).getReg(); 8624 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8625 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8626 8627 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8628 MachineMemOperand *MMOLo = 8629 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8630 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8631 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8632 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8633 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8634 .addFrameIndex(FI) 8635 .addImm(0) 8636 .addMemOperand(MMOLo); 8637 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8638 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8639 .addFrameIndex(FI) 8640 .addImm(4) 8641 .addMemOperand(MMOHi); 8642 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8643 MI.eraseFromParent(); // The pseudo instruction is gone now. 8644 return BB; 8645 } 8646 8647 static bool isSelectPseudo(MachineInstr &MI) { 8648 switch (MI.getOpcode()) { 8649 default: 8650 return false; 8651 case RISCV::Select_GPR_Using_CC_GPR: 8652 case RISCV::Select_FPR16_Using_CC_GPR: 8653 case RISCV::Select_FPR32_Using_CC_GPR: 8654 case RISCV::Select_FPR64_Using_CC_GPR: 8655 return true; 8656 } 8657 } 8658 8659 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8660 unsigned RelOpcode, unsigned EqOpcode, 8661 const RISCVSubtarget &Subtarget) { 8662 DebugLoc DL = MI.getDebugLoc(); 8663 Register DstReg = MI.getOperand(0).getReg(); 8664 Register Src1Reg = MI.getOperand(1).getReg(); 8665 Register Src2Reg = MI.getOperand(2).getReg(); 8666 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8667 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8668 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8669 8670 // Save the current FFLAGS. 8671 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8672 8673 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8674 .addReg(Src1Reg) 8675 .addReg(Src2Reg); 8676 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8677 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8678 8679 // Restore the FFLAGS. 8680 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 8681 .addReg(SavedFFlags, RegState::Kill); 8682 8683 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 8684 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 8685 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 8686 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 8687 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8688 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 8689 8690 // Erase the pseudoinstruction. 8691 MI.eraseFromParent(); 8692 return BB; 8693 } 8694 8695 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 8696 MachineBasicBlock *BB, 8697 const RISCVSubtarget &Subtarget) { 8698 // To "insert" Select_* instructions, we actually have to insert the triangle 8699 // control-flow pattern. The incoming instructions know the destination vreg 8700 // to set, the condition code register to branch on, the true/false values to 8701 // select between, and the condcode to use to select the appropriate branch. 8702 // 8703 // We produce the following control flow: 8704 // HeadMBB 8705 // | \ 8706 // | IfFalseMBB 8707 // | / 8708 // TailMBB 8709 // 8710 // When we find a sequence of selects we attempt to optimize their emission 8711 // by sharing the control flow. Currently we only handle cases where we have 8712 // multiple selects with the exact same condition (same LHS, RHS and CC). 8713 // The selects may be interleaved with other instructions if the other 8714 // instructions meet some requirements we deem safe: 8715 // - They are debug instructions. Otherwise, 8716 // - They do not have side-effects, do not access memory and their inputs do 8717 // not depend on the results of the select pseudo-instructions. 8718 // The TrueV/FalseV operands of the selects cannot depend on the result of 8719 // previous selects in the sequence. 8720 // These conditions could be further relaxed. See the X86 target for a 8721 // related approach and more information. 8722 Register LHS = MI.getOperand(1).getReg(); 8723 Register RHS = MI.getOperand(2).getReg(); 8724 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 8725 8726 SmallVector<MachineInstr *, 4> SelectDebugValues; 8727 SmallSet<Register, 4> SelectDests; 8728 SelectDests.insert(MI.getOperand(0).getReg()); 8729 8730 MachineInstr *LastSelectPseudo = &MI; 8731 8732 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 8733 SequenceMBBI != E; ++SequenceMBBI) { 8734 if (SequenceMBBI->isDebugInstr()) 8735 continue; 8736 else if (isSelectPseudo(*SequenceMBBI)) { 8737 if (SequenceMBBI->getOperand(1).getReg() != LHS || 8738 SequenceMBBI->getOperand(2).getReg() != RHS || 8739 SequenceMBBI->getOperand(3).getImm() != CC || 8740 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 8741 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 8742 break; 8743 LastSelectPseudo = &*SequenceMBBI; 8744 SequenceMBBI->collectDebugValues(SelectDebugValues); 8745 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 8746 } else { 8747 if (SequenceMBBI->hasUnmodeledSideEffects() || 8748 SequenceMBBI->mayLoadOrStore()) 8749 break; 8750 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 8751 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 8752 })) 8753 break; 8754 } 8755 } 8756 8757 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 8758 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8759 DebugLoc DL = MI.getDebugLoc(); 8760 MachineFunction::iterator I = ++BB->getIterator(); 8761 8762 MachineBasicBlock *HeadMBB = BB; 8763 MachineFunction *F = BB->getParent(); 8764 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 8765 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 8766 8767 F->insert(I, IfFalseMBB); 8768 F->insert(I, TailMBB); 8769 8770 // Transfer debug instructions associated with the selects to TailMBB. 8771 for (MachineInstr *DebugInstr : SelectDebugValues) { 8772 TailMBB->push_back(DebugInstr->removeFromParent()); 8773 } 8774 8775 // Move all instructions after the sequence to TailMBB. 8776 TailMBB->splice(TailMBB->end(), HeadMBB, 8777 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 8778 // Update machine-CFG edges by transferring all successors of the current 8779 // block to the new block which will contain the Phi nodes for the selects. 8780 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 8781 // Set the successors for HeadMBB. 8782 HeadMBB->addSuccessor(IfFalseMBB); 8783 HeadMBB->addSuccessor(TailMBB); 8784 8785 // Insert appropriate branch. 8786 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 8787 .addReg(LHS) 8788 .addReg(RHS) 8789 .addMBB(TailMBB); 8790 8791 // IfFalseMBB just falls through to TailMBB. 8792 IfFalseMBB->addSuccessor(TailMBB); 8793 8794 // Create PHIs for all of the select pseudo-instructions. 8795 auto SelectMBBI = MI.getIterator(); 8796 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 8797 auto InsertionPoint = TailMBB->begin(); 8798 while (SelectMBBI != SelectEnd) { 8799 auto Next = std::next(SelectMBBI); 8800 if (isSelectPseudo(*SelectMBBI)) { 8801 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 8802 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 8803 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 8804 .addReg(SelectMBBI->getOperand(4).getReg()) 8805 .addMBB(HeadMBB) 8806 .addReg(SelectMBBI->getOperand(5).getReg()) 8807 .addMBB(IfFalseMBB); 8808 SelectMBBI->eraseFromParent(); 8809 } 8810 SelectMBBI = Next; 8811 } 8812 8813 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8814 return TailMBB; 8815 } 8816 8817 MachineBasicBlock * 8818 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8819 MachineBasicBlock *BB) const { 8820 switch (MI.getOpcode()) { 8821 default: 8822 llvm_unreachable("Unexpected instr type to insert"); 8823 case RISCV::ReadCycleWide: 8824 assert(!Subtarget.is64Bit() && 8825 "ReadCycleWrite is only to be used on riscv32"); 8826 return emitReadCycleWidePseudo(MI, BB); 8827 case RISCV::Select_GPR_Using_CC_GPR: 8828 case RISCV::Select_FPR16_Using_CC_GPR: 8829 case RISCV::Select_FPR32_Using_CC_GPR: 8830 case RISCV::Select_FPR64_Using_CC_GPR: 8831 return emitSelectPseudo(MI, BB, Subtarget); 8832 case RISCV::BuildPairF64Pseudo: 8833 return emitBuildPairF64Pseudo(MI, BB); 8834 case RISCV::SplitF64Pseudo: 8835 return emitSplitF64Pseudo(MI, BB); 8836 case RISCV::PseudoQuietFLE_H: 8837 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 8838 case RISCV::PseudoQuietFLT_H: 8839 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 8840 case RISCV::PseudoQuietFLE_S: 8841 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 8842 case RISCV::PseudoQuietFLT_S: 8843 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 8844 case RISCV::PseudoQuietFLE_D: 8845 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 8846 case RISCV::PseudoQuietFLT_D: 8847 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 8848 } 8849 } 8850 8851 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8852 SDNode *Node) const { 8853 // Add FRM dependency to any instructions with dynamic rounding mode. 8854 unsigned Opc = MI.getOpcode(); 8855 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 8856 if (Idx < 0) 8857 return; 8858 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 8859 return; 8860 // If the instruction already reads FRM, don't add another read. 8861 if (MI.readsRegister(RISCV::FRM)) 8862 return; 8863 MI.addOperand( 8864 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 8865 } 8866 8867 // Calling Convention Implementation. 8868 // The expectations for frontend ABI lowering vary from target to target. 8869 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 8870 // details, but this is a longer term goal. For now, we simply try to keep the 8871 // role of the frontend as simple and well-defined as possible. The rules can 8872 // be summarised as: 8873 // * Never split up large scalar arguments. We handle them here. 8874 // * If a hardfloat calling convention is being used, and the struct may be 8875 // passed in a pair of registers (fp+fp, int+fp), and both registers are 8876 // available, then pass as two separate arguments. If either the GPRs or FPRs 8877 // are exhausted, then pass according to the rule below. 8878 // * If a struct could never be passed in registers or directly in a stack 8879 // slot (as it is larger than 2*XLEN and the floating point rules don't 8880 // apply), then pass it using a pointer with the byval attribute. 8881 // * If a struct is less than 2*XLEN, then coerce to either a two-element 8882 // word-sized array or a 2*XLEN scalar (depending on alignment). 8883 // * The frontend can determine whether a struct is returned by reference or 8884 // not based on its size and fields. If it will be returned by reference, the 8885 // frontend must modify the prototype so a pointer with the sret annotation is 8886 // passed as the first argument. This is not necessary for large scalar 8887 // returns. 8888 // * Struct return values and varargs should be coerced to structs containing 8889 // register-size fields in the same situations they would be for fixed 8890 // arguments. 8891 8892 static const MCPhysReg ArgGPRs[] = { 8893 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 8894 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 8895 }; 8896 static const MCPhysReg ArgFPR16s[] = { 8897 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 8898 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 8899 }; 8900 static const MCPhysReg ArgFPR32s[] = { 8901 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 8902 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 8903 }; 8904 static const MCPhysReg ArgFPR64s[] = { 8905 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 8906 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 8907 }; 8908 // This is an interim calling convention and it may be changed in the future. 8909 static const MCPhysReg ArgVRs[] = { 8910 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 8911 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 8912 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 8913 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 8914 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 8915 RISCV::V20M2, RISCV::V22M2}; 8916 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 8917 RISCV::V20M4}; 8918 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 8919 8920 // Pass a 2*XLEN argument that has been split into two XLEN values through 8921 // registers or the stack as necessary. 8922 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 8923 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 8924 MVT ValVT2, MVT LocVT2, 8925 ISD::ArgFlagsTy ArgFlags2) { 8926 unsigned XLenInBytes = XLen / 8; 8927 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8928 // At least one half can be passed via register. 8929 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 8930 VA1.getLocVT(), CCValAssign::Full)); 8931 } else { 8932 // Both halves must be passed on the stack, with proper alignment. 8933 Align StackAlign = 8934 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 8935 State.addLoc( 8936 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 8937 State.AllocateStack(XLenInBytes, StackAlign), 8938 VA1.getLocVT(), CCValAssign::Full)); 8939 State.addLoc(CCValAssign::getMem( 8940 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8941 LocVT2, CCValAssign::Full)); 8942 return false; 8943 } 8944 8945 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8946 // The second half can also be passed via register. 8947 State.addLoc( 8948 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 8949 } else { 8950 // The second half is passed via the stack, without additional alignment. 8951 State.addLoc(CCValAssign::getMem( 8952 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8953 LocVT2, CCValAssign::Full)); 8954 } 8955 8956 return false; 8957 } 8958 8959 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8960 Optional<unsigned> FirstMaskArgument, 8961 CCState &State, const RISCVTargetLowering &TLI) { 8962 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8963 if (RC == &RISCV::VRRegClass) { 8964 // Assign the first mask argument to V0. 8965 // This is an interim calling convention and it may be changed in the 8966 // future. 8967 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8968 return State.AllocateReg(RISCV::V0); 8969 return State.AllocateReg(ArgVRs); 8970 } 8971 if (RC == &RISCV::VRM2RegClass) 8972 return State.AllocateReg(ArgVRM2s); 8973 if (RC == &RISCV::VRM4RegClass) 8974 return State.AllocateReg(ArgVRM4s); 8975 if (RC == &RISCV::VRM8RegClass) 8976 return State.AllocateReg(ArgVRM8s); 8977 llvm_unreachable("Unhandled register class for ValueType"); 8978 } 8979 8980 // Implements the RISC-V calling convention. Returns true upon failure. 8981 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8982 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8983 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8984 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8985 Optional<unsigned> FirstMaskArgument) { 8986 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8987 assert(XLen == 32 || XLen == 64); 8988 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8989 8990 // Any return value split in to more than two values can't be returned 8991 // directly. Vectors are returned via the available vector registers. 8992 if (!LocVT.isVector() && IsRet && ValNo > 1) 8993 return true; 8994 8995 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8996 // variadic argument, or if no F16/F32 argument registers are available. 8997 bool UseGPRForF16_F32 = true; 8998 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8999 // variadic argument, or if no F64 argument registers are available. 9000 bool UseGPRForF64 = true; 9001 9002 switch (ABI) { 9003 default: 9004 llvm_unreachable("Unexpected ABI"); 9005 case RISCVABI::ABI_ILP32: 9006 case RISCVABI::ABI_LP64: 9007 break; 9008 case RISCVABI::ABI_ILP32F: 9009 case RISCVABI::ABI_LP64F: 9010 UseGPRForF16_F32 = !IsFixed; 9011 break; 9012 case RISCVABI::ABI_ILP32D: 9013 case RISCVABI::ABI_LP64D: 9014 UseGPRForF16_F32 = !IsFixed; 9015 UseGPRForF64 = !IsFixed; 9016 break; 9017 } 9018 9019 // FPR16, FPR32, and FPR64 alias each other. 9020 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9021 UseGPRForF16_F32 = true; 9022 UseGPRForF64 = true; 9023 } 9024 9025 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9026 // similar local variables rather than directly checking against the target 9027 // ABI. 9028 9029 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9030 LocVT = XLenVT; 9031 LocInfo = CCValAssign::BCvt; 9032 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9033 LocVT = MVT::i64; 9034 LocInfo = CCValAssign::BCvt; 9035 } 9036 9037 // If this is a variadic argument, the RISC-V calling convention requires 9038 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9039 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9040 // be used regardless of whether the original argument was split during 9041 // legalisation or not. The argument will not be passed by registers if the 9042 // original type is larger than 2*XLEN, so the register alignment rule does 9043 // not apply. 9044 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9045 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9046 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9047 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9048 // Skip 'odd' register if necessary. 9049 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9050 State.AllocateReg(ArgGPRs); 9051 } 9052 9053 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9054 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9055 State.getPendingArgFlags(); 9056 9057 assert(PendingLocs.size() == PendingArgFlags.size() && 9058 "PendingLocs and PendingArgFlags out of sync"); 9059 9060 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9061 // registers are exhausted. 9062 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9063 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9064 "Can't lower f64 if it is split"); 9065 // Depending on available argument GPRS, f64 may be passed in a pair of 9066 // GPRs, split between a GPR and the stack, or passed completely on the 9067 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9068 // cases. 9069 Register Reg = State.AllocateReg(ArgGPRs); 9070 LocVT = MVT::i32; 9071 if (!Reg) { 9072 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9073 State.addLoc( 9074 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9075 return false; 9076 } 9077 if (!State.AllocateReg(ArgGPRs)) 9078 State.AllocateStack(4, Align(4)); 9079 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9080 return false; 9081 } 9082 9083 // Fixed-length vectors are located in the corresponding scalable-vector 9084 // container types. 9085 if (ValVT.isFixedLengthVector()) 9086 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9087 9088 // Split arguments might be passed indirectly, so keep track of the pending 9089 // values. Split vectors are passed via a mix of registers and indirectly, so 9090 // treat them as we would any other argument. 9091 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9092 LocVT = XLenVT; 9093 LocInfo = CCValAssign::Indirect; 9094 PendingLocs.push_back( 9095 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9096 PendingArgFlags.push_back(ArgFlags); 9097 if (!ArgFlags.isSplitEnd()) { 9098 return false; 9099 } 9100 } 9101 9102 // If the split argument only had two elements, it should be passed directly 9103 // in registers or on the stack. 9104 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9105 PendingLocs.size() <= 2) { 9106 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9107 // Apply the normal calling convention rules to the first half of the 9108 // split argument. 9109 CCValAssign VA = PendingLocs[0]; 9110 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9111 PendingLocs.clear(); 9112 PendingArgFlags.clear(); 9113 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9114 ArgFlags); 9115 } 9116 9117 // Allocate to a register if possible, or else a stack slot. 9118 Register Reg; 9119 unsigned StoreSizeBytes = XLen / 8; 9120 Align StackAlign = Align(XLen / 8); 9121 9122 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9123 Reg = State.AllocateReg(ArgFPR16s); 9124 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9125 Reg = State.AllocateReg(ArgFPR32s); 9126 else if (ValVT == MVT::f64 && !UseGPRForF64) 9127 Reg = State.AllocateReg(ArgFPR64s); 9128 else if (ValVT.isVector()) { 9129 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9130 if (!Reg) { 9131 // For return values, the vector must be passed fully via registers or 9132 // via the stack. 9133 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9134 // but we're using all of them. 9135 if (IsRet) 9136 return true; 9137 // Try using a GPR to pass the address 9138 if ((Reg = State.AllocateReg(ArgGPRs))) { 9139 LocVT = XLenVT; 9140 LocInfo = CCValAssign::Indirect; 9141 } else if (ValVT.isScalableVector()) { 9142 LocVT = XLenVT; 9143 LocInfo = CCValAssign::Indirect; 9144 } else { 9145 // Pass fixed-length vectors on the stack. 9146 LocVT = ValVT; 9147 StoreSizeBytes = ValVT.getStoreSize(); 9148 // Align vectors to their element sizes, being careful for vXi1 9149 // vectors. 9150 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9151 } 9152 } 9153 } else { 9154 Reg = State.AllocateReg(ArgGPRs); 9155 } 9156 9157 unsigned StackOffset = 9158 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9159 9160 // If we reach this point and PendingLocs is non-empty, we must be at the 9161 // end of a split argument that must be passed indirectly. 9162 if (!PendingLocs.empty()) { 9163 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9164 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9165 9166 for (auto &It : PendingLocs) { 9167 if (Reg) 9168 It.convertToReg(Reg); 9169 else 9170 It.convertToMem(StackOffset); 9171 State.addLoc(It); 9172 } 9173 PendingLocs.clear(); 9174 PendingArgFlags.clear(); 9175 return false; 9176 } 9177 9178 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9179 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9180 "Expected an XLenVT or vector types at this stage"); 9181 9182 if (Reg) { 9183 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9184 return false; 9185 } 9186 9187 // When a floating-point value is passed on the stack, no bit-conversion is 9188 // needed. 9189 if (ValVT.isFloatingPoint()) { 9190 LocVT = ValVT; 9191 LocInfo = CCValAssign::Full; 9192 } 9193 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9194 return false; 9195 } 9196 9197 template <typename ArgTy> 9198 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9199 for (const auto &ArgIdx : enumerate(Args)) { 9200 MVT ArgVT = ArgIdx.value().VT; 9201 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9202 return ArgIdx.index(); 9203 } 9204 return None; 9205 } 9206 9207 void RISCVTargetLowering::analyzeInputArgs( 9208 MachineFunction &MF, CCState &CCInfo, 9209 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9210 RISCVCCAssignFn Fn) const { 9211 unsigned NumArgs = Ins.size(); 9212 FunctionType *FType = MF.getFunction().getFunctionType(); 9213 9214 Optional<unsigned> FirstMaskArgument; 9215 if (Subtarget.hasVInstructions()) 9216 FirstMaskArgument = preAssignMask(Ins); 9217 9218 for (unsigned i = 0; i != NumArgs; ++i) { 9219 MVT ArgVT = Ins[i].VT; 9220 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9221 9222 Type *ArgTy = nullptr; 9223 if (IsRet) 9224 ArgTy = FType->getReturnType(); 9225 else if (Ins[i].isOrigArg()) 9226 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9227 9228 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9229 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9230 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9231 FirstMaskArgument)) { 9232 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9233 << EVT(ArgVT).getEVTString() << '\n'); 9234 llvm_unreachable(nullptr); 9235 } 9236 } 9237 } 9238 9239 void RISCVTargetLowering::analyzeOutputArgs( 9240 MachineFunction &MF, CCState &CCInfo, 9241 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9242 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9243 unsigned NumArgs = Outs.size(); 9244 9245 Optional<unsigned> FirstMaskArgument; 9246 if (Subtarget.hasVInstructions()) 9247 FirstMaskArgument = preAssignMask(Outs); 9248 9249 for (unsigned i = 0; i != NumArgs; i++) { 9250 MVT ArgVT = Outs[i].VT; 9251 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9252 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9253 9254 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9255 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9256 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9257 FirstMaskArgument)) { 9258 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9259 << EVT(ArgVT).getEVTString() << "\n"); 9260 llvm_unreachable(nullptr); 9261 } 9262 } 9263 } 9264 9265 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9266 // values. 9267 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9268 const CCValAssign &VA, const SDLoc &DL, 9269 const RISCVSubtarget &Subtarget) { 9270 switch (VA.getLocInfo()) { 9271 default: 9272 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9273 case CCValAssign::Full: 9274 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9275 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9276 break; 9277 case CCValAssign::BCvt: 9278 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9279 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9280 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9281 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9282 else 9283 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9284 break; 9285 } 9286 return Val; 9287 } 9288 9289 // The caller is responsible for loading the full value if the argument is 9290 // passed with CCValAssign::Indirect. 9291 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9292 const CCValAssign &VA, const SDLoc &DL, 9293 const RISCVTargetLowering &TLI) { 9294 MachineFunction &MF = DAG.getMachineFunction(); 9295 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9296 EVT LocVT = VA.getLocVT(); 9297 SDValue Val; 9298 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9299 Register VReg = RegInfo.createVirtualRegister(RC); 9300 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9301 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9302 9303 if (VA.getLocInfo() == CCValAssign::Indirect) 9304 return Val; 9305 9306 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9307 } 9308 9309 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9310 const CCValAssign &VA, const SDLoc &DL, 9311 const RISCVSubtarget &Subtarget) { 9312 EVT LocVT = VA.getLocVT(); 9313 9314 switch (VA.getLocInfo()) { 9315 default: 9316 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9317 case CCValAssign::Full: 9318 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9319 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9320 break; 9321 case CCValAssign::BCvt: 9322 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9323 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9324 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9325 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9326 else 9327 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9328 break; 9329 } 9330 return Val; 9331 } 9332 9333 // The caller is responsible for loading the full value if the argument is 9334 // passed with CCValAssign::Indirect. 9335 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9336 const CCValAssign &VA, const SDLoc &DL) { 9337 MachineFunction &MF = DAG.getMachineFunction(); 9338 MachineFrameInfo &MFI = MF.getFrameInfo(); 9339 EVT LocVT = VA.getLocVT(); 9340 EVT ValVT = VA.getValVT(); 9341 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9342 if (ValVT.isScalableVector()) { 9343 // When the value is a scalable vector, we save the pointer which points to 9344 // the scalable vector value in the stack. The ValVT will be the pointer 9345 // type, instead of the scalable vector type. 9346 ValVT = LocVT; 9347 } 9348 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9349 /*IsImmutable=*/true); 9350 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9351 SDValue Val; 9352 9353 ISD::LoadExtType ExtType; 9354 switch (VA.getLocInfo()) { 9355 default: 9356 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9357 case CCValAssign::Full: 9358 case CCValAssign::Indirect: 9359 case CCValAssign::BCvt: 9360 ExtType = ISD::NON_EXTLOAD; 9361 break; 9362 } 9363 Val = DAG.getExtLoad( 9364 ExtType, DL, LocVT, Chain, FIN, 9365 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9366 return Val; 9367 } 9368 9369 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9370 const CCValAssign &VA, const SDLoc &DL) { 9371 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9372 "Unexpected VA"); 9373 MachineFunction &MF = DAG.getMachineFunction(); 9374 MachineFrameInfo &MFI = MF.getFrameInfo(); 9375 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9376 9377 if (VA.isMemLoc()) { 9378 // f64 is passed on the stack. 9379 int FI = 9380 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9381 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9382 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9383 MachinePointerInfo::getFixedStack(MF, FI)); 9384 } 9385 9386 assert(VA.isRegLoc() && "Expected register VA assignment"); 9387 9388 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9389 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9390 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9391 SDValue Hi; 9392 if (VA.getLocReg() == RISCV::X17) { 9393 // Second half of f64 is passed on the stack. 9394 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9395 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9396 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9397 MachinePointerInfo::getFixedStack(MF, FI)); 9398 } else { 9399 // Second half of f64 is passed in another GPR. 9400 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9401 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9402 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9403 } 9404 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9405 } 9406 9407 // FastCC has less than 1% performance improvement for some particular 9408 // benchmark. But theoretically, it may has benenfit for some cases. 9409 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9410 unsigned ValNo, MVT ValVT, MVT LocVT, 9411 CCValAssign::LocInfo LocInfo, 9412 ISD::ArgFlagsTy ArgFlags, CCState &State, 9413 bool IsFixed, bool IsRet, Type *OrigTy, 9414 const RISCVTargetLowering &TLI, 9415 Optional<unsigned> FirstMaskArgument) { 9416 9417 // X5 and X6 might be used for save-restore libcall. 9418 static const MCPhysReg GPRList[] = { 9419 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9420 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9421 RISCV::X29, RISCV::X30, RISCV::X31}; 9422 9423 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9424 if (unsigned Reg = State.AllocateReg(GPRList)) { 9425 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9426 return false; 9427 } 9428 } 9429 9430 if (LocVT == MVT::f16) { 9431 static const MCPhysReg FPR16List[] = { 9432 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9433 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9434 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9435 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9436 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9437 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9438 return false; 9439 } 9440 } 9441 9442 if (LocVT == MVT::f32) { 9443 static const MCPhysReg FPR32List[] = { 9444 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9445 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9446 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9447 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9448 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9449 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9450 return false; 9451 } 9452 } 9453 9454 if (LocVT == MVT::f64) { 9455 static const MCPhysReg FPR64List[] = { 9456 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9457 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9458 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9459 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9460 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9461 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9462 return false; 9463 } 9464 } 9465 9466 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9467 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9468 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9469 return false; 9470 } 9471 9472 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9473 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9474 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9475 return false; 9476 } 9477 9478 if (LocVT.isVector()) { 9479 if (unsigned Reg = 9480 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9481 // Fixed-length vectors are located in the corresponding scalable-vector 9482 // container types. 9483 if (ValVT.isFixedLengthVector()) 9484 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9485 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9486 } else { 9487 // Try and pass the address via a "fast" GPR. 9488 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9489 LocInfo = CCValAssign::Indirect; 9490 LocVT = TLI.getSubtarget().getXLenVT(); 9491 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9492 } else if (ValVT.isFixedLengthVector()) { 9493 auto StackAlign = 9494 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9495 unsigned StackOffset = 9496 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9497 State.addLoc( 9498 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9499 } else { 9500 // Can't pass scalable vectors on the stack. 9501 return true; 9502 } 9503 } 9504 9505 return false; 9506 } 9507 9508 return true; // CC didn't match. 9509 } 9510 9511 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9512 CCValAssign::LocInfo LocInfo, 9513 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9514 9515 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9516 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9517 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9518 static const MCPhysReg GPRList[] = { 9519 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9520 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9521 if (unsigned Reg = State.AllocateReg(GPRList)) { 9522 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9523 return false; 9524 } 9525 } 9526 9527 if (LocVT == MVT::f32) { 9528 // Pass in STG registers: F1, ..., F6 9529 // fs0 ... fs5 9530 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9531 RISCV::F18_F, RISCV::F19_F, 9532 RISCV::F20_F, RISCV::F21_F}; 9533 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9534 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9535 return false; 9536 } 9537 } 9538 9539 if (LocVT == MVT::f64) { 9540 // Pass in STG registers: D1, ..., D6 9541 // fs6 ... fs11 9542 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9543 RISCV::F24_D, RISCV::F25_D, 9544 RISCV::F26_D, RISCV::F27_D}; 9545 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9546 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9547 return false; 9548 } 9549 } 9550 9551 report_fatal_error("No registers left in GHC calling convention"); 9552 return true; 9553 } 9554 9555 // Transform physical registers into virtual registers. 9556 SDValue RISCVTargetLowering::LowerFormalArguments( 9557 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9558 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9559 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9560 9561 MachineFunction &MF = DAG.getMachineFunction(); 9562 9563 switch (CallConv) { 9564 default: 9565 report_fatal_error("Unsupported calling convention"); 9566 case CallingConv::C: 9567 case CallingConv::Fast: 9568 break; 9569 case CallingConv::GHC: 9570 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9571 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9572 report_fatal_error( 9573 "GHC calling convention requires the F and D instruction set extensions"); 9574 } 9575 9576 const Function &Func = MF.getFunction(); 9577 if (Func.hasFnAttribute("interrupt")) { 9578 if (!Func.arg_empty()) 9579 report_fatal_error( 9580 "Functions with the interrupt attribute cannot have arguments!"); 9581 9582 StringRef Kind = 9583 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9584 9585 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9586 report_fatal_error( 9587 "Function interrupt attribute argument not supported!"); 9588 } 9589 9590 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9591 MVT XLenVT = Subtarget.getXLenVT(); 9592 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9593 // Used with vargs to acumulate store chains. 9594 std::vector<SDValue> OutChains; 9595 9596 // Assign locations to all of the incoming arguments. 9597 SmallVector<CCValAssign, 16> ArgLocs; 9598 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9599 9600 if (CallConv == CallingConv::GHC) 9601 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9602 else 9603 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9604 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9605 : CC_RISCV); 9606 9607 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9608 CCValAssign &VA = ArgLocs[i]; 9609 SDValue ArgValue; 9610 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9611 // case. 9612 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9613 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9614 else if (VA.isRegLoc()) 9615 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9616 else 9617 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9618 9619 if (VA.getLocInfo() == CCValAssign::Indirect) { 9620 // If the original argument was split and passed by reference (e.g. i128 9621 // on RV32), we need to load all parts of it here (using the same 9622 // address). Vectors may be partly split to registers and partly to the 9623 // stack, in which case the base address is partly offset and subsequent 9624 // stores are relative to that. 9625 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9626 MachinePointerInfo())); 9627 unsigned ArgIndex = Ins[i].OrigArgIndex; 9628 unsigned ArgPartOffset = Ins[i].PartOffset; 9629 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9630 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9631 CCValAssign &PartVA = ArgLocs[i + 1]; 9632 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9633 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9634 if (PartVA.getValVT().isScalableVector()) 9635 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9636 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9637 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9638 MachinePointerInfo())); 9639 ++i; 9640 } 9641 continue; 9642 } 9643 InVals.push_back(ArgValue); 9644 } 9645 9646 if (IsVarArg) { 9647 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9648 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9649 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9650 MachineFrameInfo &MFI = MF.getFrameInfo(); 9651 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9652 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9653 9654 // Offset of the first variable argument from stack pointer, and size of 9655 // the vararg save area. For now, the varargs save area is either zero or 9656 // large enough to hold a0-a7. 9657 int VaArgOffset, VarArgsSaveSize; 9658 9659 // If all registers are allocated, then all varargs must be passed on the 9660 // stack and we don't need to save any argregs. 9661 if (ArgRegs.size() == Idx) { 9662 VaArgOffset = CCInfo.getNextStackOffset(); 9663 VarArgsSaveSize = 0; 9664 } else { 9665 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9666 VaArgOffset = -VarArgsSaveSize; 9667 } 9668 9669 // Record the frame index of the first variable argument 9670 // which is a value necessary to VASTART. 9671 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9672 RVFI->setVarArgsFrameIndex(FI); 9673 9674 // If saving an odd number of registers then create an extra stack slot to 9675 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9676 // offsets to even-numbered registered remain 2*XLEN-aligned. 9677 if (Idx % 2) { 9678 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 9679 VarArgsSaveSize += XLenInBytes; 9680 } 9681 9682 // Copy the integer registers that may have been used for passing varargs 9683 // to the vararg save area. 9684 for (unsigned I = Idx; I < ArgRegs.size(); 9685 ++I, VaArgOffset += XLenInBytes) { 9686 const Register Reg = RegInfo.createVirtualRegister(RC); 9687 RegInfo.addLiveIn(ArgRegs[I], Reg); 9688 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 9689 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9690 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9691 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 9692 MachinePointerInfo::getFixedStack(MF, FI)); 9693 cast<StoreSDNode>(Store.getNode()) 9694 ->getMemOperand() 9695 ->setValue((Value *)nullptr); 9696 OutChains.push_back(Store); 9697 } 9698 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 9699 } 9700 9701 // All stores are grouped in one node to allow the matching between 9702 // the size of Ins and InVals. This only happens for vararg functions. 9703 if (!OutChains.empty()) { 9704 OutChains.push_back(Chain); 9705 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 9706 } 9707 9708 return Chain; 9709 } 9710 9711 /// isEligibleForTailCallOptimization - Check whether the call is eligible 9712 /// for tail call optimization. 9713 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 9714 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 9715 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 9716 const SmallVector<CCValAssign, 16> &ArgLocs) const { 9717 9718 auto &Callee = CLI.Callee; 9719 auto CalleeCC = CLI.CallConv; 9720 auto &Outs = CLI.Outs; 9721 auto &Caller = MF.getFunction(); 9722 auto CallerCC = Caller.getCallingConv(); 9723 9724 // Exception-handling functions need a special set of instructions to 9725 // indicate a return to the hardware. Tail-calling another function would 9726 // probably break this. 9727 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 9728 // should be expanded as new function attributes are introduced. 9729 if (Caller.hasFnAttribute("interrupt")) 9730 return false; 9731 9732 // Do not tail call opt if the stack is used to pass parameters. 9733 if (CCInfo.getNextStackOffset() != 0) 9734 return false; 9735 9736 // Do not tail call opt if any parameters need to be passed indirectly. 9737 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 9738 // passed indirectly. So the address of the value will be passed in a 9739 // register, or if not available, then the address is put on the stack. In 9740 // order to pass indirectly, space on the stack often needs to be allocated 9741 // in order to store the value. In this case the CCInfo.getNextStackOffset() 9742 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 9743 // are passed CCValAssign::Indirect. 9744 for (auto &VA : ArgLocs) 9745 if (VA.getLocInfo() == CCValAssign::Indirect) 9746 return false; 9747 9748 // Do not tail call opt if either caller or callee uses struct return 9749 // semantics. 9750 auto IsCallerStructRet = Caller.hasStructRetAttr(); 9751 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 9752 if (IsCallerStructRet || IsCalleeStructRet) 9753 return false; 9754 9755 // Externally-defined functions with weak linkage should not be 9756 // tail-called. The behaviour of branch instructions in this situation (as 9757 // used for tail calls) is implementation-defined, so we cannot rely on the 9758 // linker replacing the tail call with a return. 9759 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 9760 const GlobalValue *GV = G->getGlobal(); 9761 if (GV->hasExternalWeakLinkage()) 9762 return false; 9763 } 9764 9765 // The callee has to preserve all registers the caller needs to preserve. 9766 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9767 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 9768 if (CalleeCC != CallerCC) { 9769 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 9770 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 9771 return false; 9772 } 9773 9774 // Byval parameters hand the function a pointer directly into the stack area 9775 // we want to reuse during a tail call. Working around this *is* possible 9776 // but less efficient and uglier in LowerCall. 9777 for (auto &Arg : Outs) 9778 if (Arg.Flags.isByVal()) 9779 return false; 9780 9781 return true; 9782 } 9783 9784 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 9785 return DAG.getDataLayout().getPrefTypeAlign( 9786 VT.getTypeForEVT(*DAG.getContext())); 9787 } 9788 9789 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 9790 // and output parameter nodes. 9791 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 9792 SmallVectorImpl<SDValue> &InVals) const { 9793 SelectionDAG &DAG = CLI.DAG; 9794 SDLoc &DL = CLI.DL; 9795 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 9796 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 9797 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 9798 SDValue Chain = CLI.Chain; 9799 SDValue Callee = CLI.Callee; 9800 bool &IsTailCall = CLI.IsTailCall; 9801 CallingConv::ID CallConv = CLI.CallConv; 9802 bool IsVarArg = CLI.IsVarArg; 9803 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9804 MVT XLenVT = Subtarget.getXLenVT(); 9805 9806 MachineFunction &MF = DAG.getMachineFunction(); 9807 9808 // Analyze the operands of the call, assigning locations to each operand. 9809 SmallVector<CCValAssign, 16> ArgLocs; 9810 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9811 9812 if (CallConv == CallingConv::GHC) 9813 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 9814 else 9815 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 9816 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9817 : CC_RISCV); 9818 9819 // Check if it's really possible to do a tail call. 9820 if (IsTailCall) 9821 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 9822 9823 if (IsTailCall) 9824 ++NumTailCalls; 9825 else if (CLI.CB && CLI.CB->isMustTailCall()) 9826 report_fatal_error("failed to perform tail call elimination on a call " 9827 "site marked musttail"); 9828 9829 // Get a count of how many bytes are to be pushed on the stack. 9830 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 9831 9832 // Create local copies for byval args 9833 SmallVector<SDValue, 8> ByValArgs; 9834 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9835 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9836 if (!Flags.isByVal()) 9837 continue; 9838 9839 SDValue Arg = OutVals[i]; 9840 unsigned Size = Flags.getByValSize(); 9841 Align Alignment = Flags.getNonZeroByValAlign(); 9842 9843 int FI = 9844 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 9845 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9846 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 9847 9848 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 9849 /*IsVolatile=*/false, 9850 /*AlwaysInline=*/false, IsTailCall, 9851 MachinePointerInfo(), MachinePointerInfo()); 9852 ByValArgs.push_back(FIPtr); 9853 } 9854 9855 if (!IsTailCall) 9856 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 9857 9858 // Copy argument values to their designated locations. 9859 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 9860 SmallVector<SDValue, 8> MemOpChains; 9861 SDValue StackPtr; 9862 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 9863 CCValAssign &VA = ArgLocs[i]; 9864 SDValue ArgValue = OutVals[i]; 9865 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9866 9867 // Handle passing f64 on RV32D with a soft float ABI as a special case. 9868 bool IsF64OnRV32DSoftABI = 9869 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 9870 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 9871 SDValue SplitF64 = DAG.getNode( 9872 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 9873 SDValue Lo = SplitF64.getValue(0); 9874 SDValue Hi = SplitF64.getValue(1); 9875 9876 Register RegLo = VA.getLocReg(); 9877 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 9878 9879 if (RegLo == RISCV::X17) { 9880 // Second half of f64 is passed on the stack. 9881 // Work out the address of the stack slot. 9882 if (!StackPtr.getNode()) 9883 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9884 // Emit the store. 9885 MemOpChains.push_back( 9886 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 9887 } else { 9888 // Second half of f64 is passed in another GPR. 9889 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9890 Register RegHigh = RegLo + 1; 9891 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 9892 } 9893 continue; 9894 } 9895 9896 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 9897 // as any other MemLoc. 9898 9899 // Promote the value if needed. 9900 // For now, only handle fully promoted and indirect arguments. 9901 if (VA.getLocInfo() == CCValAssign::Indirect) { 9902 // Store the argument in a stack slot and pass its address. 9903 Align StackAlign = 9904 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 9905 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 9906 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 9907 // If the original argument was split (e.g. i128), we need 9908 // to store the required parts of it here (and pass just one address). 9909 // Vectors may be partly split to registers and partly to the stack, in 9910 // which case the base address is partly offset and subsequent stores are 9911 // relative to that. 9912 unsigned ArgIndex = Outs[i].OrigArgIndex; 9913 unsigned ArgPartOffset = Outs[i].PartOffset; 9914 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9915 // Calculate the total size to store. We don't have access to what we're 9916 // actually storing other than performing the loop and collecting the 9917 // info. 9918 SmallVector<std::pair<SDValue, SDValue>> Parts; 9919 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 9920 SDValue PartValue = OutVals[i + 1]; 9921 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 9922 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9923 EVT PartVT = PartValue.getValueType(); 9924 if (PartVT.isScalableVector()) 9925 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9926 StoredSize += PartVT.getStoreSize(); 9927 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 9928 Parts.push_back(std::make_pair(PartValue, Offset)); 9929 ++i; 9930 } 9931 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 9932 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 9933 MemOpChains.push_back( 9934 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 9935 MachinePointerInfo::getFixedStack(MF, FI))); 9936 for (const auto &Part : Parts) { 9937 SDValue PartValue = Part.first; 9938 SDValue PartOffset = Part.second; 9939 SDValue Address = 9940 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 9941 MemOpChains.push_back( 9942 DAG.getStore(Chain, DL, PartValue, Address, 9943 MachinePointerInfo::getFixedStack(MF, FI))); 9944 } 9945 ArgValue = SpillSlot; 9946 } else { 9947 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 9948 } 9949 9950 // Use local copy if it is a byval arg. 9951 if (Flags.isByVal()) 9952 ArgValue = ByValArgs[j++]; 9953 9954 if (VA.isRegLoc()) { 9955 // Queue up the argument copies and emit them at the end. 9956 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 9957 } else { 9958 assert(VA.isMemLoc() && "Argument not register or memory"); 9959 assert(!IsTailCall && "Tail call not allowed if stack is used " 9960 "for passing parameters"); 9961 9962 // Work out the address of the stack slot. 9963 if (!StackPtr.getNode()) 9964 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9965 SDValue Address = 9966 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9967 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9968 9969 // Emit the store. 9970 MemOpChains.push_back( 9971 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9972 } 9973 } 9974 9975 // Join the stores, which are independent of one another. 9976 if (!MemOpChains.empty()) 9977 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9978 9979 SDValue Glue; 9980 9981 // Build a sequence of copy-to-reg nodes, chained and glued together. 9982 for (auto &Reg : RegsToPass) { 9983 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9984 Glue = Chain.getValue(1); 9985 } 9986 9987 // Validate that none of the argument registers have been marked as 9988 // reserved, if so report an error. Do the same for the return address if this 9989 // is not a tailcall. 9990 validateCCReservedRegs(RegsToPass, MF); 9991 if (!IsTailCall && 9992 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9993 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9994 MF.getFunction(), 9995 "Return address register required, but has been reserved."}); 9996 9997 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9998 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9999 // split it and then direct call can be matched by PseudoCALL. 10000 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10001 const GlobalValue *GV = S->getGlobal(); 10002 10003 unsigned OpFlags = RISCVII::MO_CALL; 10004 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10005 OpFlags = RISCVII::MO_PLT; 10006 10007 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10008 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10009 unsigned OpFlags = RISCVII::MO_CALL; 10010 10011 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10012 nullptr)) 10013 OpFlags = RISCVII::MO_PLT; 10014 10015 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10016 } 10017 10018 // The first call operand is the chain and the second is the target address. 10019 SmallVector<SDValue, 8> Ops; 10020 Ops.push_back(Chain); 10021 Ops.push_back(Callee); 10022 10023 // Add argument registers to the end of the list so that they are 10024 // known live into the call. 10025 for (auto &Reg : RegsToPass) 10026 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10027 10028 if (!IsTailCall) { 10029 // Add a register mask operand representing the call-preserved registers. 10030 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10031 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10032 assert(Mask && "Missing call preserved mask for calling convention"); 10033 Ops.push_back(DAG.getRegisterMask(Mask)); 10034 } 10035 10036 // Glue the call to the argument copies, if any. 10037 if (Glue.getNode()) 10038 Ops.push_back(Glue); 10039 10040 // Emit the call. 10041 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10042 10043 if (IsTailCall) { 10044 MF.getFrameInfo().setHasTailCall(); 10045 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10046 } 10047 10048 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10049 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10050 Glue = Chain.getValue(1); 10051 10052 // Mark the end of the call, which is glued to the call itself. 10053 Chain = DAG.getCALLSEQ_END(Chain, 10054 DAG.getConstant(NumBytes, DL, PtrVT, true), 10055 DAG.getConstant(0, DL, PtrVT, true), 10056 Glue, DL); 10057 Glue = Chain.getValue(1); 10058 10059 // Assign locations to each value returned by this call. 10060 SmallVector<CCValAssign, 16> RVLocs; 10061 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10062 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10063 10064 // Copy all of the result registers out of their specified physreg. 10065 for (auto &VA : RVLocs) { 10066 // Copy the value out 10067 SDValue RetValue = 10068 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10069 // Glue the RetValue to the end of the call sequence 10070 Chain = RetValue.getValue(1); 10071 Glue = RetValue.getValue(2); 10072 10073 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10074 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10075 SDValue RetValue2 = 10076 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10077 Chain = RetValue2.getValue(1); 10078 Glue = RetValue2.getValue(2); 10079 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10080 RetValue2); 10081 } 10082 10083 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10084 10085 InVals.push_back(RetValue); 10086 } 10087 10088 return Chain; 10089 } 10090 10091 bool RISCVTargetLowering::CanLowerReturn( 10092 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10093 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10094 SmallVector<CCValAssign, 16> RVLocs; 10095 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10096 10097 Optional<unsigned> FirstMaskArgument; 10098 if (Subtarget.hasVInstructions()) 10099 FirstMaskArgument = preAssignMask(Outs); 10100 10101 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10102 MVT VT = Outs[i].VT; 10103 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10104 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10105 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10106 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10107 *this, FirstMaskArgument)) 10108 return false; 10109 } 10110 return true; 10111 } 10112 10113 SDValue 10114 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10115 bool IsVarArg, 10116 const SmallVectorImpl<ISD::OutputArg> &Outs, 10117 const SmallVectorImpl<SDValue> &OutVals, 10118 const SDLoc &DL, SelectionDAG &DAG) const { 10119 const MachineFunction &MF = DAG.getMachineFunction(); 10120 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10121 10122 // Stores the assignment of the return value to a location. 10123 SmallVector<CCValAssign, 16> RVLocs; 10124 10125 // Info about the registers and stack slot. 10126 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10127 *DAG.getContext()); 10128 10129 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10130 nullptr, CC_RISCV); 10131 10132 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10133 report_fatal_error("GHC functions return void only"); 10134 10135 SDValue Glue; 10136 SmallVector<SDValue, 4> RetOps(1, Chain); 10137 10138 // Copy the result values into the output registers. 10139 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10140 SDValue Val = OutVals[i]; 10141 CCValAssign &VA = RVLocs[i]; 10142 assert(VA.isRegLoc() && "Can only return in registers!"); 10143 10144 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10145 // Handle returning f64 on RV32D with a soft float ABI. 10146 assert(VA.isRegLoc() && "Expected return via registers"); 10147 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10148 DAG.getVTList(MVT::i32, MVT::i32), Val); 10149 SDValue Lo = SplitF64.getValue(0); 10150 SDValue Hi = SplitF64.getValue(1); 10151 Register RegLo = VA.getLocReg(); 10152 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10153 Register RegHi = RegLo + 1; 10154 10155 if (STI.isRegisterReservedByUser(RegLo) || 10156 STI.isRegisterReservedByUser(RegHi)) 10157 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10158 MF.getFunction(), 10159 "Return value register required, but has been reserved."}); 10160 10161 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10162 Glue = Chain.getValue(1); 10163 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10164 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10165 Glue = Chain.getValue(1); 10166 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10167 } else { 10168 // Handle a 'normal' return. 10169 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10170 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10171 10172 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10173 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10174 MF.getFunction(), 10175 "Return value register required, but has been reserved."}); 10176 10177 // Guarantee that all emitted copies are stuck together. 10178 Glue = Chain.getValue(1); 10179 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10180 } 10181 } 10182 10183 RetOps[0] = Chain; // Update chain. 10184 10185 // Add the glue node if we have it. 10186 if (Glue.getNode()) { 10187 RetOps.push_back(Glue); 10188 } 10189 10190 unsigned RetOpc = RISCVISD::RET_FLAG; 10191 // Interrupt service routines use different return instructions. 10192 const Function &Func = DAG.getMachineFunction().getFunction(); 10193 if (Func.hasFnAttribute("interrupt")) { 10194 if (!Func.getReturnType()->isVoidTy()) 10195 report_fatal_error( 10196 "Functions with the interrupt attribute must have void return type!"); 10197 10198 MachineFunction &MF = DAG.getMachineFunction(); 10199 StringRef Kind = 10200 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10201 10202 if (Kind == "user") 10203 RetOpc = RISCVISD::URET_FLAG; 10204 else if (Kind == "supervisor") 10205 RetOpc = RISCVISD::SRET_FLAG; 10206 else 10207 RetOpc = RISCVISD::MRET_FLAG; 10208 } 10209 10210 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10211 } 10212 10213 void RISCVTargetLowering::validateCCReservedRegs( 10214 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10215 MachineFunction &MF) const { 10216 const Function &F = MF.getFunction(); 10217 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10218 10219 if (llvm::any_of(Regs, [&STI](auto Reg) { 10220 return STI.isRegisterReservedByUser(Reg.first); 10221 })) 10222 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10223 F, "Argument register required, but has been reserved."}); 10224 } 10225 10226 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10227 return CI->isTailCall(); 10228 } 10229 10230 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10231 #define NODE_NAME_CASE(NODE) \ 10232 case RISCVISD::NODE: \ 10233 return "RISCVISD::" #NODE; 10234 // clang-format off 10235 switch ((RISCVISD::NodeType)Opcode) { 10236 case RISCVISD::FIRST_NUMBER: 10237 break; 10238 NODE_NAME_CASE(RET_FLAG) 10239 NODE_NAME_CASE(URET_FLAG) 10240 NODE_NAME_CASE(SRET_FLAG) 10241 NODE_NAME_CASE(MRET_FLAG) 10242 NODE_NAME_CASE(CALL) 10243 NODE_NAME_CASE(SELECT_CC) 10244 NODE_NAME_CASE(BR_CC) 10245 NODE_NAME_CASE(BuildPairF64) 10246 NODE_NAME_CASE(SplitF64) 10247 NODE_NAME_CASE(TAIL) 10248 NODE_NAME_CASE(MULHSU) 10249 NODE_NAME_CASE(SLLW) 10250 NODE_NAME_CASE(SRAW) 10251 NODE_NAME_CASE(SRLW) 10252 NODE_NAME_CASE(DIVW) 10253 NODE_NAME_CASE(DIVUW) 10254 NODE_NAME_CASE(REMUW) 10255 NODE_NAME_CASE(ROLW) 10256 NODE_NAME_CASE(RORW) 10257 NODE_NAME_CASE(CLZW) 10258 NODE_NAME_CASE(CTZW) 10259 NODE_NAME_CASE(FSLW) 10260 NODE_NAME_CASE(FSRW) 10261 NODE_NAME_CASE(FSL) 10262 NODE_NAME_CASE(FSR) 10263 NODE_NAME_CASE(FMV_H_X) 10264 NODE_NAME_CASE(FMV_X_ANYEXTH) 10265 NODE_NAME_CASE(FMV_W_X_RV64) 10266 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10267 NODE_NAME_CASE(FCVT_X) 10268 NODE_NAME_CASE(FCVT_XU) 10269 NODE_NAME_CASE(FCVT_W_RV64) 10270 NODE_NAME_CASE(FCVT_WU_RV64) 10271 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10272 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10273 NODE_NAME_CASE(READ_CYCLE_WIDE) 10274 NODE_NAME_CASE(GREV) 10275 NODE_NAME_CASE(GREVW) 10276 NODE_NAME_CASE(GORC) 10277 NODE_NAME_CASE(GORCW) 10278 NODE_NAME_CASE(SHFL) 10279 NODE_NAME_CASE(SHFLW) 10280 NODE_NAME_CASE(UNSHFL) 10281 NODE_NAME_CASE(UNSHFLW) 10282 NODE_NAME_CASE(BFP) 10283 NODE_NAME_CASE(BFPW) 10284 NODE_NAME_CASE(BCOMPRESS) 10285 NODE_NAME_CASE(BCOMPRESSW) 10286 NODE_NAME_CASE(BDECOMPRESS) 10287 NODE_NAME_CASE(BDECOMPRESSW) 10288 NODE_NAME_CASE(VMV_V_X_VL) 10289 NODE_NAME_CASE(VFMV_V_F_VL) 10290 NODE_NAME_CASE(VMV_X_S) 10291 NODE_NAME_CASE(VMV_S_X_VL) 10292 NODE_NAME_CASE(VFMV_S_F_VL) 10293 NODE_NAME_CASE(SPLAT_VECTOR_I64) 10294 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10295 NODE_NAME_CASE(READ_VLENB) 10296 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10297 NODE_NAME_CASE(VSLIDEUP_VL) 10298 NODE_NAME_CASE(VSLIDE1UP_VL) 10299 NODE_NAME_CASE(VSLIDEDOWN_VL) 10300 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10301 NODE_NAME_CASE(VID_VL) 10302 NODE_NAME_CASE(VFNCVT_ROD_VL) 10303 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10304 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10305 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10306 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10307 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10308 NODE_NAME_CASE(VECREDUCE_AND_VL) 10309 NODE_NAME_CASE(VECREDUCE_OR_VL) 10310 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10311 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10312 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10313 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10314 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10315 NODE_NAME_CASE(ADD_VL) 10316 NODE_NAME_CASE(AND_VL) 10317 NODE_NAME_CASE(MUL_VL) 10318 NODE_NAME_CASE(OR_VL) 10319 NODE_NAME_CASE(SDIV_VL) 10320 NODE_NAME_CASE(SHL_VL) 10321 NODE_NAME_CASE(SREM_VL) 10322 NODE_NAME_CASE(SRA_VL) 10323 NODE_NAME_CASE(SRL_VL) 10324 NODE_NAME_CASE(SUB_VL) 10325 NODE_NAME_CASE(UDIV_VL) 10326 NODE_NAME_CASE(UREM_VL) 10327 NODE_NAME_CASE(XOR_VL) 10328 NODE_NAME_CASE(SADDSAT_VL) 10329 NODE_NAME_CASE(UADDSAT_VL) 10330 NODE_NAME_CASE(SSUBSAT_VL) 10331 NODE_NAME_CASE(USUBSAT_VL) 10332 NODE_NAME_CASE(FADD_VL) 10333 NODE_NAME_CASE(FSUB_VL) 10334 NODE_NAME_CASE(FMUL_VL) 10335 NODE_NAME_CASE(FDIV_VL) 10336 NODE_NAME_CASE(FNEG_VL) 10337 NODE_NAME_CASE(FABS_VL) 10338 NODE_NAME_CASE(FSQRT_VL) 10339 NODE_NAME_CASE(FMA_VL) 10340 NODE_NAME_CASE(FCOPYSIGN_VL) 10341 NODE_NAME_CASE(SMIN_VL) 10342 NODE_NAME_CASE(SMAX_VL) 10343 NODE_NAME_CASE(UMIN_VL) 10344 NODE_NAME_CASE(UMAX_VL) 10345 NODE_NAME_CASE(FMINNUM_VL) 10346 NODE_NAME_CASE(FMAXNUM_VL) 10347 NODE_NAME_CASE(MULHS_VL) 10348 NODE_NAME_CASE(MULHU_VL) 10349 NODE_NAME_CASE(FP_TO_SINT_VL) 10350 NODE_NAME_CASE(FP_TO_UINT_VL) 10351 NODE_NAME_CASE(SINT_TO_FP_VL) 10352 NODE_NAME_CASE(UINT_TO_FP_VL) 10353 NODE_NAME_CASE(FP_EXTEND_VL) 10354 NODE_NAME_CASE(FP_ROUND_VL) 10355 NODE_NAME_CASE(VWMUL_VL) 10356 NODE_NAME_CASE(VWMULU_VL) 10357 NODE_NAME_CASE(VWMULSU_VL) 10358 NODE_NAME_CASE(VWADD_VL) 10359 NODE_NAME_CASE(VWADDU_VL) 10360 NODE_NAME_CASE(VWSUB_VL) 10361 NODE_NAME_CASE(VWSUBU_VL) 10362 NODE_NAME_CASE(VWADD_W_VL) 10363 NODE_NAME_CASE(VWADDU_W_VL) 10364 NODE_NAME_CASE(VWSUB_W_VL) 10365 NODE_NAME_CASE(VWSUBU_W_VL) 10366 NODE_NAME_CASE(SETCC_VL) 10367 NODE_NAME_CASE(VSELECT_VL) 10368 NODE_NAME_CASE(VP_MERGE_VL) 10369 NODE_NAME_CASE(VMAND_VL) 10370 NODE_NAME_CASE(VMOR_VL) 10371 NODE_NAME_CASE(VMXOR_VL) 10372 NODE_NAME_CASE(VMCLR_VL) 10373 NODE_NAME_CASE(VMSET_VL) 10374 NODE_NAME_CASE(VRGATHER_VX_VL) 10375 NODE_NAME_CASE(VRGATHER_VV_VL) 10376 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10377 NODE_NAME_CASE(VSEXT_VL) 10378 NODE_NAME_CASE(VZEXT_VL) 10379 NODE_NAME_CASE(VCPOP_VL) 10380 NODE_NAME_CASE(VLE_VL) 10381 NODE_NAME_CASE(VSE_VL) 10382 NODE_NAME_CASE(READ_CSR) 10383 NODE_NAME_CASE(WRITE_CSR) 10384 NODE_NAME_CASE(SWAP_CSR) 10385 } 10386 // clang-format on 10387 return nullptr; 10388 #undef NODE_NAME_CASE 10389 } 10390 10391 /// getConstraintType - Given a constraint letter, return the type of 10392 /// constraint it is for this target. 10393 RISCVTargetLowering::ConstraintType 10394 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10395 if (Constraint.size() == 1) { 10396 switch (Constraint[0]) { 10397 default: 10398 break; 10399 case 'f': 10400 return C_RegisterClass; 10401 case 'I': 10402 case 'J': 10403 case 'K': 10404 return C_Immediate; 10405 case 'A': 10406 return C_Memory; 10407 case 'S': // A symbolic address 10408 return C_Other; 10409 } 10410 } else { 10411 if (Constraint == "vr" || Constraint == "vm") 10412 return C_RegisterClass; 10413 } 10414 return TargetLowering::getConstraintType(Constraint); 10415 } 10416 10417 std::pair<unsigned, const TargetRegisterClass *> 10418 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10419 StringRef Constraint, 10420 MVT VT) const { 10421 // First, see if this is a constraint that directly corresponds to a 10422 // RISCV register class. 10423 if (Constraint.size() == 1) { 10424 switch (Constraint[0]) { 10425 case 'r': 10426 // TODO: Support fixed vectors up to XLen for P extension? 10427 if (VT.isVector()) 10428 break; 10429 return std::make_pair(0U, &RISCV::GPRRegClass); 10430 case 'f': 10431 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10432 return std::make_pair(0U, &RISCV::FPR16RegClass); 10433 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10434 return std::make_pair(0U, &RISCV::FPR32RegClass); 10435 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10436 return std::make_pair(0U, &RISCV::FPR64RegClass); 10437 break; 10438 default: 10439 break; 10440 } 10441 } else if (Constraint == "vr") { 10442 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10443 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10444 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10445 return std::make_pair(0U, RC); 10446 } 10447 } else if (Constraint == "vm") { 10448 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10449 return std::make_pair(0U, &RISCV::VMV0RegClass); 10450 } 10451 10452 // Clang will correctly decode the usage of register name aliases into their 10453 // official names. However, other frontends like `rustc` do not. This allows 10454 // users of these frontends to use the ABI names for registers in LLVM-style 10455 // register constraints. 10456 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10457 .Case("{zero}", RISCV::X0) 10458 .Case("{ra}", RISCV::X1) 10459 .Case("{sp}", RISCV::X2) 10460 .Case("{gp}", RISCV::X3) 10461 .Case("{tp}", RISCV::X4) 10462 .Case("{t0}", RISCV::X5) 10463 .Case("{t1}", RISCV::X6) 10464 .Case("{t2}", RISCV::X7) 10465 .Cases("{s0}", "{fp}", RISCV::X8) 10466 .Case("{s1}", RISCV::X9) 10467 .Case("{a0}", RISCV::X10) 10468 .Case("{a1}", RISCV::X11) 10469 .Case("{a2}", RISCV::X12) 10470 .Case("{a3}", RISCV::X13) 10471 .Case("{a4}", RISCV::X14) 10472 .Case("{a5}", RISCV::X15) 10473 .Case("{a6}", RISCV::X16) 10474 .Case("{a7}", RISCV::X17) 10475 .Case("{s2}", RISCV::X18) 10476 .Case("{s3}", RISCV::X19) 10477 .Case("{s4}", RISCV::X20) 10478 .Case("{s5}", RISCV::X21) 10479 .Case("{s6}", RISCV::X22) 10480 .Case("{s7}", RISCV::X23) 10481 .Case("{s8}", RISCV::X24) 10482 .Case("{s9}", RISCV::X25) 10483 .Case("{s10}", RISCV::X26) 10484 .Case("{s11}", RISCV::X27) 10485 .Case("{t3}", RISCV::X28) 10486 .Case("{t4}", RISCV::X29) 10487 .Case("{t5}", RISCV::X30) 10488 .Case("{t6}", RISCV::X31) 10489 .Default(RISCV::NoRegister); 10490 if (XRegFromAlias != RISCV::NoRegister) 10491 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10492 10493 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10494 // TableGen record rather than the AsmName to choose registers for InlineAsm 10495 // constraints, plus we want to match those names to the widest floating point 10496 // register type available, manually select floating point registers here. 10497 // 10498 // The second case is the ABI name of the register, so that frontends can also 10499 // use the ABI names in register constraint lists. 10500 if (Subtarget.hasStdExtF()) { 10501 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10502 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10503 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10504 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10505 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10506 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10507 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10508 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10509 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10510 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10511 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10512 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10513 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10514 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10515 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10516 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10517 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10518 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10519 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10520 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10521 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10522 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10523 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10524 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10525 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10526 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10527 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10528 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10529 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10530 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10531 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10532 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10533 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10534 .Default(RISCV::NoRegister); 10535 if (FReg != RISCV::NoRegister) { 10536 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10537 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10538 unsigned RegNo = FReg - RISCV::F0_F; 10539 unsigned DReg = RISCV::F0_D + RegNo; 10540 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10541 } 10542 if (VT == MVT::f32 || VT == MVT::Other) 10543 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10544 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10545 unsigned RegNo = FReg - RISCV::F0_F; 10546 unsigned HReg = RISCV::F0_H + RegNo; 10547 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10548 } 10549 } 10550 } 10551 10552 if (Subtarget.hasVInstructions()) { 10553 Register VReg = StringSwitch<Register>(Constraint.lower()) 10554 .Case("{v0}", RISCV::V0) 10555 .Case("{v1}", RISCV::V1) 10556 .Case("{v2}", RISCV::V2) 10557 .Case("{v3}", RISCV::V3) 10558 .Case("{v4}", RISCV::V4) 10559 .Case("{v5}", RISCV::V5) 10560 .Case("{v6}", RISCV::V6) 10561 .Case("{v7}", RISCV::V7) 10562 .Case("{v8}", RISCV::V8) 10563 .Case("{v9}", RISCV::V9) 10564 .Case("{v10}", RISCV::V10) 10565 .Case("{v11}", RISCV::V11) 10566 .Case("{v12}", RISCV::V12) 10567 .Case("{v13}", RISCV::V13) 10568 .Case("{v14}", RISCV::V14) 10569 .Case("{v15}", RISCV::V15) 10570 .Case("{v16}", RISCV::V16) 10571 .Case("{v17}", RISCV::V17) 10572 .Case("{v18}", RISCV::V18) 10573 .Case("{v19}", RISCV::V19) 10574 .Case("{v20}", RISCV::V20) 10575 .Case("{v21}", RISCV::V21) 10576 .Case("{v22}", RISCV::V22) 10577 .Case("{v23}", RISCV::V23) 10578 .Case("{v24}", RISCV::V24) 10579 .Case("{v25}", RISCV::V25) 10580 .Case("{v26}", RISCV::V26) 10581 .Case("{v27}", RISCV::V27) 10582 .Case("{v28}", RISCV::V28) 10583 .Case("{v29}", RISCV::V29) 10584 .Case("{v30}", RISCV::V30) 10585 .Case("{v31}", RISCV::V31) 10586 .Default(RISCV::NoRegister); 10587 if (VReg != RISCV::NoRegister) { 10588 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10589 return std::make_pair(VReg, &RISCV::VMRegClass); 10590 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10591 return std::make_pair(VReg, &RISCV::VRRegClass); 10592 for (const auto *RC : 10593 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10594 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10595 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10596 return std::make_pair(VReg, RC); 10597 } 10598 } 10599 } 10600 } 10601 10602 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10603 } 10604 10605 unsigned 10606 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10607 // Currently only support length 1 constraints. 10608 if (ConstraintCode.size() == 1) { 10609 switch (ConstraintCode[0]) { 10610 case 'A': 10611 return InlineAsm::Constraint_A; 10612 default: 10613 break; 10614 } 10615 } 10616 10617 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10618 } 10619 10620 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10621 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10622 SelectionDAG &DAG) const { 10623 // Currently only support length 1 constraints. 10624 if (Constraint.length() == 1) { 10625 switch (Constraint[0]) { 10626 case 'I': 10627 // Validate & create a 12-bit signed immediate operand. 10628 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10629 uint64_t CVal = C->getSExtValue(); 10630 if (isInt<12>(CVal)) 10631 Ops.push_back( 10632 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10633 } 10634 return; 10635 case 'J': 10636 // Validate & create an integer zero operand. 10637 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10638 if (C->getZExtValue() == 0) 10639 Ops.push_back( 10640 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10641 return; 10642 case 'K': 10643 // Validate & create a 5-bit unsigned immediate operand. 10644 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10645 uint64_t CVal = C->getZExtValue(); 10646 if (isUInt<5>(CVal)) 10647 Ops.push_back( 10648 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10649 } 10650 return; 10651 case 'S': 10652 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10653 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10654 GA->getValueType(0))); 10655 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10656 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10657 BA->getValueType(0))); 10658 } 10659 return; 10660 default: 10661 break; 10662 } 10663 } 10664 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10665 } 10666 10667 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10668 Instruction *Inst, 10669 AtomicOrdering Ord) const { 10670 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10671 return Builder.CreateFence(Ord); 10672 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10673 return Builder.CreateFence(AtomicOrdering::Release); 10674 return nullptr; 10675 } 10676 10677 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10678 Instruction *Inst, 10679 AtomicOrdering Ord) const { 10680 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 10681 return Builder.CreateFence(AtomicOrdering::Acquire); 10682 return nullptr; 10683 } 10684 10685 TargetLowering::AtomicExpansionKind 10686 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10687 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 10688 // point operations can't be used in an lr/sc sequence without breaking the 10689 // forward-progress guarantee. 10690 if (AI->isFloatingPointOperation()) 10691 return AtomicExpansionKind::CmpXChg; 10692 10693 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10694 if (Size == 8 || Size == 16) 10695 return AtomicExpansionKind::MaskedIntrinsic; 10696 return AtomicExpansionKind::None; 10697 } 10698 10699 static Intrinsic::ID 10700 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 10701 if (XLen == 32) { 10702 switch (BinOp) { 10703 default: 10704 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10705 case AtomicRMWInst::Xchg: 10706 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 10707 case AtomicRMWInst::Add: 10708 return Intrinsic::riscv_masked_atomicrmw_add_i32; 10709 case AtomicRMWInst::Sub: 10710 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 10711 case AtomicRMWInst::Nand: 10712 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 10713 case AtomicRMWInst::Max: 10714 return Intrinsic::riscv_masked_atomicrmw_max_i32; 10715 case AtomicRMWInst::Min: 10716 return Intrinsic::riscv_masked_atomicrmw_min_i32; 10717 case AtomicRMWInst::UMax: 10718 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 10719 case AtomicRMWInst::UMin: 10720 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 10721 } 10722 } 10723 10724 if (XLen == 64) { 10725 switch (BinOp) { 10726 default: 10727 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10728 case AtomicRMWInst::Xchg: 10729 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 10730 case AtomicRMWInst::Add: 10731 return Intrinsic::riscv_masked_atomicrmw_add_i64; 10732 case AtomicRMWInst::Sub: 10733 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 10734 case AtomicRMWInst::Nand: 10735 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 10736 case AtomicRMWInst::Max: 10737 return Intrinsic::riscv_masked_atomicrmw_max_i64; 10738 case AtomicRMWInst::Min: 10739 return Intrinsic::riscv_masked_atomicrmw_min_i64; 10740 case AtomicRMWInst::UMax: 10741 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 10742 case AtomicRMWInst::UMin: 10743 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 10744 } 10745 } 10746 10747 llvm_unreachable("Unexpected XLen\n"); 10748 } 10749 10750 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 10751 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 10752 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 10753 unsigned XLen = Subtarget.getXLen(); 10754 Value *Ordering = 10755 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 10756 Type *Tys[] = {AlignedAddr->getType()}; 10757 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 10758 AI->getModule(), 10759 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 10760 10761 if (XLen == 64) { 10762 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 10763 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10764 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 10765 } 10766 10767 Value *Result; 10768 10769 // Must pass the shift amount needed to sign extend the loaded value prior 10770 // to performing a signed comparison for min/max. ShiftAmt is the number of 10771 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 10772 // is the number of bits to left+right shift the value in order to 10773 // sign-extend. 10774 if (AI->getOperation() == AtomicRMWInst::Min || 10775 AI->getOperation() == AtomicRMWInst::Max) { 10776 const DataLayout &DL = AI->getModule()->getDataLayout(); 10777 unsigned ValWidth = 10778 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 10779 Value *SextShamt = 10780 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 10781 Result = Builder.CreateCall(LrwOpScwLoop, 10782 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 10783 } else { 10784 Result = 10785 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 10786 } 10787 10788 if (XLen == 64) 10789 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10790 return Result; 10791 } 10792 10793 TargetLowering::AtomicExpansionKind 10794 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 10795 AtomicCmpXchgInst *CI) const { 10796 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 10797 if (Size == 8 || Size == 16) 10798 return AtomicExpansionKind::MaskedIntrinsic; 10799 return AtomicExpansionKind::None; 10800 } 10801 10802 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 10803 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 10804 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 10805 unsigned XLen = Subtarget.getXLen(); 10806 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 10807 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 10808 if (XLen == 64) { 10809 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 10810 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 10811 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10812 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 10813 } 10814 Type *Tys[] = {AlignedAddr->getType()}; 10815 Function *MaskedCmpXchg = 10816 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 10817 Value *Result = Builder.CreateCall( 10818 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 10819 if (XLen == 64) 10820 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10821 return Result; 10822 } 10823 10824 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 10825 return false; 10826 } 10827 10828 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 10829 EVT VT) const { 10830 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 10831 return false; 10832 10833 switch (FPVT.getSimpleVT().SimpleTy) { 10834 case MVT::f16: 10835 return Subtarget.hasStdExtZfh(); 10836 case MVT::f32: 10837 return Subtarget.hasStdExtF(); 10838 case MVT::f64: 10839 return Subtarget.hasStdExtD(); 10840 default: 10841 return false; 10842 } 10843 } 10844 10845 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 10846 // If we are using the small code model, we can reduce size of jump table 10847 // entry to 4 bytes. 10848 if (Subtarget.is64Bit() && !isPositionIndependent() && 10849 getTargetMachine().getCodeModel() == CodeModel::Small) { 10850 return MachineJumpTableInfo::EK_Custom32; 10851 } 10852 return TargetLowering::getJumpTableEncoding(); 10853 } 10854 10855 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 10856 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 10857 unsigned uid, MCContext &Ctx) const { 10858 assert(Subtarget.is64Bit() && !isPositionIndependent() && 10859 getTargetMachine().getCodeModel() == CodeModel::Small); 10860 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 10861 } 10862 10863 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 10864 EVT VT) const { 10865 VT = VT.getScalarType(); 10866 10867 if (!VT.isSimple()) 10868 return false; 10869 10870 switch (VT.getSimpleVT().SimpleTy) { 10871 case MVT::f16: 10872 return Subtarget.hasStdExtZfh(); 10873 case MVT::f32: 10874 return Subtarget.hasStdExtF(); 10875 case MVT::f64: 10876 return Subtarget.hasStdExtD(); 10877 default: 10878 break; 10879 } 10880 10881 return false; 10882 } 10883 10884 Register RISCVTargetLowering::getExceptionPointerRegister( 10885 const Constant *PersonalityFn) const { 10886 return RISCV::X10; 10887 } 10888 10889 Register RISCVTargetLowering::getExceptionSelectorRegister( 10890 const Constant *PersonalityFn) const { 10891 return RISCV::X11; 10892 } 10893 10894 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 10895 // Return false to suppress the unnecessary extensions if the LibCall 10896 // arguments or return value is f32 type for LP64 ABI. 10897 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 10898 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 10899 return false; 10900 10901 return true; 10902 } 10903 10904 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 10905 if (Subtarget.is64Bit() && Type == MVT::i32) 10906 return true; 10907 10908 return IsSigned; 10909 } 10910 10911 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 10912 SDValue C) const { 10913 // Check integral scalar types. 10914 if (VT.isScalarInteger()) { 10915 // Omit the optimization if the sub target has the M extension and the data 10916 // size exceeds XLen. 10917 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 10918 return false; 10919 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 10920 // Break the MUL to a SLLI and an ADD/SUB. 10921 const APInt &Imm = ConstNode->getAPIntValue(); 10922 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 10923 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 10924 return true; 10925 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 10926 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 10927 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 10928 (Imm - 8).isPowerOf2())) 10929 return true; 10930 // Omit the following optimization if the sub target has the M extension 10931 // and the data size >= XLen. 10932 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 10933 return false; 10934 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 10935 // a pair of LUI/ADDI. 10936 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 10937 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 10938 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 10939 (1 - ImmS).isPowerOf2()) 10940 return true; 10941 } 10942 } 10943 } 10944 10945 return false; 10946 } 10947 10948 bool RISCVTargetLowering::isMulAddWithConstProfitable( 10949 const SDValue &AddNode, const SDValue &ConstNode) const { 10950 // Let the DAGCombiner decide for vectors. 10951 EVT VT = AddNode.getValueType(); 10952 if (VT.isVector()) 10953 return true; 10954 10955 // Let the DAGCombiner decide for larger types. 10956 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 10957 return true; 10958 10959 // It is worse if c1 is simm12 while c1*c2 is not. 10960 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 10961 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 10962 const APInt &C1 = C1Node->getAPIntValue(); 10963 const APInt &C2 = C2Node->getAPIntValue(); 10964 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 10965 return false; 10966 10967 // Default to true and let the DAGCombiner decide. 10968 return true; 10969 } 10970 10971 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 10972 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 10973 bool *Fast) const { 10974 if (!VT.isVector()) 10975 return false; 10976 10977 EVT ElemVT = VT.getVectorElementType(); 10978 if (Alignment >= ElemVT.getStoreSize()) { 10979 if (Fast) 10980 *Fast = true; 10981 return true; 10982 } 10983 10984 return false; 10985 } 10986 10987 bool RISCVTargetLowering::splitValueIntoRegisterParts( 10988 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 10989 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 10990 bool IsABIRegCopy = CC.hasValue(); 10991 EVT ValueVT = Val.getValueType(); 10992 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10993 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 10994 // and cast to f32. 10995 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 10996 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 10997 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 10998 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 10999 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11000 Parts[0] = Val; 11001 return true; 11002 } 11003 11004 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11005 LLVMContext &Context = *DAG.getContext(); 11006 EVT ValueEltVT = ValueVT.getVectorElementType(); 11007 EVT PartEltVT = PartVT.getVectorElementType(); 11008 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11009 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11010 if (PartVTBitSize % ValueVTBitSize == 0) { 11011 assert(PartVTBitSize >= ValueVTBitSize); 11012 // If the element types are different, bitcast to the same element type of 11013 // PartVT first. 11014 // Give an example here, we want copy a <vscale x 1 x i8> value to 11015 // <vscale x 4 x i16>. 11016 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11017 // subvector, then we can bitcast to <vscale x 4 x i16>. 11018 if (ValueEltVT != PartEltVT) { 11019 if (PartVTBitSize > ValueVTBitSize) { 11020 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11021 assert(Count != 0 && "The number of element should not be zero."); 11022 EVT SameEltTypeVT = 11023 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11024 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11025 DAG.getUNDEF(SameEltTypeVT), Val, 11026 DAG.getVectorIdxConstant(0, DL)); 11027 } 11028 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11029 } else { 11030 Val = 11031 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11032 Val, DAG.getVectorIdxConstant(0, DL)); 11033 } 11034 Parts[0] = Val; 11035 return true; 11036 } 11037 } 11038 return false; 11039 } 11040 11041 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11042 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11043 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11044 bool IsABIRegCopy = CC.hasValue(); 11045 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11046 SDValue Val = Parts[0]; 11047 11048 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11049 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11050 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11051 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11052 return Val; 11053 } 11054 11055 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11056 LLVMContext &Context = *DAG.getContext(); 11057 SDValue Val = Parts[0]; 11058 EVT ValueEltVT = ValueVT.getVectorElementType(); 11059 EVT PartEltVT = PartVT.getVectorElementType(); 11060 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11061 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11062 if (PartVTBitSize % ValueVTBitSize == 0) { 11063 assert(PartVTBitSize >= ValueVTBitSize); 11064 EVT SameEltTypeVT = ValueVT; 11065 // If the element types are different, convert it to the same element type 11066 // of PartVT. 11067 // Give an example here, we want copy a <vscale x 1 x i8> value from 11068 // <vscale x 4 x i16>. 11069 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11070 // then we can extract <vscale x 1 x i8>. 11071 if (ValueEltVT != PartEltVT) { 11072 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11073 assert(Count != 0 && "The number of element should not be zero."); 11074 SameEltTypeVT = 11075 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11076 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11077 } 11078 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11079 DAG.getVectorIdxConstant(0, DL)); 11080 return Val; 11081 } 11082 } 11083 return SDValue(); 11084 } 11085 11086 SDValue 11087 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11088 SelectionDAG &DAG, 11089 SmallVectorImpl<SDNode *> &Created) const { 11090 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11091 if (isIntDivCheap(N->getValueType(0), Attr)) 11092 return SDValue(N, 0); // Lower SDIV as SDIV 11093 11094 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11095 "Unexpected divisor!"); 11096 11097 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11098 if (!Subtarget.hasStdExtZbt()) 11099 return SDValue(); 11100 11101 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11102 // Besides, more critical path instructions will be generated when dividing 11103 // by 2. So we keep using the original DAGs for these cases. 11104 unsigned Lg2 = Divisor.countTrailingZeros(); 11105 if (Lg2 == 1 || Lg2 >= 12) 11106 return SDValue(); 11107 11108 // fold (sdiv X, pow2) 11109 EVT VT = N->getValueType(0); 11110 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11111 return SDValue(); 11112 11113 SDLoc DL(N); 11114 SDValue N0 = N->getOperand(0); 11115 SDValue Zero = DAG.getConstant(0, DL, VT); 11116 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11117 11118 // Add (N0 < 0) ? Pow2 - 1 : 0; 11119 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11120 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11121 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11122 11123 Created.push_back(Cmp.getNode()); 11124 Created.push_back(Add.getNode()); 11125 Created.push_back(Sel.getNode()); 11126 11127 // Divide by pow2. 11128 SDValue SRA = 11129 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11130 11131 // If we're dividing by a positive value, we're done. Otherwise, we must 11132 // negate the result. 11133 if (Divisor.isNonNegative()) 11134 return SRA; 11135 11136 Created.push_back(SRA.getNode()); 11137 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11138 } 11139 11140 #define GET_REGISTER_MATCHER 11141 #include "RISCVGenAsmMatcher.inc" 11142 11143 Register 11144 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11145 const MachineFunction &MF) const { 11146 Register Reg = MatchRegisterAltName(RegName); 11147 if (Reg == RISCV::NoRegister) 11148 Reg = MatchRegisterName(RegName); 11149 if (Reg == RISCV::NoRegister) 11150 report_fatal_error( 11151 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11152 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11153 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11154 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11155 StringRef(RegName) + "\".")); 11156 return Reg; 11157 } 11158 11159 namespace llvm { 11160 namespace RISCVVIntrinsicsTable { 11161 11162 #define GET_RISCVVIntrinsicsTable_IMPL 11163 #include "RISCVGenSearchableTables.inc" 11164 11165 } // namespace RISCVVIntrinsicsTable 11166 11167 } // namespace llvm 11168