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 } 286 287 if (Subtarget.hasStdExtZbb()) { 288 setOperationAction(ISD::SMIN, XLenVT, Legal); 289 setOperationAction(ISD::SMAX, XLenVT, Legal); 290 setOperationAction(ISD::UMIN, XLenVT, Legal); 291 setOperationAction(ISD::UMAX, XLenVT, Legal); 292 293 if (Subtarget.is64Bit()) { 294 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 295 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 296 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 297 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 298 } 299 } else { 300 setOperationAction(ISD::CTTZ, XLenVT, Expand); 301 setOperationAction(ISD::CTLZ, XLenVT, Expand); 302 setOperationAction(ISD::CTPOP, XLenVT, Expand); 303 } 304 305 if (Subtarget.hasStdExtZbt()) { 306 setOperationAction(ISD::FSHL, XLenVT, Custom); 307 setOperationAction(ISD::FSHR, XLenVT, Custom); 308 setOperationAction(ISD::SELECT, XLenVT, Legal); 309 310 if (Subtarget.is64Bit()) { 311 setOperationAction(ISD::FSHL, MVT::i32, Custom); 312 setOperationAction(ISD::FSHR, MVT::i32, Custom); 313 } 314 } else { 315 setOperationAction(ISD::SELECT, XLenVT, Custom); 316 } 317 318 static const ISD::CondCode FPCCToExpand[] = { 319 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 320 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 321 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 322 323 static const ISD::NodeType FPOpToExpand[] = { 324 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 325 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 326 327 if (Subtarget.hasStdExtZfh()) 328 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 329 330 if (Subtarget.hasStdExtZfh()) { 331 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 332 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 333 setOperationAction(ISD::LRINT, MVT::f16, Legal); 334 setOperationAction(ISD::LLRINT, MVT::f16, Legal); 335 setOperationAction(ISD::LROUND, MVT::f16, Legal); 336 setOperationAction(ISD::LLROUND, MVT::f16, Legal); 337 setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal); 338 setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal); 339 setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal); 340 setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal); 341 setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal); 342 setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal); 343 setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal); 344 setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal); 345 setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal); 346 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 347 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 348 setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal); 349 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal); 350 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal); 351 for (auto CC : FPCCToExpand) 352 setCondCodeAction(CC, MVT::f16, Expand); 353 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 354 setOperationAction(ISD::SELECT, MVT::f16, Custom); 355 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 356 357 setOperationAction(ISD::FREM, MVT::f16, Promote); 358 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 359 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 360 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 361 setOperationAction(ISD::FRINT, MVT::f16, Promote); 362 setOperationAction(ISD::FROUND, MVT::f16, Promote); 363 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 364 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 365 setOperationAction(ISD::FPOW, MVT::f16, Promote); 366 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 367 setOperationAction(ISD::FCOS, MVT::f16, Promote); 368 setOperationAction(ISD::FSIN, MVT::f16, Promote); 369 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 370 setOperationAction(ISD::FEXP, MVT::f16, Promote); 371 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 372 setOperationAction(ISD::FLOG, MVT::f16, Promote); 373 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 374 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 375 376 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 377 // complete support for all operations in LegalizeDAG. 378 379 // We need to custom promote this. 380 if (Subtarget.is64Bit()) 381 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 382 } 383 384 if (Subtarget.hasStdExtF()) { 385 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 386 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 387 setOperationAction(ISD::LRINT, MVT::f32, Legal); 388 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 389 setOperationAction(ISD::LROUND, MVT::f32, Legal); 390 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 391 setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal); 392 setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal); 393 setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal); 394 setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal); 395 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 396 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 397 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 398 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 399 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 400 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 401 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 402 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 403 for (auto CC : FPCCToExpand) 404 setCondCodeAction(CC, MVT::f32, Expand); 405 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 406 setOperationAction(ISD::SELECT, MVT::f32, Custom); 407 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 408 for (auto Op : FPOpToExpand) 409 setOperationAction(Op, MVT::f32, Expand); 410 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 411 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 412 } 413 414 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 415 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 416 417 if (Subtarget.hasStdExtD()) { 418 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 419 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 420 setOperationAction(ISD::LRINT, MVT::f64, Legal); 421 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 422 setOperationAction(ISD::LROUND, MVT::f64, Legal); 423 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 424 setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal); 425 setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal); 426 setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal); 427 setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal); 428 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 429 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 430 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 431 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 432 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 433 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 434 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 435 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 436 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 437 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 438 for (auto CC : FPCCToExpand) 439 setCondCodeAction(CC, MVT::f64, Expand); 440 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 441 setOperationAction(ISD::SELECT, MVT::f64, Custom); 442 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 443 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 444 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 445 for (auto Op : FPOpToExpand) 446 setOperationAction(Op, MVT::f64, Expand); 447 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 448 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 449 } 450 451 if (Subtarget.is64Bit()) { 452 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 453 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 454 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 455 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 456 } 457 458 if (Subtarget.hasStdExtF()) { 459 setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom); 460 setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom); 461 462 setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal); 463 setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal); 464 setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal); 465 setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal); 466 467 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 468 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 469 } 470 471 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 472 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 473 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 474 setOperationAction(ISD::JumpTable, XLenVT, Custom); 475 476 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 477 478 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 479 // Unfortunately this can't be determined just from the ISA naming string. 480 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 481 Subtarget.is64Bit() ? Legal : Custom); 482 483 setOperationAction(ISD::TRAP, MVT::Other, Legal); 484 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 485 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 486 if (Subtarget.is64Bit()) 487 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 488 489 if (Subtarget.hasStdExtA()) { 490 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 491 setMinCmpXchgSizeInBits(32); 492 } else { 493 setMaxAtomicSizeInBitsSupported(0); 494 } 495 496 setBooleanContents(ZeroOrOneBooleanContent); 497 498 if (Subtarget.hasVInstructions()) { 499 setBooleanVectorContents(ZeroOrOneBooleanContent); 500 501 setOperationAction(ISD::VSCALE, XLenVT, Custom); 502 503 // RVV intrinsics may have illegal operands. 504 // We also need to custom legalize vmv.x.s. 505 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 506 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 507 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 508 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 509 if (Subtarget.is64Bit()) { 510 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 511 } else { 512 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 513 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 514 } 515 516 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 517 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 518 519 static const unsigned IntegerVPOps[] = { 520 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 521 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 522 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 523 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 524 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 525 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 526 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 527 ISD::VP_MERGE, ISD::VP_SELECT}; 528 529 static const unsigned FloatingPointVPOps[] = { 530 ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL, 531 ISD::VP_FDIV, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 532 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE, 533 ISD::VP_SELECT}; 534 535 if (!Subtarget.is64Bit()) { 536 // We must custom-lower certain vXi64 operations on RV32 due to the vector 537 // element type being illegal. 538 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 539 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 540 541 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 542 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 543 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 544 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 545 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 546 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 547 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 548 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 549 550 setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom); 551 setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom); 552 setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom); 553 setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom); 554 setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom); 555 setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom); 556 setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom); 557 setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom); 558 } 559 560 for (MVT VT : BoolVecVTs) { 561 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 562 563 // Mask VTs are custom-expanded into a series of standard nodes 564 setOperationAction(ISD::TRUNCATE, VT, Custom); 565 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 566 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 567 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 568 569 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 570 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 571 572 setOperationAction(ISD::SELECT, VT, Custom); 573 setOperationAction(ISD::SELECT_CC, VT, Expand); 574 setOperationAction(ISD::VSELECT, VT, Expand); 575 setOperationAction(ISD::VP_MERGE, VT, Expand); 576 setOperationAction(ISD::VP_SELECT, VT, Expand); 577 578 setOperationAction(ISD::VP_AND, VT, Custom); 579 setOperationAction(ISD::VP_OR, VT, Custom); 580 setOperationAction(ISD::VP_XOR, VT, Custom); 581 582 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 583 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 584 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 585 586 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 587 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 588 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 589 590 // RVV has native int->float & float->int conversions where the 591 // element type sizes are within one power-of-two of each other. Any 592 // wider distances between type sizes have to be lowered as sequences 593 // which progressively narrow the gap in stages. 594 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 595 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 596 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 597 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 598 599 // Expand all extending loads to types larger than this, and truncating 600 // stores from types larger than this. 601 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 602 setTruncStoreAction(OtherVT, VT, Expand); 603 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 604 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 605 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 606 } 607 } 608 609 for (MVT VT : IntVecVTs) { 610 if (VT.getVectorElementType() == MVT::i64 && 611 !Subtarget.hasVInstructionsI64()) 612 continue; 613 614 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 615 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 616 617 // Vectors implement MULHS/MULHU. 618 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 619 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 620 621 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 622 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) { 623 setOperationAction(ISD::MULHU, VT, Expand); 624 setOperationAction(ISD::MULHS, VT, Expand); 625 } 626 627 setOperationAction(ISD::SMIN, VT, Legal); 628 setOperationAction(ISD::SMAX, VT, Legal); 629 setOperationAction(ISD::UMIN, VT, Legal); 630 setOperationAction(ISD::UMAX, VT, Legal); 631 632 setOperationAction(ISD::ROTL, VT, Expand); 633 setOperationAction(ISD::ROTR, VT, Expand); 634 635 setOperationAction(ISD::CTTZ, VT, Expand); 636 setOperationAction(ISD::CTLZ, VT, Expand); 637 setOperationAction(ISD::CTPOP, VT, Expand); 638 639 setOperationAction(ISD::BSWAP, VT, Expand); 640 641 // Custom-lower extensions and truncations from/to mask types. 642 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 643 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 644 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 645 646 // RVV has native int->float & float->int conversions where the 647 // element type sizes are within one power-of-two of each other. Any 648 // wider distances between type sizes have to be lowered as sequences 649 // which progressively narrow the gap in stages. 650 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 651 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 652 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 653 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 654 655 setOperationAction(ISD::SADDSAT, VT, Legal); 656 setOperationAction(ISD::UADDSAT, VT, Legal); 657 setOperationAction(ISD::SSUBSAT, VT, Legal); 658 setOperationAction(ISD::USUBSAT, VT, Legal); 659 660 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 661 // nodes which truncate by one power of two at a time. 662 setOperationAction(ISD::TRUNCATE, VT, Custom); 663 664 // Custom-lower insert/extract operations to simplify patterns. 665 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 666 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 667 668 // Custom-lower reduction operations to set up the corresponding custom 669 // nodes' operands. 670 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 671 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 672 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 673 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 674 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 675 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 676 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 677 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 678 679 for (unsigned VPOpc : IntegerVPOps) 680 setOperationAction(VPOpc, VT, Custom); 681 682 setOperationAction(ISD::LOAD, VT, Custom); 683 setOperationAction(ISD::STORE, VT, Custom); 684 685 setOperationAction(ISD::MLOAD, VT, Custom); 686 setOperationAction(ISD::MSTORE, VT, Custom); 687 setOperationAction(ISD::MGATHER, VT, Custom); 688 setOperationAction(ISD::MSCATTER, VT, Custom); 689 690 setOperationAction(ISD::VP_LOAD, VT, Custom); 691 setOperationAction(ISD::VP_STORE, VT, Custom); 692 setOperationAction(ISD::VP_GATHER, VT, Custom); 693 setOperationAction(ISD::VP_SCATTER, VT, Custom); 694 695 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 696 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 697 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 698 699 setOperationAction(ISD::SELECT, VT, Custom); 700 setOperationAction(ISD::SELECT_CC, VT, Expand); 701 702 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 703 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 704 705 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 706 setTruncStoreAction(VT, OtherVT, Expand); 707 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 708 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 709 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 710 } 711 712 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 713 // type that can represent the value exactly. 714 if (VT.getVectorElementType() != MVT::i64) { 715 MVT FloatEltVT = 716 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 717 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 718 if (isTypeLegal(FloatVT)) { 719 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 720 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 721 } 722 } 723 } 724 725 // Expand various CCs to best match the RVV ISA, which natively supports UNE 726 // but no other unordered comparisons, and supports all ordered comparisons 727 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 728 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 729 // and we pattern-match those back to the "original", swapping operands once 730 // more. This way we catch both operations and both "vf" and "fv" forms with 731 // fewer patterns. 732 static const ISD::CondCode VFPCCToExpand[] = { 733 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 734 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 735 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 736 }; 737 738 // Sets common operation actions on RVV floating-point vector types. 739 const auto SetCommonVFPActions = [&](MVT VT) { 740 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 741 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 742 // sizes are within one power-of-two of each other. Therefore conversions 743 // between vXf16 and vXf64 must be lowered as sequences which convert via 744 // vXf32. 745 setOperationAction(ISD::FP_ROUND, VT, Custom); 746 setOperationAction(ISD::FP_EXTEND, VT, Custom); 747 // Custom-lower insert/extract operations to simplify patterns. 748 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 749 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 750 // Expand various condition codes (explained above). 751 for (auto CC : VFPCCToExpand) 752 setCondCodeAction(CC, VT, Expand); 753 754 setOperationAction(ISD::FMINNUM, VT, Legal); 755 setOperationAction(ISD::FMAXNUM, VT, Legal); 756 757 setOperationAction(ISD::FTRUNC, VT, Custom); 758 setOperationAction(ISD::FCEIL, VT, Custom); 759 setOperationAction(ISD::FFLOOR, VT, Custom); 760 761 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 762 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 763 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 764 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 765 766 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 767 768 setOperationAction(ISD::LOAD, VT, Custom); 769 setOperationAction(ISD::STORE, VT, Custom); 770 771 setOperationAction(ISD::MLOAD, VT, Custom); 772 setOperationAction(ISD::MSTORE, VT, Custom); 773 setOperationAction(ISD::MGATHER, VT, Custom); 774 setOperationAction(ISD::MSCATTER, VT, Custom); 775 776 setOperationAction(ISD::VP_LOAD, VT, Custom); 777 setOperationAction(ISD::VP_STORE, VT, Custom); 778 setOperationAction(ISD::VP_GATHER, VT, Custom); 779 setOperationAction(ISD::VP_SCATTER, VT, Custom); 780 781 setOperationAction(ISD::SELECT, VT, Custom); 782 setOperationAction(ISD::SELECT_CC, VT, Expand); 783 784 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 785 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 786 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 787 788 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 789 790 for (unsigned VPOpc : FloatingPointVPOps) 791 setOperationAction(VPOpc, VT, Custom); 792 }; 793 794 // Sets common extload/truncstore actions on RVV floating-point vector 795 // types. 796 const auto SetCommonVFPExtLoadTruncStoreActions = 797 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 798 for (auto SmallVT : SmallerVTs) { 799 setTruncStoreAction(VT, SmallVT, Expand); 800 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 801 } 802 }; 803 804 if (Subtarget.hasVInstructionsF16()) 805 for (MVT VT : F16VecVTs) 806 SetCommonVFPActions(VT); 807 808 for (MVT VT : F32VecVTs) { 809 if (Subtarget.hasVInstructionsF32()) 810 SetCommonVFPActions(VT); 811 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 812 } 813 814 for (MVT VT : F64VecVTs) { 815 if (Subtarget.hasVInstructionsF64()) 816 SetCommonVFPActions(VT); 817 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 818 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 819 } 820 821 if (Subtarget.useRVVForFixedLengthVectors()) { 822 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 823 if (!useRVVForFixedLengthVectorVT(VT)) 824 continue; 825 826 // By default everything must be expanded. 827 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 828 setOperationAction(Op, VT, Expand); 829 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 830 setTruncStoreAction(VT, OtherVT, Expand); 831 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 832 setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand); 833 setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand); 834 } 835 836 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 837 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 838 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 839 840 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 841 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 842 843 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 844 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 845 846 setOperationAction(ISD::LOAD, VT, Custom); 847 setOperationAction(ISD::STORE, VT, Custom); 848 849 setOperationAction(ISD::SETCC, VT, Custom); 850 851 setOperationAction(ISD::SELECT, VT, Custom); 852 853 setOperationAction(ISD::TRUNCATE, VT, Custom); 854 855 setOperationAction(ISD::BITCAST, VT, Custom); 856 857 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 858 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 859 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 860 861 setOperationAction(ISD::VP_REDUCE_AND, VT, Custom); 862 setOperationAction(ISD::VP_REDUCE_OR, VT, Custom); 863 setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom); 864 865 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 866 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 867 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 868 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 869 870 // Operations below are different for between masks and other vectors. 871 if (VT.getVectorElementType() == MVT::i1) { 872 setOperationAction(ISD::VP_AND, VT, Custom); 873 setOperationAction(ISD::VP_OR, VT, Custom); 874 setOperationAction(ISD::VP_XOR, VT, Custom); 875 setOperationAction(ISD::AND, VT, Custom); 876 setOperationAction(ISD::OR, VT, Custom); 877 setOperationAction(ISD::XOR, VT, Custom); 878 continue; 879 } 880 881 // Use SPLAT_VECTOR to prevent type legalization from destroying the 882 // splats when type legalizing i64 scalar on RV32. 883 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 884 // improvements first. 885 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 886 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 887 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 888 } 889 890 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 891 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 892 893 setOperationAction(ISD::MLOAD, VT, Custom); 894 setOperationAction(ISD::MSTORE, VT, Custom); 895 setOperationAction(ISD::MGATHER, VT, Custom); 896 setOperationAction(ISD::MSCATTER, VT, Custom); 897 898 setOperationAction(ISD::VP_LOAD, VT, Custom); 899 setOperationAction(ISD::VP_STORE, VT, Custom); 900 setOperationAction(ISD::VP_GATHER, VT, Custom); 901 setOperationAction(ISD::VP_SCATTER, VT, Custom); 902 903 setOperationAction(ISD::ADD, VT, Custom); 904 setOperationAction(ISD::MUL, VT, Custom); 905 setOperationAction(ISD::SUB, VT, Custom); 906 setOperationAction(ISD::AND, VT, Custom); 907 setOperationAction(ISD::OR, VT, Custom); 908 setOperationAction(ISD::XOR, VT, Custom); 909 setOperationAction(ISD::SDIV, VT, Custom); 910 setOperationAction(ISD::SREM, VT, Custom); 911 setOperationAction(ISD::UDIV, VT, Custom); 912 setOperationAction(ISD::UREM, VT, Custom); 913 setOperationAction(ISD::SHL, VT, Custom); 914 setOperationAction(ISD::SRA, VT, Custom); 915 setOperationAction(ISD::SRL, VT, Custom); 916 917 setOperationAction(ISD::SMIN, VT, Custom); 918 setOperationAction(ISD::SMAX, VT, Custom); 919 setOperationAction(ISD::UMIN, VT, Custom); 920 setOperationAction(ISD::UMAX, VT, Custom); 921 setOperationAction(ISD::ABS, VT, Custom); 922 923 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 924 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) { 925 setOperationAction(ISD::MULHS, VT, Custom); 926 setOperationAction(ISD::MULHU, VT, Custom); 927 } 928 929 setOperationAction(ISD::SADDSAT, VT, Custom); 930 setOperationAction(ISD::UADDSAT, VT, Custom); 931 setOperationAction(ISD::SSUBSAT, VT, Custom); 932 setOperationAction(ISD::USUBSAT, VT, Custom); 933 934 setOperationAction(ISD::VSELECT, VT, Custom); 935 setOperationAction(ISD::SELECT_CC, VT, Expand); 936 937 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 938 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 939 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 940 941 // Custom-lower reduction operations to set up the corresponding custom 942 // nodes' operands. 943 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 944 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 945 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 946 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 947 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 948 949 for (unsigned VPOpc : IntegerVPOps) 950 setOperationAction(VPOpc, VT, Custom); 951 952 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 953 // type that can represent the value exactly. 954 if (VT.getVectorElementType() != MVT::i64) { 955 MVT FloatEltVT = 956 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 957 EVT FloatVT = 958 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 959 if (isTypeLegal(FloatVT)) { 960 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom); 961 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom); 962 } 963 } 964 } 965 966 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 967 if (!useRVVForFixedLengthVectorVT(VT)) 968 continue; 969 970 // By default everything must be expanded. 971 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 972 setOperationAction(Op, VT, Expand); 973 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 974 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 975 setTruncStoreAction(VT, OtherVT, Expand); 976 } 977 978 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 979 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 980 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 981 982 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 983 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 984 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 985 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 986 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 987 988 setOperationAction(ISD::LOAD, VT, Custom); 989 setOperationAction(ISD::STORE, VT, Custom); 990 setOperationAction(ISD::MLOAD, VT, Custom); 991 setOperationAction(ISD::MSTORE, VT, Custom); 992 setOperationAction(ISD::MGATHER, VT, Custom); 993 setOperationAction(ISD::MSCATTER, VT, Custom); 994 995 setOperationAction(ISD::VP_LOAD, VT, Custom); 996 setOperationAction(ISD::VP_STORE, VT, Custom); 997 setOperationAction(ISD::VP_GATHER, VT, Custom); 998 setOperationAction(ISD::VP_SCATTER, VT, Custom); 999 1000 setOperationAction(ISD::FADD, VT, Custom); 1001 setOperationAction(ISD::FSUB, VT, Custom); 1002 setOperationAction(ISD::FMUL, VT, Custom); 1003 setOperationAction(ISD::FDIV, VT, Custom); 1004 setOperationAction(ISD::FNEG, VT, Custom); 1005 setOperationAction(ISD::FABS, VT, Custom); 1006 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 1007 setOperationAction(ISD::FSQRT, VT, Custom); 1008 setOperationAction(ISD::FMA, VT, Custom); 1009 setOperationAction(ISD::FMINNUM, VT, Custom); 1010 setOperationAction(ISD::FMAXNUM, VT, Custom); 1011 1012 setOperationAction(ISD::FP_ROUND, VT, Custom); 1013 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1014 1015 setOperationAction(ISD::FTRUNC, VT, Custom); 1016 setOperationAction(ISD::FCEIL, VT, Custom); 1017 setOperationAction(ISD::FFLOOR, VT, Custom); 1018 1019 for (auto CC : VFPCCToExpand) 1020 setCondCodeAction(CC, VT, Expand); 1021 1022 setOperationAction(ISD::VSELECT, VT, Custom); 1023 setOperationAction(ISD::SELECT, VT, Custom); 1024 setOperationAction(ISD::SELECT_CC, VT, Expand); 1025 1026 setOperationAction(ISD::BITCAST, VT, Custom); 1027 1028 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1029 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1030 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1031 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1032 1033 for (unsigned VPOpc : FloatingPointVPOps) 1034 setOperationAction(VPOpc, VT, Custom); 1035 } 1036 1037 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 1038 setOperationAction(ISD::BITCAST, MVT::i8, Custom); 1039 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 1040 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 1041 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1042 if (Subtarget.hasStdExtZfh()) 1043 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 1044 if (Subtarget.hasStdExtF()) 1045 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 1046 if (Subtarget.hasStdExtD()) 1047 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 1048 } 1049 } 1050 1051 // Function alignments. 1052 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 1053 setMinFunctionAlignment(FunctionAlignment); 1054 setPrefFunctionAlignment(FunctionAlignment); 1055 1056 setMinimumJumpTableEntries(5); 1057 1058 // Jumps are expensive, compared to logic 1059 setJumpIsExpensive(); 1060 1061 setTargetDAGCombine(ISD::ADD); 1062 setTargetDAGCombine(ISD::SUB); 1063 setTargetDAGCombine(ISD::AND); 1064 setTargetDAGCombine(ISD::OR); 1065 setTargetDAGCombine(ISD::XOR); 1066 setTargetDAGCombine(ISD::ANY_EXTEND); 1067 if (Subtarget.hasStdExtF()) { 1068 setTargetDAGCombine(ISD::ZERO_EXTEND); 1069 setTargetDAGCombine(ISD::FP_TO_SINT); 1070 setTargetDAGCombine(ISD::FP_TO_UINT); 1071 setTargetDAGCombine(ISD::FP_TO_SINT_SAT); 1072 setTargetDAGCombine(ISD::FP_TO_UINT_SAT); 1073 } 1074 if (Subtarget.hasVInstructions()) { 1075 setTargetDAGCombine(ISD::FCOPYSIGN); 1076 setTargetDAGCombine(ISD::MGATHER); 1077 setTargetDAGCombine(ISD::MSCATTER); 1078 setTargetDAGCombine(ISD::VP_GATHER); 1079 setTargetDAGCombine(ISD::VP_SCATTER); 1080 setTargetDAGCombine(ISD::SRA); 1081 setTargetDAGCombine(ISD::SRL); 1082 setTargetDAGCombine(ISD::SHL); 1083 setTargetDAGCombine(ISD::STORE); 1084 } 1085 1086 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 1087 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 1088 } 1089 1090 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 1091 LLVMContext &Context, 1092 EVT VT) const { 1093 if (!VT.isVector()) 1094 return getPointerTy(DL); 1095 if (Subtarget.hasVInstructions() && 1096 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 1097 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 1098 return VT.changeVectorElementTypeToInteger(); 1099 } 1100 1101 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 1102 return Subtarget.getXLenVT(); 1103 } 1104 1105 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1106 const CallInst &I, 1107 MachineFunction &MF, 1108 unsigned Intrinsic) const { 1109 auto &DL = I.getModule()->getDataLayout(); 1110 switch (Intrinsic) { 1111 default: 1112 return false; 1113 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1114 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1115 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1116 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1117 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1118 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1119 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1120 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1121 case Intrinsic::riscv_masked_cmpxchg_i32: { 1122 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 1123 Info.opc = ISD::INTRINSIC_W_CHAIN; 1124 Info.memVT = MVT::getVT(PtrTy->getPointerElementType()); 1125 Info.ptrVal = I.getArgOperand(0); 1126 Info.offset = 0; 1127 Info.align = Align(4); 1128 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1129 MachineMemOperand::MOVolatile; 1130 return true; 1131 } 1132 case Intrinsic::riscv_masked_strided_load: 1133 Info.opc = ISD::INTRINSIC_W_CHAIN; 1134 Info.ptrVal = I.getArgOperand(1); 1135 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1136 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1137 Info.size = MemoryLocation::UnknownSize; 1138 Info.flags |= MachineMemOperand::MOLoad; 1139 return true; 1140 case Intrinsic::riscv_masked_strided_store: 1141 Info.opc = ISD::INTRINSIC_VOID; 1142 Info.ptrVal = I.getArgOperand(1); 1143 Info.memVT = 1144 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1145 Info.align = Align( 1146 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1147 8); 1148 Info.size = MemoryLocation::UnknownSize; 1149 Info.flags |= MachineMemOperand::MOStore; 1150 return true; 1151 } 1152 } 1153 1154 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1155 const AddrMode &AM, Type *Ty, 1156 unsigned AS, 1157 Instruction *I) const { 1158 // No global is ever allowed as a base. 1159 if (AM.BaseGV) 1160 return false; 1161 1162 // Require a 12-bit signed offset. 1163 if (!isInt<12>(AM.BaseOffs)) 1164 return false; 1165 1166 switch (AM.Scale) { 1167 case 0: // "r+i" or just "i", depending on HasBaseReg. 1168 break; 1169 case 1: 1170 if (!AM.HasBaseReg) // allow "r+i". 1171 break; 1172 return false; // disallow "r+r" or "r+r+i". 1173 default: 1174 return false; 1175 } 1176 1177 return true; 1178 } 1179 1180 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1181 return isInt<12>(Imm); 1182 } 1183 1184 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1185 return isInt<12>(Imm); 1186 } 1187 1188 // On RV32, 64-bit integers are split into their high and low parts and held 1189 // in two different registers, so the trunc is free since the low register can 1190 // just be used. 1191 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1192 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1193 return false; 1194 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1195 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1196 return (SrcBits == 64 && DestBits == 32); 1197 } 1198 1199 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1200 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1201 !SrcVT.isInteger() || !DstVT.isInteger()) 1202 return false; 1203 unsigned SrcBits = SrcVT.getSizeInBits(); 1204 unsigned DestBits = DstVT.getSizeInBits(); 1205 return (SrcBits == 64 && DestBits == 32); 1206 } 1207 1208 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1209 // Zexts are free if they can be combined with a load. 1210 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1211 // poorly with type legalization of compares preferring sext. 1212 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1213 EVT MemVT = LD->getMemoryVT(); 1214 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1215 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1216 LD->getExtensionType() == ISD::ZEXTLOAD)) 1217 return true; 1218 } 1219 1220 return TargetLowering::isZExtFree(Val, VT2); 1221 } 1222 1223 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1224 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1225 } 1226 1227 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1228 return Subtarget.hasStdExtZbb(); 1229 } 1230 1231 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1232 return Subtarget.hasStdExtZbb(); 1233 } 1234 1235 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1236 EVT VT = Y.getValueType(); 1237 1238 // FIXME: Support vectors once we have tests. 1239 if (VT.isVector()) 1240 return false; 1241 1242 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1243 Subtarget.hasStdExtZbkb()) && 1244 !isa<ConstantSDNode>(Y); 1245 } 1246 1247 /// Check if sinking \p I's operands to I's basic block is profitable, because 1248 /// the operands can be folded into a target instruction, e.g. 1249 /// splats of scalars can fold into vector instructions. 1250 bool RISCVTargetLowering::shouldSinkOperands( 1251 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1252 using namespace llvm::PatternMatch; 1253 1254 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1255 return false; 1256 1257 auto IsSinker = [&](Instruction *I, int Operand) { 1258 switch (I->getOpcode()) { 1259 case Instruction::Add: 1260 case Instruction::Sub: 1261 case Instruction::Mul: 1262 case Instruction::And: 1263 case Instruction::Or: 1264 case Instruction::Xor: 1265 case Instruction::FAdd: 1266 case Instruction::FSub: 1267 case Instruction::FMul: 1268 case Instruction::FDiv: 1269 case Instruction::ICmp: 1270 case Instruction::FCmp: 1271 return true; 1272 case Instruction::Shl: 1273 case Instruction::LShr: 1274 case Instruction::AShr: 1275 case Instruction::UDiv: 1276 case Instruction::SDiv: 1277 case Instruction::URem: 1278 case Instruction::SRem: 1279 return Operand == 1; 1280 case Instruction::Call: 1281 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1282 switch (II->getIntrinsicID()) { 1283 case Intrinsic::fma: 1284 return Operand == 0 || Operand == 1; 1285 // FIXME: Our patterns can only match vx/vf instructions when the splat 1286 // it on the RHS, because TableGen doesn't recognize our VP operations 1287 // as commutative. 1288 case Intrinsic::vp_add: 1289 case Intrinsic::vp_mul: 1290 case Intrinsic::vp_and: 1291 case Intrinsic::vp_or: 1292 case Intrinsic::vp_xor: 1293 case Intrinsic::vp_fadd: 1294 case Intrinsic::vp_fmul: 1295 case Intrinsic::vp_shl: 1296 case Intrinsic::vp_lshr: 1297 case Intrinsic::vp_ashr: 1298 case Intrinsic::vp_udiv: 1299 case Intrinsic::vp_sdiv: 1300 case Intrinsic::vp_urem: 1301 case Intrinsic::vp_srem: 1302 return Operand == 1; 1303 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1304 // explicit patterns for both LHS and RHS (as 'vr' versions). 1305 case Intrinsic::vp_sub: 1306 case Intrinsic::vp_fsub: 1307 case Intrinsic::vp_fdiv: 1308 return Operand == 0 || Operand == 1; 1309 default: 1310 return false; 1311 } 1312 } 1313 return false; 1314 default: 1315 return false; 1316 } 1317 }; 1318 1319 for (auto OpIdx : enumerate(I->operands())) { 1320 if (!IsSinker(I, OpIdx.index())) 1321 continue; 1322 1323 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1324 // Make sure we are not already sinking this operand 1325 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1326 continue; 1327 1328 // We are looking for a splat that can be sunk. 1329 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1330 m_Undef(), m_ZeroMask()))) 1331 continue; 1332 1333 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1334 // and vector registers 1335 for (Use &U : Op->uses()) { 1336 Instruction *Insn = cast<Instruction>(U.getUser()); 1337 if (!IsSinker(Insn, U.getOperandNo())) 1338 return false; 1339 } 1340 1341 Ops.push_back(&Op->getOperandUse(0)); 1342 Ops.push_back(&OpIdx.value()); 1343 } 1344 return true; 1345 } 1346 1347 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1348 bool ForCodeSize) const { 1349 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1350 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1351 return false; 1352 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1353 return false; 1354 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1355 return false; 1356 return Imm.isZero(); 1357 } 1358 1359 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1360 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1361 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1362 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1363 } 1364 1365 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1366 CallingConv::ID CC, 1367 EVT VT) const { 1368 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1369 // We might still end up using a GPR but that will be decided based on ABI. 1370 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1371 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1372 return MVT::f32; 1373 1374 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1375 } 1376 1377 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1378 CallingConv::ID CC, 1379 EVT VT) const { 1380 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1381 // We might still end up using a GPR but that will be decided based on ABI. 1382 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1383 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1384 return 1; 1385 1386 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1387 } 1388 1389 // Changes the condition code and swaps operands if necessary, so the SetCC 1390 // operation matches one of the comparisons supported directly by branches 1391 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1392 // with 1/-1. 1393 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1394 ISD::CondCode &CC, SelectionDAG &DAG) { 1395 // Convert X > -1 to X >= 0. 1396 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1397 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1398 CC = ISD::SETGE; 1399 return; 1400 } 1401 // Convert X < 1 to 0 >= X. 1402 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1403 RHS = LHS; 1404 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1405 CC = ISD::SETGE; 1406 return; 1407 } 1408 1409 switch (CC) { 1410 default: 1411 break; 1412 case ISD::SETGT: 1413 case ISD::SETLE: 1414 case ISD::SETUGT: 1415 case ISD::SETULE: 1416 CC = ISD::getSetCCSwappedOperands(CC); 1417 std::swap(LHS, RHS); 1418 break; 1419 } 1420 } 1421 1422 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1423 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1424 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1425 if (VT.getVectorElementType() == MVT::i1) 1426 KnownSize *= 8; 1427 1428 switch (KnownSize) { 1429 default: 1430 llvm_unreachable("Invalid LMUL."); 1431 case 8: 1432 return RISCVII::VLMUL::LMUL_F8; 1433 case 16: 1434 return RISCVII::VLMUL::LMUL_F4; 1435 case 32: 1436 return RISCVII::VLMUL::LMUL_F2; 1437 case 64: 1438 return RISCVII::VLMUL::LMUL_1; 1439 case 128: 1440 return RISCVII::VLMUL::LMUL_2; 1441 case 256: 1442 return RISCVII::VLMUL::LMUL_4; 1443 case 512: 1444 return RISCVII::VLMUL::LMUL_8; 1445 } 1446 } 1447 1448 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1449 switch (LMul) { 1450 default: 1451 llvm_unreachable("Invalid LMUL."); 1452 case RISCVII::VLMUL::LMUL_F8: 1453 case RISCVII::VLMUL::LMUL_F4: 1454 case RISCVII::VLMUL::LMUL_F2: 1455 case RISCVII::VLMUL::LMUL_1: 1456 return RISCV::VRRegClassID; 1457 case RISCVII::VLMUL::LMUL_2: 1458 return RISCV::VRM2RegClassID; 1459 case RISCVII::VLMUL::LMUL_4: 1460 return RISCV::VRM4RegClassID; 1461 case RISCVII::VLMUL::LMUL_8: 1462 return RISCV::VRM8RegClassID; 1463 } 1464 } 1465 1466 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1467 RISCVII::VLMUL LMUL = getLMUL(VT); 1468 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1469 LMUL == RISCVII::VLMUL::LMUL_F4 || 1470 LMUL == RISCVII::VLMUL::LMUL_F2 || 1471 LMUL == RISCVII::VLMUL::LMUL_1) { 1472 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1473 "Unexpected subreg numbering"); 1474 return RISCV::sub_vrm1_0 + Index; 1475 } 1476 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1477 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1478 "Unexpected subreg numbering"); 1479 return RISCV::sub_vrm2_0 + Index; 1480 } 1481 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1482 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1483 "Unexpected subreg numbering"); 1484 return RISCV::sub_vrm4_0 + Index; 1485 } 1486 llvm_unreachable("Invalid vector type."); 1487 } 1488 1489 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1490 if (VT.getVectorElementType() == MVT::i1) 1491 return RISCV::VRRegClassID; 1492 return getRegClassIDForLMUL(getLMUL(VT)); 1493 } 1494 1495 // Attempt to decompose a subvector insert/extract between VecVT and 1496 // SubVecVT via subregister indices. Returns the subregister index that 1497 // can perform the subvector insert/extract with the given element index, as 1498 // well as the index corresponding to any leftover subvectors that must be 1499 // further inserted/extracted within the register class for SubVecVT. 1500 std::pair<unsigned, unsigned> 1501 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1502 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1503 const RISCVRegisterInfo *TRI) { 1504 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1505 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1506 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1507 "Register classes not ordered"); 1508 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1509 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1510 // Try to compose a subregister index that takes us from the incoming 1511 // LMUL>1 register class down to the outgoing one. At each step we half 1512 // the LMUL: 1513 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1514 // Note that this is not guaranteed to find a subregister index, such as 1515 // when we are extracting from one VR type to another. 1516 unsigned SubRegIdx = RISCV::NoSubRegister; 1517 for (const unsigned RCID : 1518 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1519 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1520 VecVT = VecVT.getHalfNumVectorElementsVT(); 1521 bool IsHi = 1522 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1523 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1524 getSubregIndexByMVT(VecVT, IsHi)); 1525 if (IsHi) 1526 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1527 } 1528 return {SubRegIdx, InsertExtractIdx}; 1529 } 1530 1531 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1532 // stores for those types. 1533 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1534 return !Subtarget.useRVVForFixedLengthVectors() || 1535 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1536 } 1537 1538 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1539 if (ScalarTy->isPointerTy()) 1540 return true; 1541 1542 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1543 ScalarTy->isIntegerTy(32)) 1544 return true; 1545 1546 if (ScalarTy->isIntegerTy(64)) 1547 return Subtarget.hasVInstructionsI64(); 1548 1549 if (ScalarTy->isHalfTy()) 1550 return Subtarget.hasVInstructionsF16(); 1551 if (ScalarTy->isFloatTy()) 1552 return Subtarget.hasVInstructionsF32(); 1553 if (ScalarTy->isDoubleTy()) 1554 return Subtarget.hasVInstructionsF64(); 1555 1556 return false; 1557 } 1558 1559 static SDValue getVLOperand(SDValue Op) { 1560 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1561 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1562 "Unexpected opcode"); 1563 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1564 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1565 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1566 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1567 if (!II) 1568 return SDValue(); 1569 return Op.getOperand(II->VLOperand + 1 + HasChain); 1570 } 1571 1572 static bool useRVVForFixedLengthVectorVT(MVT VT, 1573 const RISCVSubtarget &Subtarget) { 1574 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1575 if (!Subtarget.useRVVForFixedLengthVectors()) 1576 return false; 1577 1578 // We only support a set of vector types with a consistent maximum fixed size 1579 // across all supported vector element types to avoid legalization issues. 1580 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1581 // fixed-length vector type we support is 1024 bytes. 1582 if (VT.getFixedSizeInBits() > 1024 * 8) 1583 return false; 1584 1585 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1586 1587 MVT EltVT = VT.getVectorElementType(); 1588 1589 // Don't use RVV for vectors we cannot scalarize if required. 1590 switch (EltVT.SimpleTy) { 1591 // i1 is supported but has different rules. 1592 default: 1593 return false; 1594 case MVT::i1: 1595 // Masks can only use a single register. 1596 if (VT.getVectorNumElements() > MinVLen) 1597 return false; 1598 MinVLen /= 8; 1599 break; 1600 case MVT::i8: 1601 case MVT::i16: 1602 case MVT::i32: 1603 break; 1604 case MVT::i64: 1605 if (!Subtarget.hasVInstructionsI64()) 1606 return false; 1607 break; 1608 case MVT::f16: 1609 if (!Subtarget.hasVInstructionsF16()) 1610 return false; 1611 break; 1612 case MVT::f32: 1613 if (!Subtarget.hasVInstructionsF32()) 1614 return false; 1615 break; 1616 case MVT::f64: 1617 if (!Subtarget.hasVInstructionsF64()) 1618 return false; 1619 break; 1620 } 1621 1622 // Reject elements larger than ELEN. 1623 if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors()) 1624 return false; 1625 1626 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1627 // Don't use RVV for types that don't fit. 1628 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1629 return false; 1630 1631 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1632 // the base fixed length RVV support in place. 1633 if (!VT.isPow2VectorType()) 1634 return false; 1635 1636 return true; 1637 } 1638 1639 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1640 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1641 } 1642 1643 // Return the largest legal scalable vector type that matches VT's element type. 1644 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1645 const RISCVSubtarget &Subtarget) { 1646 // This may be called before legal types are setup. 1647 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1648 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1649 "Expected legal fixed length vector!"); 1650 1651 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1652 unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors(); 1653 1654 MVT EltVT = VT.getVectorElementType(); 1655 switch (EltVT.SimpleTy) { 1656 default: 1657 llvm_unreachable("unexpected element type for RVV container"); 1658 case MVT::i1: 1659 case MVT::i8: 1660 case MVT::i16: 1661 case MVT::i32: 1662 case MVT::i64: 1663 case MVT::f16: 1664 case MVT::f32: 1665 case MVT::f64: { 1666 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1667 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1668 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1669 unsigned NumElts = 1670 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1671 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1672 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1673 return MVT::getScalableVectorVT(EltVT, NumElts); 1674 } 1675 } 1676 } 1677 1678 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1679 const RISCVSubtarget &Subtarget) { 1680 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1681 Subtarget); 1682 } 1683 1684 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1685 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1686 } 1687 1688 // Grow V to consume an entire RVV register. 1689 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1690 const RISCVSubtarget &Subtarget) { 1691 assert(VT.isScalableVector() && 1692 "Expected to convert into a scalable vector!"); 1693 assert(V.getValueType().isFixedLengthVector() && 1694 "Expected a fixed length vector operand!"); 1695 SDLoc DL(V); 1696 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1697 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1698 } 1699 1700 // Shrink V so it's just big enough to maintain a VT's worth of data. 1701 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1702 const RISCVSubtarget &Subtarget) { 1703 assert(VT.isFixedLengthVector() && 1704 "Expected to convert into a fixed length vector!"); 1705 assert(V.getValueType().isScalableVector() && 1706 "Expected a scalable vector operand!"); 1707 SDLoc DL(V); 1708 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1709 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1710 } 1711 1712 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1713 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1714 // the vector type that it is contained in. 1715 static std::pair<SDValue, SDValue> 1716 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1717 const RISCVSubtarget &Subtarget) { 1718 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1719 MVT XLenVT = Subtarget.getXLenVT(); 1720 SDValue VL = VecVT.isFixedLengthVector() 1721 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1722 : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT); 1723 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1724 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1725 return {Mask, VL}; 1726 } 1727 1728 // As above but assuming the given type is a scalable vector type. 1729 static std::pair<SDValue, SDValue> 1730 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1731 const RISCVSubtarget &Subtarget) { 1732 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1733 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1734 } 1735 1736 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1737 // of either is (currently) supported. This can get us into an infinite loop 1738 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1739 // as a ..., etc. 1740 // Until either (or both) of these can reliably lower any node, reporting that 1741 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1742 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1743 // which is not desirable. 1744 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1745 EVT VT, unsigned DefinedValues) const { 1746 return false; 1747 } 1748 1749 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1750 // Only splats are currently supported. 1751 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1752 return true; 1753 1754 return false; 1755 } 1756 1757 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1758 const RISCVSubtarget &Subtarget) { 1759 // RISCV FP-to-int conversions saturate to the destination register size, but 1760 // don't produce 0 for nan. We can use a conversion instruction and fix the 1761 // nan case with a compare and a select. 1762 SDValue Src = Op.getOperand(0); 1763 1764 EVT DstVT = Op.getValueType(); 1765 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1766 1767 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1768 unsigned Opc; 1769 if (SatVT == DstVT) 1770 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1771 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1772 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1773 else 1774 return SDValue(); 1775 // FIXME: Support other SatVTs by clamping before or after the conversion. 1776 1777 SDLoc DL(Op); 1778 SDValue FpToInt = DAG.getNode( 1779 Opc, DL, DstVT, Src, 1780 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1781 1782 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1783 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1784 } 1785 1786 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1787 // and back. Taking care to avoid converting values that are nan or already 1788 // correct. 1789 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1790 // have FRM dependencies modeled yet. 1791 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1792 MVT VT = Op.getSimpleValueType(); 1793 assert(VT.isVector() && "Unexpected type"); 1794 1795 SDLoc DL(Op); 1796 1797 // Freeze the source since we are increasing the number of uses. 1798 SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0)); 1799 1800 // Truncate to integer and convert back to FP. 1801 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1802 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1803 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1804 1805 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1806 1807 if (Op.getOpcode() == ISD::FCEIL) { 1808 // If the truncated value is the greater than or equal to the original 1809 // value, we've computed the ceil. Otherwise, we went the wrong way and 1810 // need to increase by 1. 1811 // FIXME: This should use a masked operation. Handle here or in isel? 1812 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1813 DAG.getConstantFP(1.0, DL, VT)); 1814 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1815 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1816 } else if (Op.getOpcode() == ISD::FFLOOR) { 1817 // If the truncated value is the less than or equal to the original value, 1818 // we've computed the floor. Otherwise, we went the wrong way and need to 1819 // decrease by 1. 1820 // FIXME: This should use a masked operation. Handle here or in isel? 1821 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1822 DAG.getConstantFP(1.0, DL, VT)); 1823 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1824 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1825 } 1826 1827 // Restore the original sign so that -0.0 is preserved. 1828 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1829 1830 // Determine the largest integer that can be represented exactly. This and 1831 // values larger than it don't have any fractional bits so don't need to 1832 // be converted. 1833 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1834 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1835 APFloat MaxVal = APFloat(FltSem); 1836 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1837 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1838 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1839 1840 // If abs(Src) was larger than MaxVal or nan, keep it. 1841 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1842 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1843 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1844 } 1845 1846 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG, 1847 const RISCVSubtarget &Subtarget) { 1848 MVT VT = Op.getSimpleValueType(); 1849 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1850 1851 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1852 1853 SDLoc DL(Op); 1854 SDValue Mask, VL; 1855 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1856 1857 unsigned Opc = 1858 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 1859 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL); 1860 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1861 } 1862 1863 struct VIDSequence { 1864 int64_t StepNumerator; 1865 unsigned StepDenominator; 1866 int64_t Addend; 1867 }; 1868 1869 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1870 // to the (non-zero) step S and start value X. This can be then lowered as the 1871 // RVV sequence (VID * S) + X, for example. 1872 // The step S is represented as an integer numerator divided by a positive 1873 // denominator. Note that the implementation currently only identifies 1874 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1875 // cannot detect 2/3, for example. 1876 // Note that this method will also match potentially unappealing index 1877 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1878 // determine whether this is worth generating code for. 1879 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1880 unsigned NumElts = Op.getNumOperands(); 1881 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1882 if (!Op.getValueType().isInteger()) 1883 return None; 1884 1885 Optional<unsigned> SeqStepDenom; 1886 Optional<int64_t> SeqStepNum, SeqAddend; 1887 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1888 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1889 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1890 // Assume undef elements match the sequence; we just have to be careful 1891 // when interpolating across them. 1892 if (Op.getOperand(Idx).isUndef()) 1893 continue; 1894 // The BUILD_VECTOR must be all constants. 1895 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1896 return None; 1897 1898 uint64_t Val = Op.getConstantOperandVal(Idx) & 1899 maskTrailingOnes<uint64_t>(EltSizeInBits); 1900 1901 if (PrevElt) { 1902 // Calculate the step since the last non-undef element, and ensure 1903 // it's consistent across the entire sequence. 1904 unsigned IdxDiff = Idx - PrevElt->second; 1905 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1906 1907 // A zero-value value difference means that we're somewhere in the middle 1908 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1909 // step change before evaluating the sequence. 1910 if (ValDiff != 0) { 1911 int64_t Remainder = ValDiff % IdxDiff; 1912 // Normalize the step if it's greater than 1. 1913 if (Remainder != ValDiff) { 1914 // The difference must cleanly divide the element span. 1915 if (Remainder != 0) 1916 return None; 1917 ValDiff /= IdxDiff; 1918 IdxDiff = 1; 1919 } 1920 1921 if (!SeqStepNum) 1922 SeqStepNum = ValDiff; 1923 else if (ValDiff != SeqStepNum) 1924 return None; 1925 1926 if (!SeqStepDenom) 1927 SeqStepDenom = IdxDiff; 1928 else if (IdxDiff != *SeqStepDenom) 1929 return None; 1930 } 1931 } 1932 1933 // Record and/or check any addend. 1934 if (SeqStepNum && SeqStepDenom) { 1935 uint64_t ExpectedVal = 1936 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1937 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1938 if (!SeqAddend) 1939 SeqAddend = Addend; 1940 else if (SeqAddend != Addend) 1941 return None; 1942 } 1943 1944 // Record this non-undef element for later. 1945 if (!PrevElt || PrevElt->first != Val) 1946 PrevElt = std::make_pair(Val, Idx); 1947 } 1948 // We need to have logged both a step and an addend for this to count as 1949 // a legal index sequence. 1950 if (!SeqStepNum || !SeqStepDenom || !SeqAddend) 1951 return None; 1952 1953 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1954 } 1955 1956 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1957 const RISCVSubtarget &Subtarget) { 1958 MVT VT = Op.getSimpleValueType(); 1959 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1960 1961 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1962 1963 SDLoc DL(Op); 1964 SDValue Mask, VL; 1965 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1966 1967 MVT XLenVT = Subtarget.getXLenVT(); 1968 unsigned NumElts = Op.getNumOperands(); 1969 1970 if (VT.getVectorElementType() == MVT::i1) { 1971 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1972 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1973 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1974 } 1975 1976 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1977 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1978 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1979 } 1980 1981 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1982 // scalar integer chunks whose bit-width depends on the number of mask 1983 // bits and XLEN. 1984 // First, determine the most appropriate scalar integer type to use. This 1985 // is at most XLenVT, but may be shrunk to a smaller vector element type 1986 // according to the size of the final vector - use i8 chunks rather than 1987 // XLenVT if we're producing a v8i1. This results in more consistent 1988 // codegen across RV32 and RV64. 1989 unsigned NumViaIntegerBits = 1990 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1991 NumViaIntegerBits = std::min(NumViaIntegerBits, 1992 Subtarget.getMaxELENForFixedLengthVectors()); 1993 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1994 // If we have to use more than one INSERT_VECTOR_ELT then this 1995 // optimization is likely to increase code size; avoid peforming it in 1996 // such a case. We can use a load from a constant pool in this case. 1997 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1998 return SDValue(); 1999 // Now we can create our integer vector type. Note that it may be larger 2000 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2001 MVT IntegerViaVecVT = 2002 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2003 divideCeil(NumElts, NumViaIntegerBits)); 2004 2005 uint64_t Bits = 0; 2006 unsigned BitPos = 0, IntegerEltIdx = 0; 2007 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2008 2009 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2010 // Once we accumulate enough bits to fill our scalar type, insert into 2011 // our vector and clear our accumulated data. 2012 if (I != 0 && I % NumViaIntegerBits == 0) { 2013 if (NumViaIntegerBits <= 32) 2014 Bits = SignExtend64(Bits, 32); 2015 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2016 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2017 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2018 Bits = 0; 2019 BitPos = 0; 2020 IntegerEltIdx++; 2021 } 2022 SDValue V = Op.getOperand(I); 2023 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2024 Bits |= ((uint64_t)BitValue << BitPos); 2025 } 2026 2027 // Insert the (remaining) scalar value into position in our integer 2028 // vector type. 2029 if (NumViaIntegerBits <= 32) 2030 Bits = SignExtend64(Bits, 32); 2031 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2032 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2033 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2034 2035 if (NumElts < NumViaIntegerBits) { 2036 // If we're producing a smaller vector than our minimum legal integer 2037 // type, bitcast to the equivalent (known-legal) mask type, and extract 2038 // our final mask. 2039 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2040 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2041 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2042 DAG.getConstant(0, DL, XLenVT)); 2043 } else { 2044 // Else we must have produced an integer type with the same size as the 2045 // mask type; bitcast for the final result. 2046 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2047 Vec = DAG.getBitcast(VT, Vec); 2048 } 2049 2050 return Vec; 2051 } 2052 2053 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2054 // vector type, we have a legal equivalently-sized i8 type, so we can use 2055 // that. 2056 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2057 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2058 2059 SDValue WideVec; 2060 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2061 // For a splat, perform a scalar truncate before creating the wider 2062 // vector. 2063 assert(Splat.getValueType() == XLenVT && 2064 "Unexpected type for i1 splat value"); 2065 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2066 DAG.getConstant(1, DL, XLenVT)); 2067 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2068 } else { 2069 SmallVector<SDValue, 8> Ops(Op->op_values()); 2070 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2071 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2072 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2073 } 2074 2075 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2076 } 2077 2078 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2079 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2080 : RISCVISD::VMV_V_X_VL; 2081 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 2082 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2083 } 2084 2085 // Try and match index sequences, which we can lower to the vid instruction 2086 // with optional modifications. An all-undef vector is matched by 2087 // getSplatValue, above. 2088 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2089 int64_t StepNumerator = SimpleVID->StepNumerator; 2090 unsigned StepDenominator = SimpleVID->StepDenominator; 2091 int64_t Addend = SimpleVID->Addend; 2092 2093 assert(StepNumerator != 0 && "Invalid step"); 2094 bool Negate = false; 2095 int64_t SplatStepVal = StepNumerator; 2096 unsigned StepOpcode = ISD::MUL; 2097 if (StepNumerator != 1) { 2098 if (isPowerOf2_64(std::abs(StepNumerator))) { 2099 Negate = StepNumerator < 0; 2100 StepOpcode = ISD::SHL; 2101 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2102 } 2103 } 2104 2105 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2106 // threshold since it's the immediate value many RVV instructions accept. 2107 // There is no vmul.vi instruction so ensure multiply constant can fit in 2108 // a single addi instruction. 2109 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2110 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2111 isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) { 2112 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2113 // Convert right out of the scalable type so we can use standard ISD 2114 // nodes for the rest of the computation. If we used scalable types with 2115 // these, we'd lose the fixed-length vector info and generate worse 2116 // vsetvli code. 2117 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2118 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2119 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2120 SDValue SplatStep = DAG.getSplatVector( 2121 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2122 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2123 } 2124 if (StepDenominator != 1) { 2125 SDValue SplatStep = DAG.getSplatVector( 2126 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2127 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2128 } 2129 if (Addend != 0 || Negate) { 2130 SDValue SplatAddend = 2131 DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2132 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2133 } 2134 return VID; 2135 } 2136 } 2137 2138 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2139 // when re-interpreted as a vector with a larger element type. For example, 2140 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2141 // could be instead splat as 2142 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2143 // TODO: This optimization could also work on non-constant splats, but it 2144 // would require bit-manipulation instructions to construct the splat value. 2145 SmallVector<SDValue> Sequence; 2146 unsigned EltBitSize = VT.getScalarSizeInBits(); 2147 const auto *BV = cast<BuildVectorSDNode>(Op); 2148 if (VT.isInteger() && EltBitSize < 64 && 2149 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2150 BV->getRepeatedSequence(Sequence) && 2151 (Sequence.size() * EltBitSize) <= 64) { 2152 unsigned SeqLen = Sequence.size(); 2153 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2154 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2155 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2156 ViaIntVT == MVT::i64) && 2157 "Unexpected sequence type"); 2158 2159 unsigned EltIdx = 0; 2160 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2161 uint64_t SplatValue = 0; 2162 // Construct the amalgamated value which can be splatted as this larger 2163 // vector type. 2164 for (const auto &SeqV : Sequence) { 2165 if (!SeqV.isUndef()) 2166 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2167 << (EltIdx * EltBitSize)); 2168 EltIdx++; 2169 } 2170 2171 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2172 // achieve better constant materializion. 2173 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2174 SplatValue = SignExtend64(SplatValue, 32); 2175 2176 // Since we can't introduce illegal i64 types at this stage, we can only 2177 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2178 // way we can use RVV instructions to splat. 2179 assert((ViaIntVT.bitsLE(XLenVT) || 2180 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2181 "Unexpected bitcast sequence"); 2182 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2183 SDValue ViaVL = 2184 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2185 MVT ViaContainerVT = 2186 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2187 SDValue Splat = 2188 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2189 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2190 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2191 return DAG.getBitcast(VT, Splat); 2192 } 2193 } 2194 2195 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2196 // which constitute a large proportion of the elements. In such cases we can 2197 // splat a vector with the dominant element and make up the shortfall with 2198 // INSERT_VECTOR_ELTs. 2199 // Note that this includes vectors of 2 elements by association. The 2200 // upper-most element is the "dominant" one, allowing us to use a splat to 2201 // "insert" the upper element, and an insert of the lower element at position 2202 // 0, which improves codegen. 2203 SDValue DominantValue; 2204 unsigned MostCommonCount = 0; 2205 DenseMap<SDValue, unsigned> ValueCounts; 2206 unsigned NumUndefElts = 2207 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2208 2209 // Track the number of scalar loads we know we'd be inserting, estimated as 2210 // any non-zero floating-point constant. Other kinds of element are either 2211 // already in registers or are materialized on demand. The threshold at which 2212 // a vector load is more desirable than several scalar materializion and 2213 // vector-insertion instructions is not known. 2214 unsigned NumScalarLoads = 0; 2215 2216 for (SDValue V : Op->op_values()) { 2217 if (V.isUndef()) 2218 continue; 2219 2220 ValueCounts.insert(std::make_pair(V, 0)); 2221 unsigned &Count = ValueCounts[V]; 2222 2223 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2224 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2225 2226 // Is this value dominant? In case of a tie, prefer the highest element as 2227 // it's cheaper to insert near the beginning of a vector than it is at the 2228 // end. 2229 if (++Count >= MostCommonCount) { 2230 DominantValue = V; 2231 MostCommonCount = Count; 2232 } 2233 } 2234 2235 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2236 unsigned NumDefElts = NumElts - NumUndefElts; 2237 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2238 2239 // Don't perform this optimization when optimizing for size, since 2240 // materializing elements and inserting them tends to cause code bloat. 2241 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2242 ((MostCommonCount > DominantValueCountThreshold) || 2243 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2244 // Start by splatting the most common element. 2245 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2246 2247 DenseSet<SDValue> Processed{DominantValue}; 2248 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2249 for (const auto &OpIdx : enumerate(Op->ops())) { 2250 const SDValue &V = OpIdx.value(); 2251 if (V.isUndef() || !Processed.insert(V).second) 2252 continue; 2253 if (ValueCounts[V] == 1) { 2254 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2255 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2256 } else { 2257 // Blend in all instances of this value using a VSELECT, using a 2258 // mask where each bit signals whether that element is the one 2259 // we're after. 2260 SmallVector<SDValue> Ops; 2261 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2262 return DAG.getConstant(V == V1, DL, XLenVT); 2263 }); 2264 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2265 DAG.getBuildVector(SelMaskTy, DL, Ops), 2266 DAG.getSplatBuildVector(VT, DL, V), Vec); 2267 } 2268 } 2269 2270 return Vec; 2271 } 2272 2273 return SDValue(); 2274 } 2275 2276 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo, 2277 SDValue Hi, SDValue VL, SelectionDAG &DAG) { 2278 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2279 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2280 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2281 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2282 // node in order to try and match RVV vector/scalar instructions. 2283 if ((LoC >> 31) == HiC) 2284 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2285 2286 // If vl is equal to VLMax and Hi constant is equal to Lo, we could use 2287 // vmv.v.x whose EEW = 32 to lower it. 2288 auto *Const = dyn_cast<ConstantSDNode>(VL); 2289 if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) { 2290 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2291 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2292 // access the subtarget here now. 2293 auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL); 2294 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2295 } 2296 } 2297 2298 // Fall back to a stack store and stride x0 vector load. 2299 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL); 2300 } 2301 2302 // Called by type legalization to handle splat of i64 on RV32. 2303 // FIXME: We can optimize this when the type has sign or zero bits in one 2304 // of the halves. 2305 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2306 SDValue VL, SelectionDAG &DAG) { 2307 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2308 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2309 DAG.getConstant(0, DL, MVT::i32)); 2310 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2311 DAG.getConstant(1, DL, MVT::i32)); 2312 return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG); 2313 } 2314 2315 // This function lowers a splat of a scalar operand Splat with the vector 2316 // length VL. It ensures the final sequence is type legal, which is useful when 2317 // lowering a splat after type legalization. 2318 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL, 2319 SelectionDAG &DAG, 2320 const RISCVSubtarget &Subtarget) { 2321 if (VT.isFloatingPoint()) { 2322 // If VL is 1, we could use vfmv.s.f. 2323 if (isOneConstant(VL)) 2324 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT), 2325 Scalar, VL); 2326 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL); 2327 } 2328 2329 MVT XLenVT = Subtarget.getXLenVT(); 2330 2331 // Simplest case is that the operand needs to be promoted to XLenVT. 2332 if (Scalar.getValueType().bitsLE(XLenVT)) { 2333 // If the operand is a constant, sign extend to increase our chances 2334 // of being able to use a .vi instruction. ANY_EXTEND would become a 2335 // a zero extend and the simm5 check in isel would fail. 2336 // FIXME: Should we ignore the upper bits in isel instead? 2337 unsigned ExtOpc = 2338 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2339 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2340 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2341 // If VL is 1 and the scalar value won't benefit from immediate, we could 2342 // use vmv.s.x. 2343 if (isOneConstant(VL) && 2344 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2345 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar, 2346 VL); 2347 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL); 2348 } 2349 2350 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2351 "Unexpected scalar for splat lowering!"); 2352 2353 if (isOneConstant(VL) && isNullConstant(Scalar)) 2354 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), 2355 DAG.getConstant(0, DL, XLenVT), VL); 2356 2357 // Otherwise use the more complicated splatting algorithm. 2358 return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2359 } 2360 2361 // Is the mask a slidedown that shifts in undefs. 2362 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) { 2363 int Size = Mask.size(); 2364 2365 // Elements shifted in should be undef. 2366 auto CheckUndefs = [&](int Shift) { 2367 for (int i = Size - Shift; i != Size; ++i) 2368 if (Mask[i] >= 0) 2369 return false; 2370 return true; 2371 }; 2372 2373 // Elements should be shifted or undef. 2374 auto MatchShift = [&](int Shift) { 2375 for (int i = 0; i != Size - Shift; ++i) 2376 if (Mask[i] >= 0 && Mask[i] != Shift + i) 2377 return false; 2378 return true; 2379 }; 2380 2381 // Try all possible shifts. 2382 for (int Shift = 1; Shift != Size; ++Shift) 2383 if (CheckUndefs(Shift) && MatchShift(Shift)) 2384 return Shift; 2385 2386 // No match. 2387 return -1; 2388 } 2389 2390 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2391 const RISCVSubtarget &Subtarget) { 2392 // We need to be able to widen elements to the next larger integer type. 2393 if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors()) 2394 return false; 2395 2396 int Size = Mask.size(); 2397 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2398 2399 int Srcs[] = {-1, -1}; 2400 for (int i = 0; i != Size; ++i) { 2401 // Ignore undef elements. 2402 if (Mask[i] < 0) 2403 continue; 2404 2405 // Is this an even or odd element. 2406 int Pol = i % 2; 2407 2408 // Ensure we consistently use the same source for this element polarity. 2409 int Src = Mask[i] / Size; 2410 if (Srcs[Pol] < 0) 2411 Srcs[Pol] = Src; 2412 if (Srcs[Pol] != Src) 2413 return false; 2414 2415 // Make sure the element within the source is appropriate for this element 2416 // in the destination. 2417 int Elt = Mask[i] % Size; 2418 if (Elt != i / 2) 2419 return false; 2420 } 2421 2422 // We need to find a source for each polarity and they can't be the same. 2423 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2424 return false; 2425 2426 // Swap the sources if the second source was in the even polarity. 2427 SwapSources = Srcs[0] > Srcs[1]; 2428 2429 return true; 2430 } 2431 2432 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2433 const RISCVSubtarget &Subtarget) { 2434 SDValue V1 = Op.getOperand(0); 2435 SDValue V2 = Op.getOperand(1); 2436 SDLoc DL(Op); 2437 MVT XLenVT = Subtarget.getXLenVT(); 2438 MVT VT = Op.getSimpleValueType(); 2439 unsigned NumElts = VT.getVectorNumElements(); 2440 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2441 2442 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2443 2444 SDValue TrueMask, VL; 2445 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2446 2447 if (SVN->isSplat()) { 2448 const int Lane = SVN->getSplatIndex(); 2449 if (Lane >= 0) { 2450 MVT SVT = VT.getVectorElementType(); 2451 2452 // Turn splatted vector load into a strided load with an X0 stride. 2453 SDValue V = V1; 2454 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2455 // with undef. 2456 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2457 int Offset = Lane; 2458 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2459 int OpElements = 2460 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2461 V = V.getOperand(Offset / OpElements); 2462 Offset %= OpElements; 2463 } 2464 2465 // We need to ensure the load isn't atomic or volatile. 2466 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2467 auto *Ld = cast<LoadSDNode>(V); 2468 Offset *= SVT.getStoreSize(); 2469 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2470 TypeSize::Fixed(Offset), DL); 2471 2472 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2473 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2474 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2475 SDValue IntID = 2476 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2477 SDValue Ops[] = {Ld->getChain(), 2478 IntID, 2479 DAG.getUNDEF(ContainerVT), 2480 NewAddr, 2481 DAG.getRegister(RISCV::X0, XLenVT), 2482 VL}; 2483 SDValue NewLoad = DAG.getMemIntrinsicNode( 2484 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2485 DAG.getMachineFunction().getMachineMemOperand( 2486 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2487 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2488 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2489 } 2490 2491 // Otherwise use a scalar load and splat. This will give the best 2492 // opportunity to fold a splat into the operation. ISel can turn it into 2493 // the x0 strided load if we aren't able to fold away the select. 2494 if (SVT.isFloatingPoint()) 2495 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2496 Ld->getPointerInfo().getWithOffset(Offset), 2497 Ld->getOriginalAlign(), 2498 Ld->getMemOperand()->getFlags()); 2499 else 2500 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2501 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2502 Ld->getOriginalAlign(), 2503 Ld->getMemOperand()->getFlags()); 2504 DAG.makeEquivalentMemoryOrdering(Ld, V); 2505 2506 unsigned Opc = 2507 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2508 SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL); 2509 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2510 } 2511 2512 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2513 assert(Lane < (int)NumElts && "Unexpected lane!"); 2514 SDValue Gather = 2515 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2516 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2517 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2518 } 2519 } 2520 2521 ArrayRef<int> Mask = SVN->getMask(); 2522 2523 // Try to match as a slidedown. 2524 int SlideAmt = matchShuffleAsSlideDown(Mask); 2525 if (SlideAmt >= 0) { 2526 // TODO: Should we reduce the VL to account for the upper undef elements? 2527 // Requires additional vsetvlis, but might be faster to execute. 2528 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2529 SDValue SlideDown = 2530 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 2531 DAG.getUNDEF(ContainerVT), V1, 2532 DAG.getConstant(SlideAmt, DL, XLenVT), 2533 TrueMask, VL); 2534 return convertFromScalableVector(VT, SlideDown, DAG, Subtarget); 2535 } 2536 2537 // Detect an interleave shuffle and lower to 2538 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2539 bool SwapSources; 2540 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2541 // Swap sources if needed. 2542 if (SwapSources) 2543 std::swap(V1, V2); 2544 2545 // Extract the lower half of the vectors. 2546 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2547 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2548 DAG.getConstant(0, DL, XLenVT)); 2549 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2550 DAG.getConstant(0, DL, XLenVT)); 2551 2552 // Double the element width and halve the number of elements in an int type. 2553 unsigned EltBits = VT.getScalarSizeInBits(); 2554 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2555 MVT WideIntVT = 2556 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2557 // Convert this to a scalable vector. We need to base this on the 2558 // destination size to ensure there's always a type with a smaller LMUL. 2559 MVT WideIntContainerVT = 2560 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2561 2562 // Convert sources to scalable vectors with the same element count as the 2563 // larger type. 2564 MVT HalfContainerVT = MVT::getVectorVT( 2565 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2566 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2567 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2568 2569 // Cast sources to integer. 2570 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2571 MVT IntHalfVT = 2572 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2573 V1 = DAG.getBitcast(IntHalfVT, V1); 2574 V2 = DAG.getBitcast(IntHalfVT, V2); 2575 2576 // Freeze V2 since we use it twice and we need to be sure that the add and 2577 // multiply see the same value. 2578 V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2); 2579 2580 // Recreate TrueMask using the widened type's element count. 2581 MVT MaskVT = 2582 MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount()); 2583 TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2584 2585 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2586 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2587 V2, TrueMask, VL); 2588 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2589 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2590 DAG.getAllOnesConstant(DL, XLenVT)); 2591 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2592 V2, Multiplier, TrueMask, VL); 2593 // Add the new copies to our previous addition giving us 2^eltbits copies of 2594 // V2. This is equivalent to shifting V2 left by eltbits. This should 2595 // combine with the vwmulu.vv above to form vwmaccu.vv. 2596 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2597 TrueMask, VL); 2598 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2599 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2600 // vector VT. 2601 ContainerVT = 2602 MVT::getVectorVT(VT.getVectorElementType(), 2603 WideIntContainerVT.getVectorElementCount() * 2); 2604 Add = DAG.getBitcast(ContainerVT, Add); 2605 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2606 } 2607 2608 // Detect shuffles which can be re-expressed as vector selects; these are 2609 // shuffles in which each element in the destination is taken from an element 2610 // at the corresponding index in either source vectors. 2611 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2612 int MaskIndex = MaskIdx.value(); 2613 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2614 }); 2615 2616 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2617 2618 SmallVector<SDValue> MaskVals; 2619 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2620 // merged with a second vrgather. 2621 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2622 2623 // By default we preserve the original operand order, and use a mask to 2624 // select LHS as true and RHS as false. However, since RVV vector selects may 2625 // feature splats but only on the LHS, we may choose to invert our mask and 2626 // instead select between RHS and LHS. 2627 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2628 bool InvertMask = IsSelect == SwapOps; 2629 2630 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2631 // half. 2632 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2633 2634 // Now construct the mask that will be used by the vselect or blended 2635 // vrgather operation. For vrgathers, construct the appropriate indices into 2636 // each vector. 2637 for (int MaskIndex : Mask) { 2638 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2639 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2640 if (!IsSelect) { 2641 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2642 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2643 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2644 : DAG.getUNDEF(XLenVT)); 2645 GatherIndicesRHS.push_back( 2646 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2647 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2648 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2649 ++LHSIndexCounts[MaskIndex]; 2650 if (!IsLHSOrUndefIndex) 2651 ++RHSIndexCounts[MaskIndex - NumElts]; 2652 } 2653 } 2654 2655 if (SwapOps) { 2656 std::swap(V1, V2); 2657 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2658 } 2659 2660 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2661 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2662 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2663 2664 if (IsSelect) 2665 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2666 2667 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2668 // On such a large vector we're unable to use i8 as the index type. 2669 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2670 // may involve vector splitting if we're already at LMUL=8, or our 2671 // user-supplied maximum fixed-length LMUL. 2672 return SDValue(); 2673 } 2674 2675 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2676 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2677 MVT IndexVT = VT.changeTypeToInteger(); 2678 // Since we can't introduce illegal index types at this stage, use i16 and 2679 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2680 // than XLenVT. 2681 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2682 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2683 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2684 } 2685 2686 MVT IndexContainerVT = 2687 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2688 2689 SDValue Gather; 2690 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2691 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2692 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2693 Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget); 2694 } else { 2695 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2696 // If only one index is used, we can use a "splat" vrgather. 2697 // TODO: We can splat the most-common index and fix-up any stragglers, if 2698 // that's beneficial. 2699 if (LHSIndexCounts.size() == 1) { 2700 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2701 Gather = 2702 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2703 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2704 } else { 2705 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2706 LHSIndices = 2707 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2708 2709 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2710 TrueMask, VL); 2711 } 2712 } 2713 2714 // If a second vector operand is used by this shuffle, blend it in with an 2715 // additional vrgather. 2716 if (!V2.isUndef()) { 2717 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2718 // If only one index is used, we can use a "splat" vrgather. 2719 // TODO: We can splat the most-common index and fix-up any stragglers, if 2720 // that's beneficial. 2721 if (RHSIndexCounts.size() == 1) { 2722 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2723 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2724 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2725 } else { 2726 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2727 RHSIndices = 2728 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2729 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2730 VL); 2731 } 2732 2733 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2734 SelectMask = 2735 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2736 2737 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2738 Gather, VL); 2739 } 2740 2741 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2742 } 2743 2744 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2745 SDLoc DL, SelectionDAG &DAG, 2746 const RISCVSubtarget &Subtarget) { 2747 if (VT.isScalableVector()) 2748 return DAG.getFPExtendOrRound(Op, DL, VT); 2749 assert(VT.isFixedLengthVector() && 2750 "Unexpected value type for RVV FP extend/round lowering"); 2751 SDValue Mask, VL; 2752 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2753 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2754 ? RISCVISD::FP_EXTEND_VL 2755 : RISCVISD::FP_ROUND_VL; 2756 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2757 } 2758 2759 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2760 // the exponent. 2761 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2762 MVT VT = Op.getSimpleValueType(); 2763 unsigned EltSize = VT.getScalarSizeInBits(); 2764 SDValue Src = Op.getOperand(0); 2765 SDLoc DL(Op); 2766 2767 // We need a FP type that can represent the value. 2768 // TODO: Use f16 for i8 when possible? 2769 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2770 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2771 2772 // Legal types should have been checked in the RISCVTargetLowering 2773 // constructor. 2774 // TODO: Splitting may make sense in some cases. 2775 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2776 "Expected legal float type!"); 2777 2778 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2779 // The trailing zero count is equal to log2 of this single bit value. 2780 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2781 SDValue Neg = 2782 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2783 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2784 } 2785 2786 // We have a legal FP type, convert to it. 2787 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2788 // Bitcast to integer and shift the exponent to the LSB. 2789 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2790 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2791 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2792 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2793 DAG.getConstant(ShiftAmt, DL, IntVT)); 2794 // Truncate back to original type to allow vnsrl. 2795 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2796 // The exponent contains log2 of the value in biased form. 2797 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2798 2799 // For trailing zeros, we just need to subtract the bias. 2800 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2801 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2802 DAG.getConstant(ExponentBias, DL, VT)); 2803 2804 // For leading zeros, we need to remove the bias and convert from log2 to 2805 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2806 unsigned Adjust = ExponentBias + (EltSize - 1); 2807 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2808 } 2809 2810 // While RVV has alignment restrictions, we should always be able to load as a 2811 // legal equivalently-sized byte-typed vector instead. This method is 2812 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2813 // the load is already correctly-aligned, it returns SDValue(). 2814 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2815 SelectionDAG &DAG) const { 2816 auto *Load = cast<LoadSDNode>(Op); 2817 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2818 2819 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2820 Load->getMemoryVT(), 2821 *Load->getMemOperand())) 2822 return SDValue(); 2823 2824 SDLoc DL(Op); 2825 MVT VT = Op.getSimpleValueType(); 2826 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2827 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2828 "Unexpected unaligned RVV load type"); 2829 MVT NewVT = 2830 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2831 assert(NewVT.isValid() && 2832 "Expecting equally-sized RVV vector types to be legal"); 2833 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2834 Load->getPointerInfo(), Load->getOriginalAlign(), 2835 Load->getMemOperand()->getFlags()); 2836 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2837 } 2838 2839 // While RVV has alignment restrictions, we should always be able to store as a 2840 // legal equivalently-sized byte-typed vector instead. This method is 2841 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2842 // returns SDValue() if the store is already correctly aligned. 2843 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2844 SelectionDAG &DAG) const { 2845 auto *Store = cast<StoreSDNode>(Op); 2846 assert(Store && Store->getValue().getValueType().isVector() && 2847 "Expected vector store"); 2848 2849 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2850 Store->getMemoryVT(), 2851 *Store->getMemOperand())) 2852 return SDValue(); 2853 2854 SDLoc DL(Op); 2855 SDValue StoredVal = Store->getValue(); 2856 MVT VT = StoredVal.getSimpleValueType(); 2857 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2858 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2859 "Unexpected unaligned RVV store type"); 2860 MVT NewVT = 2861 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2862 assert(NewVT.isValid() && 2863 "Expecting equally-sized RVV vector types to be legal"); 2864 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2865 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2866 Store->getPointerInfo(), Store->getOriginalAlign(), 2867 Store->getMemOperand()->getFlags()); 2868 } 2869 2870 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2871 SelectionDAG &DAG) const { 2872 switch (Op.getOpcode()) { 2873 default: 2874 report_fatal_error("unimplemented operand"); 2875 case ISD::GlobalAddress: 2876 return lowerGlobalAddress(Op, DAG); 2877 case ISD::BlockAddress: 2878 return lowerBlockAddress(Op, DAG); 2879 case ISD::ConstantPool: 2880 return lowerConstantPool(Op, DAG); 2881 case ISD::JumpTable: 2882 return lowerJumpTable(Op, DAG); 2883 case ISD::GlobalTLSAddress: 2884 return lowerGlobalTLSAddress(Op, DAG); 2885 case ISD::SELECT: 2886 return lowerSELECT(Op, DAG); 2887 case ISD::BRCOND: 2888 return lowerBRCOND(Op, DAG); 2889 case ISD::VASTART: 2890 return lowerVASTART(Op, DAG); 2891 case ISD::FRAMEADDR: 2892 return lowerFRAMEADDR(Op, DAG); 2893 case ISD::RETURNADDR: 2894 return lowerRETURNADDR(Op, DAG); 2895 case ISD::SHL_PARTS: 2896 return lowerShiftLeftParts(Op, DAG); 2897 case ISD::SRA_PARTS: 2898 return lowerShiftRightParts(Op, DAG, true); 2899 case ISD::SRL_PARTS: 2900 return lowerShiftRightParts(Op, DAG, false); 2901 case ISD::BITCAST: { 2902 SDLoc DL(Op); 2903 EVT VT = Op.getValueType(); 2904 SDValue Op0 = Op.getOperand(0); 2905 EVT Op0VT = Op0.getValueType(); 2906 MVT XLenVT = Subtarget.getXLenVT(); 2907 if (VT.isFixedLengthVector()) { 2908 // We can handle fixed length vector bitcasts with a simple replacement 2909 // in isel. 2910 if (Op0VT.isFixedLengthVector()) 2911 return Op; 2912 // When bitcasting from scalar to fixed-length vector, insert the scalar 2913 // into a one-element vector of the result type, and perform a vector 2914 // bitcast. 2915 if (!Op0VT.isVector()) { 2916 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2917 if (!isTypeLegal(BVT)) 2918 return SDValue(); 2919 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2920 DAG.getUNDEF(BVT), Op0, 2921 DAG.getConstant(0, DL, XLenVT))); 2922 } 2923 return SDValue(); 2924 } 2925 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2926 // thus: bitcast the vector to a one-element vector type whose element type 2927 // is the same as the result type, and extract the first element. 2928 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2929 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2930 if (!isTypeLegal(BVT)) 2931 return SDValue(); 2932 SDValue BVec = DAG.getBitcast(BVT, Op0); 2933 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2934 DAG.getConstant(0, DL, XLenVT)); 2935 } 2936 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2937 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2938 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2939 return FPConv; 2940 } 2941 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2942 Subtarget.hasStdExtF()) { 2943 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2944 SDValue FPConv = 2945 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2946 return FPConv; 2947 } 2948 return SDValue(); 2949 } 2950 case ISD::INTRINSIC_WO_CHAIN: 2951 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2952 case ISD::INTRINSIC_W_CHAIN: 2953 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2954 case ISD::INTRINSIC_VOID: 2955 return LowerINTRINSIC_VOID(Op, DAG); 2956 case ISD::BSWAP: 2957 case ISD::BITREVERSE: { 2958 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 2959 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2960 MVT VT = Op.getSimpleValueType(); 2961 SDLoc DL(Op); 2962 // Start with the maximum immediate value which is the bitwidth - 1. 2963 unsigned Imm = VT.getSizeInBits() - 1; 2964 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 2965 if (Op.getOpcode() == ISD::BSWAP) 2966 Imm &= ~0x7U; 2967 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 2968 DAG.getConstant(Imm, DL, VT)); 2969 } 2970 case ISD::FSHL: 2971 case ISD::FSHR: { 2972 MVT VT = Op.getSimpleValueType(); 2973 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 2974 SDLoc DL(Op); 2975 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 2976 // use log(XLen) bits. Mask the shift amount accordingly to prevent 2977 // accidentally setting the extra bit. 2978 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 2979 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 2980 DAG.getConstant(ShAmtWidth, DL, VT)); 2981 // fshl and fshr concatenate their operands in the same order. fsr and fsl 2982 // instruction use different orders. fshl will return its first operand for 2983 // shift of zero, fshr will return its second operand. fsl and fsr both 2984 // return rs1 so the ISD nodes need to have different operand orders. 2985 // Shift amount is in rs2. 2986 SDValue Op0 = Op.getOperand(0); 2987 SDValue Op1 = Op.getOperand(1); 2988 unsigned Opc = RISCVISD::FSL; 2989 if (Op.getOpcode() == ISD::FSHR) { 2990 std::swap(Op0, Op1); 2991 Opc = RISCVISD::FSR; 2992 } 2993 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 2994 } 2995 case ISD::TRUNCATE: { 2996 SDLoc DL(Op); 2997 MVT VT = Op.getSimpleValueType(); 2998 // Only custom-lower vector truncates 2999 if (!VT.isVector()) 3000 return Op; 3001 3002 // Truncates to mask types are handled differently 3003 if (VT.getVectorElementType() == MVT::i1) 3004 return lowerVectorMaskTrunc(Op, DAG); 3005 3006 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 3007 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 3008 // truncate by one power of two at a time. 3009 MVT DstEltVT = VT.getVectorElementType(); 3010 3011 SDValue Src = Op.getOperand(0); 3012 MVT SrcVT = Src.getSimpleValueType(); 3013 MVT SrcEltVT = SrcVT.getVectorElementType(); 3014 3015 assert(DstEltVT.bitsLT(SrcEltVT) && 3016 isPowerOf2_64(DstEltVT.getSizeInBits()) && 3017 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 3018 "Unexpected vector truncate lowering"); 3019 3020 MVT ContainerVT = SrcVT; 3021 if (SrcVT.isFixedLengthVector()) { 3022 ContainerVT = getContainerForFixedLengthVector(SrcVT); 3023 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 3024 } 3025 3026 SDValue Result = Src; 3027 SDValue Mask, VL; 3028 std::tie(Mask, VL) = 3029 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 3030 LLVMContext &Context = *DAG.getContext(); 3031 const ElementCount Count = ContainerVT.getVectorElementCount(); 3032 do { 3033 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 3034 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 3035 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 3036 Mask, VL); 3037 } while (SrcEltVT != DstEltVT); 3038 3039 if (SrcVT.isFixedLengthVector()) 3040 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3041 3042 return Result; 3043 } 3044 case ISD::ANY_EXTEND: 3045 case ISD::ZERO_EXTEND: 3046 if (Op.getOperand(0).getValueType().isVector() && 3047 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3048 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3049 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3050 case ISD::SIGN_EXTEND: 3051 if (Op.getOperand(0).getValueType().isVector() && 3052 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3053 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3054 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3055 case ISD::SPLAT_VECTOR_PARTS: 3056 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3057 case ISD::INSERT_VECTOR_ELT: 3058 return lowerINSERT_VECTOR_ELT(Op, DAG); 3059 case ISD::EXTRACT_VECTOR_ELT: 3060 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3061 case ISD::VSCALE: { 3062 MVT VT = Op.getSimpleValueType(); 3063 SDLoc DL(Op); 3064 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3065 // We define our scalable vector types for lmul=1 to use a 64 bit known 3066 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3067 // vscale as VLENB / 8. 3068 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3069 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3070 // We assume VLENB is a multiple of 8. We manually choose the best shift 3071 // here because SimplifyDemandedBits isn't always able to simplify it. 3072 uint64_t Val = Op.getConstantOperandVal(0); 3073 if (isPowerOf2_64(Val)) { 3074 uint64_t Log2 = Log2_64(Val); 3075 if (Log2 < 3) 3076 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3077 DAG.getConstant(3 - Log2, DL, VT)); 3078 if (Log2 > 3) 3079 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3080 DAG.getConstant(Log2 - 3, DL, VT)); 3081 return VLENB; 3082 } 3083 // If the multiplier is a multiple of 8, scale it down to avoid needing 3084 // to shift the VLENB value. 3085 if ((Val % 8) == 0) 3086 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3087 DAG.getConstant(Val / 8, DL, VT)); 3088 } 3089 3090 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3091 DAG.getConstant(3, DL, VT)); 3092 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3093 } 3094 case ISD::FPOWI: { 3095 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3096 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3097 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3098 Op.getOperand(1).getValueType() == MVT::i32) { 3099 SDLoc DL(Op); 3100 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3101 SDValue Powi = 3102 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3103 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3104 DAG.getIntPtrConstant(0, DL)); 3105 } 3106 return SDValue(); 3107 } 3108 case ISD::FP_EXTEND: { 3109 // RVV can only do fp_extend to types double the size as the source. We 3110 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3111 // via f32. 3112 SDLoc DL(Op); 3113 MVT VT = Op.getSimpleValueType(); 3114 SDValue Src = Op.getOperand(0); 3115 MVT SrcVT = Src.getSimpleValueType(); 3116 3117 // Prepare any fixed-length vector operands. 3118 MVT ContainerVT = VT; 3119 if (SrcVT.isFixedLengthVector()) { 3120 ContainerVT = getContainerForFixedLengthVector(VT); 3121 MVT SrcContainerVT = 3122 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3123 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3124 } 3125 3126 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3127 SrcVT.getVectorElementType() != MVT::f16) { 3128 // For scalable vectors, we only need to close the gap between 3129 // vXf16->vXf64. 3130 if (!VT.isFixedLengthVector()) 3131 return Op; 3132 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3133 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3134 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3135 } 3136 3137 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3138 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3139 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3140 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3141 3142 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3143 DL, DAG, Subtarget); 3144 if (VT.isFixedLengthVector()) 3145 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3146 return Extend; 3147 } 3148 case ISD::FP_ROUND: { 3149 // RVV can only do fp_round to types half the size as the source. We 3150 // custom-lower f64->f16 rounds via RVV's round-to-odd float 3151 // conversion instruction. 3152 SDLoc DL(Op); 3153 MVT VT = Op.getSimpleValueType(); 3154 SDValue Src = Op.getOperand(0); 3155 MVT SrcVT = Src.getSimpleValueType(); 3156 3157 // Prepare any fixed-length vector operands. 3158 MVT ContainerVT = VT; 3159 if (VT.isFixedLengthVector()) { 3160 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3161 ContainerVT = 3162 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3163 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3164 } 3165 3166 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 3167 SrcVT.getVectorElementType() != MVT::f64) { 3168 // For scalable vectors, we only need to close the gap between 3169 // vXf64<->vXf16. 3170 if (!VT.isFixedLengthVector()) 3171 return Op; 3172 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 3173 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3174 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3175 } 3176 3177 SDValue Mask, VL; 3178 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3179 3180 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 3181 SDValue IntermediateRound = 3182 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 3183 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 3184 DL, DAG, Subtarget); 3185 3186 if (VT.isFixedLengthVector()) 3187 return convertFromScalableVector(VT, Round, DAG, Subtarget); 3188 return Round; 3189 } 3190 case ISD::FP_TO_SINT: 3191 case ISD::FP_TO_UINT: 3192 case ISD::SINT_TO_FP: 3193 case ISD::UINT_TO_FP: { 3194 // RVV can only do fp<->int conversions to types half/double the size as 3195 // the source. We custom-lower any conversions that do two hops into 3196 // sequences. 3197 MVT VT = Op.getSimpleValueType(); 3198 if (!VT.isVector()) 3199 return Op; 3200 SDLoc DL(Op); 3201 SDValue Src = Op.getOperand(0); 3202 MVT EltVT = VT.getVectorElementType(); 3203 MVT SrcVT = Src.getSimpleValueType(); 3204 MVT SrcEltVT = SrcVT.getVectorElementType(); 3205 unsigned EltSize = EltVT.getSizeInBits(); 3206 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3207 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3208 "Unexpected vector element types"); 3209 3210 bool IsInt2FP = SrcEltVT.isInteger(); 3211 // Widening conversions 3212 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 3213 if (IsInt2FP) { 3214 // Do a regular integer sign/zero extension then convert to float. 3215 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 3216 VT.getVectorElementCount()); 3217 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3218 ? ISD::ZERO_EXTEND 3219 : ISD::SIGN_EXTEND; 3220 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3221 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3222 } 3223 // FP2Int 3224 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3225 // Do one doubling fp_extend then complete the operation by converting 3226 // to int. 3227 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3228 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3229 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3230 } 3231 3232 // Narrowing conversions 3233 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 3234 if (IsInt2FP) { 3235 // One narrowing int_to_fp, then an fp_round. 3236 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3237 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3238 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3239 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3240 } 3241 // FP2Int 3242 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3243 // representable by the integer, the result is poison. 3244 MVT IVecVT = 3245 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 3246 VT.getVectorElementCount()); 3247 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3248 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3249 } 3250 3251 // Scalable vectors can exit here. Patterns will handle equally-sized 3252 // conversions halving/doubling ones. 3253 if (!VT.isFixedLengthVector()) 3254 return Op; 3255 3256 // For fixed-length vectors we lower to a custom "VL" node. 3257 unsigned RVVOpc = 0; 3258 switch (Op.getOpcode()) { 3259 default: 3260 llvm_unreachable("Impossible opcode"); 3261 case ISD::FP_TO_SINT: 3262 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3263 break; 3264 case ISD::FP_TO_UINT: 3265 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3266 break; 3267 case ISD::SINT_TO_FP: 3268 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3269 break; 3270 case ISD::UINT_TO_FP: 3271 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3272 break; 3273 } 3274 3275 MVT ContainerVT, SrcContainerVT; 3276 // Derive the reference container type from the larger vector type. 3277 if (SrcEltSize > EltSize) { 3278 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3279 ContainerVT = 3280 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3281 } else { 3282 ContainerVT = getContainerForFixedLengthVector(VT); 3283 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3284 } 3285 3286 SDValue Mask, VL; 3287 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3288 3289 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3290 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3291 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3292 } 3293 case ISD::FP_TO_SINT_SAT: 3294 case ISD::FP_TO_UINT_SAT: 3295 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3296 case ISD::FTRUNC: 3297 case ISD::FCEIL: 3298 case ISD::FFLOOR: 3299 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3300 case ISD::VECREDUCE_ADD: 3301 case ISD::VECREDUCE_UMAX: 3302 case ISD::VECREDUCE_SMAX: 3303 case ISD::VECREDUCE_UMIN: 3304 case ISD::VECREDUCE_SMIN: 3305 return lowerVECREDUCE(Op, DAG); 3306 case ISD::VECREDUCE_AND: 3307 case ISD::VECREDUCE_OR: 3308 case ISD::VECREDUCE_XOR: 3309 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3310 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3311 return lowerVECREDUCE(Op, DAG); 3312 case ISD::VECREDUCE_FADD: 3313 case ISD::VECREDUCE_SEQ_FADD: 3314 case ISD::VECREDUCE_FMIN: 3315 case ISD::VECREDUCE_FMAX: 3316 return lowerFPVECREDUCE(Op, DAG); 3317 case ISD::VP_REDUCE_ADD: 3318 case ISD::VP_REDUCE_UMAX: 3319 case ISD::VP_REDUCE_SMAX: 3320 case ISD::VP_REDUCE_UMIN: 3321 case ISD::VP_REDUCE_SMIN: 3322 case ISD::VP_REDUCE_FADD: 3323 case ISD::VP_REDUCE_SEQ_FADD: 3324 case ISD::VP_REDUCE_FMIN: 3325 case ISD::VP_REDUCE_FMAX: 3326 return lowerVPREDUCE(Op, DAG); 3327 case ISD::VP_REDUCE_AND: 3328 case ISD::VP_REDUCE_OR: 3329 case ISD::VP_REDUCE_XOR: 3330 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3331 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3332 return lowerVPREDUCE(Op, DAG); 3333 case ISD::INSERT_SUBVECTOR: 3334 return lowerINSERT_SUBVECTOR(Op, DAG); 3335 case ISD::EXTRACT_SUBVECTOR: 3336 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3337 case ISD::STEP_VECTOR: 3338 return lowerSTEP_VECTOR(Op, DAG); 3339 case ISD::VECTOR_REVERSE: 3340 return lowerVECTOR_REVERSE(Op, DAG); 3341 case ISD::BUILD_VECTOR: 3342 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3343 case ISD::SPLAT_VECTOR: 3344 if (Op.getValueType().getVectorElementType() == MVT::i1) 3345 return lowerVectorMaskSplat(Op, DAG); 3346 return lowerSPLAT_VECTOR(Op, DAG, Subtarget); 3347 case ISD::VECTOR_SHUFFLE: 3348 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3349 case ISD::CONCAT_VECTORS: { 3350 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3351 // better than going through the stack, as the default expansion does. 3352 SDLoc DL(Op); 3353 MVT VT = Op.getSimpleValueType(); 3354 unsigned NumOpElts = 3355 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3356 SDValue Vec = DAG.getUNDEF(VT); 3357 for (const auto &OpIdx : enumerate(Op->ops())) { 3358 SDValue SubVec = OpIdx.value(); 3359 // Don't insert undef subvectors. 3360 if (SubVec.isUndef()) 3361 continue; 3362 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3363 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3364 } 3365 return Vec; 3366 } 3367 case ISD::LOAD: 3368 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3369 return V; 3370 if (Op.getValueType().isFixedLengthVector()) 3371 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3372 return Op; 3373 case ISD::STORE: 3374 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3375 return V; 3376 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3377 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3378 return Op; 3379 case ISD::MLOAD: 3380 case ISD::VP_LOAD: 3381 return lowerMaskedLoad(Op, DAG); 3382 case ISD::MSTORE: 3383 case ISD::VP_STORE: 3384 return lowerMaskedStore(Op, DAG); 3385 case ISD::SETCC: 3386 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3387 case ISD::ADD: 3388 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3389 case ISD::SUB: 3390 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3391 case ISD::MUL: 3392 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3393 case ISD::MULHS: 3394 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3395 case ISD::MULHU: 3396 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3397 case ISD::AND: 3398 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3399 RISCVISD::AND_VL); 3400 case ISD::OR: 3401 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3402 RISCVISD::OR_VL); 3403 case ISD::XOR: 3404 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3405 RISCVISD::XOR_VL); 3406 case ISD::SDIV: 3407 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3408 case ISD::SREM: 3409 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3410 case ISD::UDIV: 3411 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3412 case ISD::UREM: 3413 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3414 case ISD::SHL: 3415 case ISD::SRA: 3416 case ISD::SRL: 3417 if (Op.getSimpleValueType().isFixedLengthVector()) 3418 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3419 // This can be called for an i32 shift amount that needs to be promoted. 3420 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3421 "Unexpected custom legalisation"); 3422 return SDValue(); 3423 case ISD::SADDSAT: 3424 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3425 case ISD::UADDSAT: 3426 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3427 case ISD::SSUBSAT: 3428 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3429 case ISD::USUBSAT: 3430 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3431 case ISD::FADD: 3432 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3433 case ISD::FSUB: 3434 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3435 case ISD::FMUL: 3436 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3437 case ISD::FDIV: 3438 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3439 case ISD::FNEG: 3440 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3441 case ISD::FABS: 3442 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3443 case ISD::FSQRT: 3444 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3445 case ISD::FMA: 3446 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3447 case ISD::SMIN: 3448 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3449 case ISD::SMAX: 3450 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3451 case ISD::UMIN: 3452 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3453 case ISD::UMAX: 3454 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3455 case ISD::FMINNUM: 3456 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3457 case ISD::FMAXNUM: 3458 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3459 case ISD::ABS: 3460 return lowerABS(Op, DAG); 3461 case ISD::CTLZ_ZERO_UNDEF: 3462 case ISD::CTTZ_ZERO_UNDEF: 3463 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3464 case ISD::VSELECT: 3465 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3466 case ISD::FCOPYSIGN: 3467 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3468 case ISD::MGATHER: 3469 case ISD::VP_GATHER: 3470 return lowerMaskedGather(Op, DAG); 3471 case ISD::MSCATTER: 3472 case ISD::VP_SCATTER: 3473 return lowerMaskedScatter(Op, DAG); 3474 case ISD::FLT_ROUNDS_: 3475 return lowerGET_ROUNDING(Op, DAG); 3476 case ISD::SET_ROUNDING: 3477 return lowerSET_ROUNDING(Op, DAG); 3478 case ISD::VP_SELECT: 3479 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3480 case ISD::VP_MERGE: 3481 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3482 case ISD::VP_ADD: 3483 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3484 case ISD::VP_SUB: 3485 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3486 case ISD::VP_MUL: 3487 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3488 case ISD::VP_SDIV: 3489 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3490 case ISD::VP_UDIV: 3491 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3492 case ISD::VP_SREM: 3493 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3494 case ISD::VP_UREM: 3495 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3496 case ISD::VP_AND: 3497 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3498 case ISD::VP_OR: 3499 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3500 case ISD::VP_XOR: 3501 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3502 case ISD::VP_ASHR: 3503 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3504 case ISD::VP_LSHR: 3505 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3506 case ISD::VP_SHL: 3507 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3508 case ISD::VP_FADD: 3509 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3510 case ISD::VP_FSUB: 3511 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3512 case ISD::VP_FMUL: 3513 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3514 case ISD::VP_FDIV: 3515 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3516 } 3517 } 3518 3519 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3520 SelectionDAG &DAG, unsigned Flags) { 3521 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3522 } 3523 3524 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3525 SelectionDAG &DAG, unsigned Flags) { 3526 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3527 Flags); 3528 } 3529 3530 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3531 SelectionDAG &DAG, unsigned Flags) { 3532 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3533 N->getOffset(), Flags); 3534 } 3535 3536 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3537 SelectionDAG &DAG, unsigned Flags) { 3538 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3539 } 3540 3541 template <class NodeTy> 3542 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3543 bool IsLocal) const { 3544 SDLoc DL(N); 3545 EVT Ty = getPointerTy(DAG.getDataLayout()); 3546 3547 if (isPositionIndependent()) { 3548 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3549 if (IsLocal) 3550 // Use PC-relative addressing to access the symbol. This generates the 3551 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3552 // %pcrel_lo(auipc)). 3553 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3554 3555 // Use PC-relative addressing to access the GOT for this symbol, then load 3556 // the address from the GOT. This generates the pattern (PseudoLA sym), 3557 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3558 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3559 } 3560 3561 switch (getTargetMachine().getCodeModel()) { 3562 default: 3563 report_fatal_error("Unsupported code model for lowering"); 3564 case CodeModel::Small: { 3565 // Generate a sequence for accessing addresses within the first 2 GiB of 3566 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3567 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3568 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3569 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3570 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3571 } 3572 case CodeModel::Medium: { 3573 // Generate a sequence for accessing addresses within any 2GiB range within 3574 // the address space. This generates the pattern (PseudoLLA sym), which 3575 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3576 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3577 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3578 } 3579 } 3580 } 3581 3582 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3583 SelectionDAG &DAG) const { 3584 SDLoc DL(Op); 3585 EVT Ty = Op.getValueType(); 3586 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3587 int64_t Offset = N->getOffset(); 3588 MVT XLenVT = Subtarget.getXLenVT(); 3589 3590 const GlobalValue *GV = N->getGlobal(); 3591 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3592 SDValue Addr = getAddr(N, DAG, IsLocal); 3593 3594 // In order to maximise the opportunity for common subexpression elimination, 3595 // emit a separate ADD node for the global address offset instead of folding 3596 // it in the global address node. Later peephole optimisations may choose to 3597 // fold it back in when profitable. 3598 if (Offset != 0) 3599 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3600 DAG.getConstant(Offset, DL, XLenVT)); 3601 return Addr; 3602 } 3603 3604 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3605 SelectionDAG &DAG) const { 3606 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3607 3608 return getAddr(N, DAG); 3609 } 3610 3611 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3612 SelectionDAG &DAG) const { 3613 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3614 3615 return getAddr(N, DAG); 3616 } 3617 3618 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3619 SelectionDAG &DAG) const { 3620 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3621 3622 return getAddr(N, DAG); 3623 } 3624 3625 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3626 SelectionDAG &DAG, 3627 bool UseGOT) const { 3628 SDLoc DL(N); 3629 EVT Ty = getPointerTy(DAG.getDataLayout()); 3630 const GlobalValue *GV = N->getGlobal(); 3631 MVT XLenVT = Subtarget.getXLenVT(); 3632 3633 if (UseGOT) { 3634 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3635 // load the address from the GOT and add the thread pointer. This generates 3636 // the pattern (PseudoLA_TLS_IE sym), which expands to 3637 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3638 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3639 SDValue Load = 3640 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3641 3642 // Add the thread pointer. 3643 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3644 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3645 } 3646 3647 // Generate a sequence for accessing the address relative to the thread 3648 // pointer, with the appropriate adjustment for the thread pointer offset. 3649 // This generates the pattern 3650 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3651 SDValue AddrHi = 3652 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3653 SDValue AddrAdd = 3654 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3655 SDValue AddrLo = 3656 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3657 3658 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3659 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3660 SDValue MNAdd = SDValue( 3661 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3662 0); 3663 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3664 } 3665 3666 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3667 SelectionDAG &DAG) const { 3668 SDLoc DL(N); 3669 EVT Ty = getPointerTy(DAG.getDataLayout()); 3670 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3671 const GlobalValue *GV = N->getGlobal(); 3672 3673 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3674 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3675 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3676 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3677 SDValue Load = 3678 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3679 3680 // Prepare argument list to generate call. 3681 ArgListTy Args; 3682 ArgListEntry Entry; 3683 Entry.Node = Load; 3684 Entry.Ty = CallTy; 3685 Args.push_back(Entry); 3686 3687 // Setup call to __tls_get_addr. 3688 TargetLowering::CallLoweringInfo CLI(DAG); 3689 CLI.setDebugLoc(DL) 3690 .setChain(DAG.getEntryNode()) 3691 .setLibCallee(CallingConv::C, CallTy, 3692 DAG.getExternalSymbol("__tls_get_addr", Ty), 3693 std::move(Args)); 3694 3695 return LowerCallTo(CLI).first; 3696 } 3697 3698 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3699 SelectionDAG &DAG) const { 3700 SDLoc DL(Op); 3701 EVT Ty = Op.getValueType(); 3702 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3703 int64_t Offset = N->getOffset(); 3704 MVT XLenVT = Subtarget.getXLenVT(); 3705 3706 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3707 3708 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3709 CallingConv::GHC) 3710 report_fatal_error("In GHC calling convention TLS is not supported"); 3711 3712 SDValue Addr; 3713 switch (Model) { 3714 case TLSModel::LocalExec: 3715 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3716 break; 3717 case TLSModel::InitialExec: 3718 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3719 break; 3720 case TLSModel::LocalDynamic: 3721 case TLSModel::GeneralDynamic: 3722 Addr = getDynamicTLSAddr(N, DAG); 3723 break; 3724 } 3725 3726 // In order to maximise the opportunity for common subexpression elimination, 3727 // emit a separate ADD node for the global address offset instead of folding 3728 // it in the global address node. Later peephole optimisations may choose to 3729 // fold it back in when profitable. 3730 if (Offset != 0) 3731 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3732 DAG.getConstant(Offset, DL, XLenVT)); 3733 return Addr; 3734 } 3735 3736 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3737 SDValue CondV = Op.getOperand(0); 3738 SDValue TrueV = Op.getOperand(1); 3739 SDValue FalseV = Op.getOperand(2); 3740 SDLoc DL(Op); 3741 MVT VT = Op.getSimpleValueType(); 3742 MVT XLenVT = Subtarget.getXLenVT(); 3743 3744 // Lower vector SELECTs to VSELECTs by splatting the condition. 3745 if (VT.isVector()) { 3746 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3747 SDValue CondSplat = VT.isScalableVector() 3748 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3749 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3750 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3751 } 3752 3753 // If the result type is XLenVT and CondV is the output of a SETCC node 3754 // which also operated on XLenVT inputs, then merge the SETCC node into the 3755 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3756 // compare+branch instructions. i.e.: 3757 // (select (setcc lhs, rhs, cc), truev, falsev) 3758 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3759 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3760 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3761 SDValue LHS = CondV.getOperand(0); 3762 SDValue RHS = CondV.getOperand(1); 3763 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3764 ISD::CondCode CCVal = CC->get(); 3765 3766 // Special case for a select of 2 constants that have a diffence of 1. 3767 // Normally this is done by DAGCombine, but if the select is introduced by 3768 // type legalization or op legalization, we miss it. Restricting to SETLT 3769 // case for now because that is what signed saturating add/sub need. 3770 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3771 // but we would probably want to swap the true/false values if the condition 3772 // is SETGE/SETLE to avoid an XORI. 3773 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3774 CCVal == ISD::SETLT) { 3775 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3776 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3777 if (TrueVal - 1 == FalseVal) 3778 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3779 if (TrueVal + 1 == FalseVal) 3780 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3781 } 3782 3783 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3784 3785 SDValue TargetCC = DAG.getCondCode(CCVal); 3786 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3787 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3788 } 3789 3790 // Otherwise: 3791 // (select condv, truev, falsev) 3792 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3793 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3794 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3795 3796 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3797 3798 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3799 } 3800 3801 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3802 SDValue CondV = Op.getOperand(1); 3803 SDLoc DL(Op); 3804 MVT XLenVT = Subtarget.getXLenVT(); 3805 3806 if (CondV.getOpcode() == ISD::SETCC && 3807 CondV.getOperand(0).getValueType() == XLenVT) { 3808 SDValue LHS = CondV.getOperand(0); 3809 SDValue RHS = CondV.getOperand(1); 3810 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3811 3812 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3813 3814 SDValue TargetCC = DAG.getCondCode(CCVal); 3815 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3816 LHS, RHS, TargetCC, Op.getOperand(2)); 3817 } 3818 3819 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3820 CondV, DAG.getConstant(0, DL, XLenVT), 3821 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3822 } 3823 3824 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3825 MachineFunction &MF = DAG.getMachineFunction(); 3826 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3827 3828 SDLoc DL(Op); 3829 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3830 getPointerTy(MF.getDataLayout())); 3831 3832 // vastart just stores the address of the VarArgsFrameIndex slot into the 3833 // memory location argument. 3834 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3835 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3836 MachinePointerInfo(SV)); 3837 } 3838 3839 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3840 SelectionDAG &DAG) const { 3841 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3842 MachineFunction &MF = DAG.getMachineFunction(); 3843 MachineFrameInfo &MFI = MF.getFrameInfo(); 3844 MFI.setFrameAddressIsTaken(true); 3845 Register FrameReg = RI.getFrameRegister(MF); 3846 int XLenInBytes = Subtarget.getXLen() / 8; 3847 3848 EVT VT = Op.getValueType(); 3849 SDLoc DL(Op); 3850 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3851 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3852 while (Depth--) { 3853 int Offset = -(XLenInBytes * 2); 3854 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3855 DAG.getIntPtrConstant(Offset, DL)); 3856 FrameAddr = 3857 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3858 } 3859 return FrameAddr; 3860 } 3861 3862 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3863 SelectionDAG &DAG) const { 3864 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3865 MachineFunction &MF = DAG.getMachineFunction(); 3866 MachineFrameInfo &MFI = MF.getFrameInfo(); 3867 MFI.setReturnAddressIsTaken(true); 3868 MVT XLenVT = Subtarget.getXLenVT(); 3869 int XLenInBytes = Subtarget.getXLen() / 8; 3870 3871 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3872 return SDValue(); 3873 3874 EVT VT = Op.getValueType(); 3875 SDLoc DL(Op); 3876 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3877 if (Depth) { 3878 int Off = -XLenInBytes; 3879 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3880 SDValue Offset = DAG.getConstant(Off, DL, VT); 3881 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3882 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3883 MachinePointerInfo()); 3884 } 3885 3886 // Return the value of the return address register, marking it an implicit 3887 // live-in. 3888 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3889 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3890 } 3891 3892 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3893 SelectionDAG &DAG) const { 3894 SDLoc DL(Op); 3895 SDValue Lo = Op.getOperand(0); 3896 SDValue Hi = Op.getOperand(1); 3897 SDValue Shamt = Op.getOperand(2); 3898 EVT VT = Lo.getValueType(); 3899 3900 // if Shamt-XLEN < 0: // Shamt < XLEN 3901 // Lo = Lo << Shamt 3902 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 3903 // else: 3904 // Lo = 0 3905 // Hi = Lo << (Shamt-XLEN) 3906 3907 SDValue Zero = DAG.getConstant(0, DL, VT); 3908 SDValue One = DAG.getConstant(1, DL, VT); 3909 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3910 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3911 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3912 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3913 3914 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3915 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3916 SDValue ShiftRightLo = 3917 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3918 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3919 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3920 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3921 3922 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3923 3924 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3925 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3926 3927 SDValue Parts[2] = {Lo, Hi}; 3928 return DAG.getMergeValues(Parts, DL); 3929 } 3930 3931 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3932 bool IsSRA) const { 3933 SDLoc DL(Op); 3934 SDValue Lo = Op.getOperand(0); 3935 SDValue Hi = Op.getOperand(1); 3936 SDValue Shamt = Op.getOperand(2); 3937 EVT VT = Lo.getValueType(); 3938 3939 // SRA expansion: 3940 // if Shamt-XLEN < 0: // Shamt < XLEN 3941 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3942 // Hi = Hi >>s Shamt 3943 // else: 3944 // Lo = Hi >>s (Shamt-XLEN); 3945 // Hi = Hi >>s (XLEN-1) 3946 // 3947 // SRL expansion: 3948 // if Shamt-XLEN < 0: // Shamt < XLEN 3949 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 3950 // Hi = Hi >>u Shamt 3951 // else: 3952 // Lo = Hi >>u (Shamt-XLEN); 3953 // Hi = 0; 3954 3955 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3956 3957 SDValue Zero = DAG.getConstant(0, DL, VT); 3958 SDValue One = DAG.getConstant(1, DL, VT); 3959 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3960 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3961 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3962 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 3963 3964 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3965 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3966 SDValue ShiftLeftHi = 3967 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3968 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3969 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3970 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3971 SDValue HiFalse = 3972 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3973 3974 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3975 3976 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3977 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3978 3979 SDValue Parts[2] = {Lo, Hi}; 3980 return DAG.getMergeValues(Parts, DL); 3981 } 3982 3983 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3984 // legal equivalently-sized i8 type, so we can use that as a go-between. 3985 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3986 SelectionDAG &DAG) const { 3987 SDLoc DL(Op); 3988 MVT VT = Op.getSimpleValueType(); 3989 SDValue SplatVal = Op.getOperand(0); 3990 // All-zeros or all-ones splats are handled specially. 3991 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3992 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3993 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3994 } 3995 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3996 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3997 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 3998 } 3999 MVT XLenVT = Subtarget.getXLenVT(); 4000 assert(SplatVal.getValueType() == XLenVT && 4001 "Unexpected type for i1 splat value"); 4002 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4003 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4004 DAG.getConstant(1, DL, XLenVT)); 4005 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4006 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4007 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4008 } 4009 4010 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4011 // illegal (currently only vXi64 RV32). 4012 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4013 // them to SPLAT_VECTOR_I64 4014 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4015 SelectionDAG &DAG) const { 4016 SDLoc DL(Op); 4017 MVT VecVT = Op.getSimpleValueType(); 4018 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4019 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4020 4021 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4022 SDValue Lo = Op.getOperand(0); 4023 SDValue Hi = Op.getOperand(1); 4024 4025 if (VecVT.isFixedLengthVector()) { 4026 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4027 SDLoc DL(Op); 4028 SDValue Mask, VL; 4029 std::tie(Mask, VL) = 4030 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4031 4032 SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG); 4033 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4034 } 4035 4036 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4037 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4038 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4039 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4040 // node in order to try and match RVV vector/scalar instructions. 4041 if ((LoC >> 31) == HiC) 4042 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 4043 } 4044 4045 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4046 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4047 isa<ConstantSDNode>(Hi.getOperand(1)) && 4048 Hi.getConstantOperandVal(1) == 31) 4049 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 4050 4051 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4052 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi, 4053 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64)); 4054 } 4055 4056 // Custom-lower extensions from mask vectors by using a vselect either with 1 4057 // for zero/any-extension or -1 for sign-extension: 4058 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4059 // Note that any-extension is lowered identically to zero-extension. 4060 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4061 int64_t ExtTrueVal) const { 4062 SDLoc DL(Op); 4063 MVT VecVT = Op.getSimpleValueType(); 4064 SDValue Src = Op.getOperand(0); 4065 // Only custom-lower extensions from mask types 4066 assert(Src.getValueType().isVector() && 4067 Src.getValueType().getVectorElementType() == MVT::i1); 4068 4069 MVT XLenVT = Subtarget.getXLenVT(); 4070 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4071 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4072 4073 if (VecVT.isScalableVector()) { 4074 // Be careful not to introduce illegal scalar types at this stage, and be 4075 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 4076 // illegal and must be expanded. Since we know that the constants are 4077 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 4078 bool IsRV32E64 = 4079 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 4080 4081 if (!IsRV32E64) { 4082 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 4083 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 4084 } else { 4085 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 4086 SplatTrueVal = 4087 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 4088 } 4089 4090 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4091 } 4092 4093 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4094 MVT I1ContainerVT = 4095 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4096 4097 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4098 4099 SDValue Mask, VL; 4100 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4101 4102 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 4103 SplatTrueVal = 4104 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 4105 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4106 SplatTrueVal, SplatZero, VL); 4107 4108 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4109 } 4110 4111 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4112 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4113 MVT ExtVT = Op.getSimpleValueType(); 4114 // Only custom-lower extensions from fixed-length vector types. 4115 if (!ExtVT.isFixedLengthVector()) 4116 return Op; 4117 MVT VT = Op.getOperand(0).getSimpleValueType(); 4118 // Grab the canonical container type for the extended type. Infer the smaller 4119 // type from that to ensure the same number of vector elements, as we know 4120 // the LMUL will be sufficient to hold the smaller type. 4121 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4122 // Get the extended container type manually to ensure the same number of 4123 // vector elements between source and dest. 4124 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4125 ContainerExtVT.getVectorElementCount()); 4126 4127 SDValue Op1 = 4128 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4129 4130 SDLoc DL(Op); 4131 SDValue Mask, VL; 4132 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4133 4134 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4135 4136 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4137 } 4138 4139 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4140 // setcc operation: 4141 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4142 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 4143 SelectionDAG &DAG) const { 4144 SDLoc DL(Op); 4145 EVT MaskVT = Op.getValueType(); 4146 // Only expect to custom-lower truncations to mask types 4147 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4148 "Unexpected type for vector mask lowering"); 4149 SDValue Src = Op.getOperand(0); 4150 MVT VecVT = Src.getSimpleValueType(); 4151 4152 // If this is a fixed vector, we need to convert it to a scalable vector. 4153 MVT ContainerVT = VecVT; 4154 if (VecVT.isFixedLengthVector()) { 4155 ContainerVT = getContainerForFixedLengthVector(VecVT); 4156 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4157 } 4158 4159 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4160 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4161 4162 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 4163 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 4164 4165 if (VecVT.isScalableVector()) { 4166 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 4167 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 4168 } 4169 4170 SDValue Mask, VL; 4171 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4172 4173 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4174 SDValue Trunc = 4175 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4176 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4177 DAG.getCondCode(ISD::SETNE), Mask, VL); 4178 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4179 } 4180 4181 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4182 // first position of a vector, and that vector is slid up to the insert index. 4183 // By limiting the active vector length to index+1 and merging with the 4184 // original vector (with an undisturbed tail policy for elements >= VL), we 4185 // achieve the desired result of leaving all elements untouched except the one 4186 // at VL-1, which is replaced with the desired value. 4187 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4188 SelectionDAG &DAG) const { 4189 SDLoc DL(Op); 4190 MVT VecVT = Op.getSimpleValueType(); 4191 SDValue Vec = Op.getOperand(0); 4192 SDValue Val = Op.getOperand(1); 4193 SDValue Idx = Op.getOperand(2); 4194 4195 if (VecVT.getVectorElementType() == MVT::i1) { 4196 // FIXME: For now we just promote to an i8 vector and insert into that, 4197 // but this is probably not optimal. 4198 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4199 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4200 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4201 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4202 } 4203 4204 MVT ContainerVT = VecVT; 4205 // If the operand is a fixed-length vector, convert to a scalable one. 4206 if (VecVT.isFixedLengthVector()) { 4207 ContainerVT = getContainerForFixedLengthVector(VecVT); 4208 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4209 } 4210 4211 MVT XLenVT = Subtarget.getXLenVT(); 4212 4213 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4214 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4215 // Even i64-element vectors on RV32 can be lowered without scalar 4216 // legalization if the most-significant 32 bits of the value are not affected 4217 // by the sign-extension of the lower 32 bits. 4218 // TODO: We could also catch sign extensions of a 32-bit value. 4219 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4220 const auto *CVal = cast<ConstantSDNode>(Val); 4221 if (isInt<32>(CVal->getSExtValue())) { 4222 IsLegalInsert = true; 4223 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4224 } 4225 } 4226 4227 SDValue Mask, VL; 4228 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4229 4230 SDValue ValInVec; 4231 4232 if (IsLegalInsert) { 4233 unsigned Opc = 4234 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4235 if (isNullConstant(Idx)) { 4236 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4237 if (!VecVT.isFixedLengthVector()) 4238 return Vec; 4239 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4240 } 4241 ValInVec = 4242 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4243 } else { 4244 // On RV32, i64-element vectors must be specially handled to place the 4245 // value at element 0, by using two vslide1up instructions in sequence on 4246 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4247 // this. 4248 SDValue One = DAG.getConstant(1, DL, XLenVT); 4249 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4250 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4251 MVT I32ContainerVT = 4252 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4253 SDValue I32Mask = 4254 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4255 // Limit the active VL to two. 4256 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4257 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4258 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4259 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 4260 InsertI64VL); 4261 // First slide in the hi value, then the lo in underneath it. 4262 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4263 ValHi, I32Mask, InsertI64VL); 4264 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 4265 ValLo, I32Mask, InsertI64VL); 4266 // Bitcast back to the right container type. 4267 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4268 } 4269 4270 // Now that the value is in a vector, slide it into position. 4271 SDValue InsertVL = 4272 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4273 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4274 ValInVec, Idx, Mask, InsertVL); 4275 if (!VecVT.isFixedLengthVector()) 4276 return Slideup; 4277 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4278 } 4279 4280 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4281 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4282 // types this is done using VMV_X_S to allow us to glean information about the 4283 // sign bits of the result. 4284 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4285 SelectionDAG &DAG) const { 4286 SDLoc DL(Op); 4287 SDValue Idx = Op.getOperand(1); 4288 SDValue Vec = Op.getOperand(0); 4289 EVT EltVT = Op.getValueType(); 4290 MVT VecVT = Vec.getSimpleValueType(); 4291 MVT XLenVT = Subtarget.getXLenVT(); 4292 4293 if (VecVT.getVectorElementType() == MVT::i1) { 4294 // FIXME: For now we just promote to an i8 vector and extract from that, 4295 // but this is probably not optimal. 4296 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4297 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4298 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4299 } 4300 4301 // If this is a fixed vector, we need to convert it to a scalable vector. 4302 MVT ContainerVT = VecVT; 4303 if (VecVT.isFixedLengthVector()) { 4304 ContainerVT = getContainerForFixedLengthVector(VecVT); 4305 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4306 } 4307 4308 // If the index is 0, the vector is already in the right position. 4309 if (!isNullConstant(Idx)) { 4310 // Use a VL of 1 to avoid processing more elements than we need. 4311 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4312 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4313 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4314 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4315 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4316 } 4317 4318 if (!EltVT.isInteger()) { 4319 // Floating-point extracts are handled in TableGen. 4320 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4321 DAG.getConstant(0, DL, XLenVT)); 4322 } 4323 4324 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4325 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4326 } 4327 4328 // Some RVV intrinsics may claim that they want an integer operand to be 4329 // promoted or expanded. 4330 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 4331 const RISCVSubtarget &Subtarget) { 4332 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4333 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4334 "Unexpected opcode"); 4335 4336 if (!Subtarget.hasVInstructions()) 4337 return SDValue(); 4338 4339 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4340 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4341 SDLoc DL(Op); 4342 4343 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4344 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4345 if (!II || !II->hasSplatOperand()) 4346 return SDValue(); 4347 4348 unsigned SplatOp = II->SplatOperand + 1 + HasChain; 4349 assert(SplatOp < Op.getNumOperands()); 4350 4351 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4352 SDValue &ScalarOp = Operands[SplatOp]; 4353 MVT OpVT = ScalarOp.getSimpleValueType(); 4354 MVT XLenVT = Subtarget.getXLenVT(); 4355 4356 // If this isn't a scalar, or its type is XLenVT we're done. 4357 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4358 return SDValue(); 4359 4360 // Simplest case is that the operand needs to be promoted to XLenVT. 4361 if (OpVT.bitsLT(XLenVT)) { 4362 // If the operand is a constant, sign extend to increase our chances 4363 // of being able to use a .vi instruction. ANY_EXTEND would become a 4364 // a zero extend and the simm5 check in isel would fail. 4365 // FIXME: Should we ignore the upper bits in isel instead? 4366 unsigned ExtOpc = 4367 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4368 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4369 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4370 } 4371 4372 // Use the previous operand to get the vXi64 VT. The result might be a mask 4373 // VT for compares. Using the previous operand assumes that the previous 4374 // operand will never have a smaller element size than a scalar operand and 4375 // that a widening operation never uses SEW=64. 4376 // NOTE: If this fails the below assert, we can probably just find the 4377 // element count from any operand or result and use it to construct the VT. 4378 assert(II->SplatOperand > 0 && "Unexpected splat operand!"); 4379 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4380 4381 // The more complex case is when the scalar is larger than XLenVT. 4382 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4383 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4384 4385 // If this is a sign-extended 32-bit constant, we can truncate it and rely 4386 // on the instruction to sign-extend since SEW>XLEN. 4387 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 4388 if (isInt<32>(CVal->getSExtValue())) { 4389 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4390 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4391 } 4392 } 4393 4394 // We need to convert the scalar to a splat vector. 4395 // FIXME: Can we implicitly truncate the scalar if it is known to 4396 // be sign extended? 4397 SDValue VL = getVLOperand(Op); 4398 assert(VL.getValueType() == XLenVT); 4399 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 4400 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4401 } 4402 4403 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4404 SelectionDAG &DAG) const { 4405 unsigned IntNo = Op.getConstantOperandVal(0); 4406 SDLoc DL(Op); 4407 MVT XLenVT = Subtarget.getXLenVT(); 4408 4409 switch (IntNo) { 4410 default: 4411 break; // Don't custom lower most intrinsics. 4412 case Intrinsic::thread_pointer: { 4413 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4414 return DAG.getRegister(RISCV::X4, PtrVT); 4415 } 4416 case Intrinsic::riscv_orc_b: 4417 // Lower to the GORCI encoding for orc.b. 4418 return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1), 4419 DAG.getConstant(7, DL, XLenVT)); 4420 case Intrinsic::riscv_grev: 4421 case Intrinsic::riscv_gorc: { 4422 unsigned Opc = 4423 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4424 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4425 } 4426 case Intrinsic::riscv_shfl: 4427 case Intrinsic::riscv_unshfl: { 4428 unsigned Opc = 4429 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4430 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4431 } 4432 case Intrinsic::riscv_bcompress: 4433 case Intrinsic::riscv_bdecompress: { 4434 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4435 : RISCVISD::BDECOMPRESS; 4436 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4437 } 4438 case Intrinsic::riscv_bfp: 4439 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4440 Op.getOperand(2)); 4441 case Intrinsic::riscv_fsl: 4442 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4443 Op.getOperand(2), Op.getOperand(3)); 4444 case Intrinsic::riscv_fsr: 4445 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4446 Op.getOperand(2), Op.getOperand(3)); 4447 case Intrinsic::riscv_vmv_x_s: 4448 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4449 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4450 Op.getOperand(1)); 4451 case Intrinsic::riscv_vmv_v_x: 4452 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4453 Op.getSimpleValueType(), DL, DAG, Subtarget); 4454 case Intrinsic::riscv_vfmv_v_f: 4455 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4456 Op.getOperand(1), Op.getOperand(2)); 4457 case Intrinsic::riscv_vmv_s_x: { 4458 SDValue Scalar = Op.getOperand(2); 4459 4460 if (Scalar.getValueType().bitsLE(XLenVT)) { 4461 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4462 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4463 Op.getOperand(1), Scalar, Op.getOperand(3)); 4464 } 4465 4466 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4467 4468 // This is an i64 value that lives in two scalar registers. We have to 4469 // insert this in a convoluted way. First we build vXi64 splat containing 4470 // the/ two values that we assemble using some bit math. Next we'll use 4471 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4472 // to merge element 0 from our splat into the source vector. 4473 // FIXME: This is probably not the best way to do this, but it is 4474 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4475 // point. 4476 // sw lo, (a0) 4477 // sw hi, 4(a0) 4478 // vlse vX, (a0) 4479 // 4480 // vid.v vVid 4481 // vmseq.vx mMask, vVid, 0 4482 // vmerge.vvm vDest, vSrc, vVal, mMask 4483 MVT VT = Op.getSimpleValueType(); 4484 SDValue Vec = Op.getOperand(1); 4485 SDValue VL = getVLOperand(Op); 4486 4487 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 4488 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 4489 DAG.getConstant(0, DL, MVT::i32), VL); 4490 4491 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 4492 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4493 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4494 SDValue SelectCond = 4495 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4496 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4497 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4498 Vec, VL); 4499 } 4500 case Intrinsic::riscv_vslide1up: 4501 case Intrinsic::riscv_vslide1down: 4502 case Intrinsic::riscv_vslide1up_mask: 4503 case Intrinsic::riscv_vslide1down_mask: { 4504 // We need to special case these when the scalar is larger than XLen. 4505 unsigned NumOps = Op.getNumOperands(); 4506 bool IsMasked = NumOps == 7; 4507 unsigned OpOffset = IsMasked ? 1 : 0; 4508 SDValue Scalar = Op.getOperand(2 + OpOffset); 4509 if (Scalar.getValueType().bitsLE(XLenVT)) 4510 break; 4511 4512 // Splatting a sign extended constant is fine. 4513 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) 4514 if (isInt<32>(CVal->getSExtValue())) 4515 break; 4516 4517 MVT VT = Op.getSimpleValueType(); 4518 assert(VT.getVectorElementType() == MVT::i64 && 4519 Scalar.getValueType() == MVT::i64 && "Unexpected VTs"); 4520 4521 // Convert the vector source to the equivalent nxvXi32 vector. 4522 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4523 SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset)); 4524 4525 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4526 DAG.getConstant(0, DL, XLenVT)); 4527 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 4528 DAG.getConstant(1, DL, XLenVT)); 4529 4530 // Double the VL since we halved SEW. 4531 SDValue VL = getVLOperand(Op); 4532 SDValue I32VL = 4533 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4534 4535 MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount()); 4536 SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL); 4537 4538 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4539 // instructions. 4540 if (IntNo == Intrinsic::riscv_vslide1up || 4541 IntNo == Intrinsic::riscv_vslide1up_mask) { 4542 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi, 4543 I32Mask, I32VL); 4544 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo, 4545 I32Mask, I32VL); 4546 } else { 4547 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo, 4548 I32Mask, I32VL); 4549 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi, 4550 I32Mask, I32VL); 4551 } 4552 4553 // Convert back to nxvXi64. 4554 Vec = DAG.getBitcast(VT, Vec); 4555 4556 if (!IsMasked) 4557 return Vec; 4558 4559 // Apply mask after the operation. 4560 SDValue Mask = Op.getOperand(NumOps - 3); 4561 SDValue MaskedOff = Op.getOperand(1); 4562 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL); 4563 } 4564 } 4565 4566 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4567 } 4568 4569 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4570 SelectionDAG &DAG) const { 4571 unsigned IntNo = Op.getConstantOperandVal(1); 4572 switch (IntNo) { 4573 default: 4574 break; 4575 case Intrinsic::riscv_masked_strided_load: { 4576 SDLoc DL(Op); 4577 MVT XLenVT = Subtarget.getXLenVT(); 4578 4579 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4580 // the selection of the masked intrinsics doesn't do this for us. 4581 SDValue Mask = Op.getOperand(5); 4582 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4583 4584 MVT VT = Op->getSimpleValueType(0); 4585 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4586 4587 SDValue PassThru = Op.getOperand(2); 4588 if (!IsUnmasked) { 4589 MVT MaskVT = 4590 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4591 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4592 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4593 } 4594 4595 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4596 4597 SDValue IntID = DAG.getTargetConstant( 4598 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4599 XLenVT); 4600 4601 auto *Load = cast<MemIntrinsicSDNode>(Op); 4602 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4603 if (IsUnmasked) 4604 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4605 else 4606 Ops.push_back(PassThru); 4607 Ops.push_back(Op.getOperand(3)); // Ptr 4608 Ops.push_back(Op.getOperand(4)); // Stride 4609 if (!IsUnmasked) 4610 Ops.push_back(Mask); 4611 Ops.push_back(VL); 4612 if (!IsUnmasked) { 4613 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4614 Ops.push_back(Policy); 4615 } 4616 4617 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4618 SDValue Result = 4619 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4620 Load->getMemoryVT(), Load->getMemOperand()); 4621 SDValue Chain = Result.getValue(1); 4622 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4623 return DAG.getMergeValues({Result, Chain}, DL); 4624 } 4625 } 4626 4627 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 4628 } 4629 4630 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4631 SelectionDAG &DAG) const { 4632 unsigned IntNo = Op.getConstantOperandVal(1); 4633 switch (IntNo) { 4634 default: 4635 break; 4636 case Intrinsic::riscv_masked_strided_store: { 4637 SDLoc DL(Op); 4638 MVT XLenVT = Subtarget.getXLenVT(); 4639 4640 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4641 // the selection of the masked intrinsics doesn't do this for us. 4642 SDValue Mask = Op.getOperand(5); 4643 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4644 4645 SDValue Val = Op.getOperand(2); 4646 MVT VT = Val.getSimpleValueType(); 4647 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4648 4649 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4650 if (!IsUnmasked) { 4651 MVT MaskVT = 4652 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4653 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4654 } 4655 4656 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4657 4658 SDValue IntID = DAG.getTargetConstant( 4659 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4660 XLenVT); 4661 4662 auto *Store = cast<MemIntrinsicSDNode>(Op); 4663 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4664 Ops.push_back(Val); 4665 Ops.push_back(Op.getOperand(3)); // Ptr 4666 Ops.push_back(Op.getOperand(4)); // Stride 4667 if (!IsUnmasked) 4668 Ops.push_back(Mask); 4669 Ops.push_back(VL); 4670 4671 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4672 Ops, Store->getMemoryVT(), 4673 Store->getMemOperand()); 4674 } 4675 } 4676 4677 return SDValue(); 4678 } 4679 4680 static MVT getLMUL1VT(MVT VT) { 4681 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4682 "Unexpected vector MVT"); 4683 return MVT::getScalableVectorVT( 4684 VT.getVectorElementType(), 4685 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4686 } 4687 4688 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4689 switch (ISDOpcode) { 4690 default: 4691 llvm_unreachable("Unhandled reduction"); 4692 case ISD::VECREDUCE_ADD: 4693 return RISCVISD::VECREDUCE_ADD_VL; 4694 case ISD::VECREDUCE_UMAX: 4695 return RISCVISD::VECREDUCE_UMAX_VL; 4696 case ISD::VECREDUCE_SMAX: 4697 return RISCVISD::VECREDUCE_SMAX_VL; 4698 case ISD::VECREDUCE_UMIN: 4699 return RISCVISD::VECREDUCE_UMIN_VL; 4700 case ISD::VECREDUCE_SMIN: 4701 return RISCVISD::VECREDUCE_SMIN_VL; 4702 case ISD::VECREDUCE_AND: 4703 return RISCVISD::VECREDUCE_AND_VL; 4704 case ISD::VECREDUCE_OR: 4705 return RISCVISD::VECREDUCE_OR_VL; 4706 case ISD::VECREDUCE_XOR: 4707 return RISCVISD::VECREDUCE_XOR_VL; 4708 } 4709 } 4710 4711 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4712 SelectionDAG &DAG, 4713 bool IsVP) const { 4714 SDLoc DL(Op); 4715 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4716 MVT VecVT = Vec.getSimpleValueType(); 4717 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4718 Op.getOpcode() == ISD::VECREDUCE_OR || 4719 Op.getOpcode() == ISD::VECREDUCE_XOR || 4720 Op.getOpcode() == ISD::VP_REDUCE_AND || 4721 Op.getOpcode() == ISD::VP_REDUCE_OR || 4722 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 4723 "Unexpected reduction lowering"); 4724 4725 MVT XLenVT = Subtarget.getXLenVT(); 4726 assert(Op.getValueType() == XLenVT && 4727 "Expected reduction output to be legalized to XLenVT"); 4728 4729 MVT ContainerVT = VecVT; 4730 if (VecVT.isFixedLengthVector()) { 4731 ContainerVT = getContainerForFixedLengthVector(VecVT); 4732 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4733 } 4734 4735 SDValue Mask, VL; 4736 if (IsVP) { 4737 Mask = Op.getOperand(2); 4738 VL = Op.getOperand(3); 4739 } else { 4740 std::tie(Mask, VL) = 4741 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4742 } 4743 4744 unsigned BaseOpc; 4745 ISD::CondCode CC; 4746 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4747 4748 switch (Op.getOpcode()) { 4749 default: 4750 llvm_unreachable("Unhandled reduction"); 4751 case ISD::VECREDUCE_AND: 4752 case ISD::VP_REDUCE_AND: { 4753 // vcpop ~x == 0 4754 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 4755 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 4756 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4757 CC = ISD::SETEQ; 4758 BaseOpc = ISD::AND; 4759 break; 4760 } 4761 case ISD::VECREDUCE_OR: 4762 case ISD::VP_REDUCE_OR: 4763 // vcpop x != 0 4764 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4765 CC = ISD::SETNE; 4766 BaseOpc = ISD::OR; 4767 break; 4768 case ISD::VECREDUCE_XOR: 4769 case ISD::VP_REDUCE_XOR: { 4770 // ((vcpop x) & 1) != 0 4771 SDValue One = DAG.getConstant(1, DL, XLenVT); 4772 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 4773 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 4774 CC = ISD::SETNE; 4775 BaseOpc = ISD::XOR; 4776 break; 4777 } 4778 } 4779 4780 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 4781 4782 if (!IsVP) 4783 return SetCC; 4784 4785 // Now include the start value in the operation. 4786 // Note that we must return the start value when no elements are operated 4787 // upon. The vcpop instructions we've emitted in each case above will return 4788 // 0 for an inactive vector, and so we've already received the neutral value: 4789 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 4790 // can simply include the start value. 4791 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 4792 } 4793 4794 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 4795 SelectionDAG &DAG) const { 4796 SDLoc DL(Op); 4797 SDValue Vec = Op.getOperand(0); 4798 EVT VecEVT = Vec.getValueType(); 4799 4800 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 4801 4802 // Due to ordering in legalize types we may have a vector type that needs to 4803 // be split. Do that manually so we can get down to a legal type. 4804 while (getTypeAction(*DAG.getContext(), VecEVT) == 4805 TargetLowering::TypeSplitVector) { 4806 SDValue Lo, Hi; 4807 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 4808 VecEVT = Lo.getValueType(); 4809 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 4810 } 4811 4812 // TODO: The type may need to be widened rather than split. Or widened before 4813 // it can be split. 4814 if (!isTypeLegal(VecEVT)) 4815 return SDValue(); 4816 4817 MVT VecVT = VecEVT.getSimpleVT(); 4818 MVT VecEltVT = VecVT.getVectorElementType(); 4819 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 4820 4821 MVT ContainerVT = VecVT; 4822 if (VecVT.isFixedLengthVector()) { 4823 ContainerVT = getContainerForFixedLengthVector(VecVT); 4824 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4825 } 4826 4827 MVT M1VT = getLMUL1VT(ContainerVT); 4828 MVT XLenVT = Subtarget.getXLenVT(); 4829 4830 SDValue Mask, VL; 4831 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4832 4833 SDValue NeutralElem = 4834 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 4835 SDValue IdentitySplat = lowerScalarSplat( 4836 NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4837 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 4838 IdentitySplat, Mask, VL); 4839 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4840 DAG.getConstant(0, DL, XLenVT)); 4841 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4842 } 4843 4844 // Given a reduction op, this function returns the matching reduction opcode, 4845 // the vector SDValue and the scalar SDValue required to lower this to a 4846 // RISCVISD node. 4847 static std::tuple<unsigned, SDValue, SDValue> 4848 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 4849 SDLoc DL(Op); 4850 auto Flags = Op->getFlags(); 4851 unsigned Opcode = Op.getOpcode(); 4852 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 4853 switch (Opcode) { 4854 default: 4855 llvm_unreachable("Unhandled reduction"); 4856 case ISD::VECREDUCE_FADD: { 4857 // Use positive zero if we can. It is cheaper to materialize. 4858 SDValue Zero = 4859 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 4860 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 4861 } 4862 case ISD::VECREDUCE_SEQ_FADD: 4863 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 4864 Op.getOperand(0)); 4865 case ISD::VECREDUCE_FMIN: 4866 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 4867 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4868 case ISD::VECREDUCE_FMAX: 4869 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 4870 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 4871 } 4872 } 4873 4874 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 4875 SelectionDAG &DAG) const { 4876 SDLoc DL(Op); 4877 MVT VecEltVT = Op.getSimpleValueType(); 4878 4879 unsigned RVVOpcode; 4880 SDValue VectorVal, ScalarVal; 4881 std::tie(RVVOpcode, VectorVal, ScalarVal) = 4882 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 4883 MVT VecVT = VectorVal.getSimpleValueType(); 4884 4885 MVT ContainerVT = VecVT; 4886 if (VecVT.isFixedLengthVector()) { 4887 ContainerVT = getContainerForFixedLengthVector(VecVT); 4888 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 4889 } 4890 4891 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 4892 MVT XLenVT = Subtarget.getXLenVT(); 4893 4894 SDValue Mask, VL; 4895 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4896 4897 SDValue ScalarSplat = lowerScalarSplat( 4898 ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget); 4899 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 4900 VectorVal, ScalarSplat, Mask, VL); 4901 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 4902 DAG.getConstant(0, DL, XLenVT)); 4903 } 4904 4905 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 4906 switch (ISDOpcode) { 4907 default: 4908 llvm_unreachable("Unhandled reduction"); 4909 case ISD::VP_REDUCE_ADD: 4910 return RISCVISD::VECREDUCE_ADD_VL; 4911 case ISD::VP_REDUCE_UMAX: 4912 return RISCVISD::VECREDUCE_UMAX_VL; 4913 case ISD::VP_REDUCE_SMAX: 4914 return RISCVISD::VECREDUCE_SMAX_VL; 4915 case ISD::VP_REDUCE_UMIN: 4916 return RISCVISD::VECREDUCE_UMIN_VL; 4917 case ISD::VP_REDUCE_SMIN: 4918 return RISCVISD::VECREDUCE_SMIN_VL; 4919 case ISD::VP_REDUCE_AND: 4920 return RISCVISD::VECREDUCE_AND_VL; 4921 case ISD::VP_REDUCE_OR: 4922 return RISCVISD::VECREDUCE_OR_VL; 4923 case ISD::VP_REDUCE_XOR: 4924 return RISCVISD::VECREDUCE_XOR_VL; 4925 case ISD::VP_REDUCE_FADD: 4926 return RISCVISD::VECREDUCE_FADD_VL; 4927 case ISD::VP_REDUCE_SEQ_FADD: 4928 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 4929 case ISD::VP_REDUCE_FMAX: 4930 return RISCVISD::VECREDUCE_FMAX_VL; 4931 case ISD::VP_REDUCE_FMIN: 4932 return RISCVISD::VECREDUCE_FMIN_VL; 4933 } 4934 } 4935 4936 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 4937 SelectionDAG &DAG) const { 4938 SDLoc DL(Op); 4939 SDValue Vec = Op.getOperand(1); 4940 EVT VecEVT = Vec.getValueType(); 4941 4942 // TODO: The type may need to be widened rather than split. Or widened before 4943 // it can be split. 4944 if (!isTypeLegal(VecEVT)) 4945 return SDValue(); 4946 4947 MVT VecVT = VecEVT.getSimpleVT(); 4948 MVT VecEltVT = VecVT.getVectorElementType(); 4949 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 4950 4951 MVT ContainerVT = VecVT; 4952 if (VecVT.isFixedLengthVector()) { 4953 ContainerVT = getContainerForFixedLengthVector(VecVT); 4954 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4955 } 4956 4957 SDValue VL = Op.getOperand(3); 4958 SDValue Mask = Op.getOperand(2); 4959 4960 MVT M1VT = getLMUL1VT(ContainerVT); 4961 MVT XLenVT = Subtarget.getXLenVT(); 4962 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 4963 4964 SDValue StartSplat = 4965 lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT, 4966 DL, DAG, Subtarget); 4967 SDValue Reduction = 4968 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 4969 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 4970 DAG.getConstant(0, DL, XLenVT)); 4971 if (!VecVT.isInteger()) 4972 return Elt0; 4973 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 4974 } 4975 4976 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4977 SelectionDAG &DAG) const { 4978 SDValue Vec = Op.getOperand(0); 4979 SDValue SubVec = Op.getOperand(1); 4980 MVT VecVT = Vec.getSimpleValueType(); 4981 MVT SubVecVT = SubVec.getSimpleValueType(); 4982 4983 SDLoc DL(Op); 4984 MVT XLenVT = Subtarget.getXLenVT(); 4985 unsigned OrigIdx = Op.getConstantOperandVal(2); 4986 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4987 4988 // We don't have the ability to slide mask vectors up indexed by their i1 4989 // elements; the smallest we can do is i8. Often we are able to bitcast to 4990 // equivalent i8 vectors. Note that when inserting a fixed-length vector 4991 // into a scalable one, we might not necessarily have enough scalable 4992 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 4993 if (SubVecVT.getVectorElementType() == MVT::i1 && 4994 (OrigIdx != 0 || !Vec.isUndef())) { 4995 if (VecVT.getVectorMinNumElements() >= 8 && 4996 SubVecVT.getVectorMinNumElements() >= 8) { 4997 assert(OrigIdx % 8 == 0 && "Invalid index"); 4998 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 4999 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5000 "Unexpected mask vector lowering"); 5001 OrigIdx /= 8; 5002 SubVecVT = 5003 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5004 SubVecVT.isScalableVector()); 5005 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5006 VecVT.isScalableVector()); 5007 Vec = DAG.getBitcast(VecVT, Vec); 5008 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5009 } else { 5010 // We can't slide this mask vector up indexed by its i1 elements. 5011 // This poses a problem when we wish to insert a scalable vector which 5012 // can't be re-expressed as a larger type. Just choose the slow path and 5013 // extend to a larger type, then truncate back down. 5014 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5015 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5016 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5017 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5018 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5019 Op.getOperand(2)); 5020 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5021 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5022 } 5023 } 5024 5025 // If the subvector vector is a fixed-length type, we cannot use subregister 5026 // manipulation to simplify the codegen; we don't know which register of a 5027 // LMUL group contains the specific subvector as we only know the minimum 5028 // register size. Therefore we must slide the vector group up the full 5029 // amount. 5030 if (SubVecVT.isFixedLengthVector()) { 5031 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5032 return Op; 5033 MVT ContainerVT = VecVT; 5034 if (VecVT.isFixedLengthVector()) { 5035 ContainerVT = getContainerForFixedLengthVector(VecVT); 5036 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5037 } 5038 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5039 DAG.getUNDEF(ContainerVT), SubVec, 5040 DAG.getConstant(0, DL, XLenVT)); 5041 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5042 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5043 return DAG.getBitcast(Op.getValueType(), SubVec); 5044 } 5045 SDValue Mask = 5046 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5047 // Set the vector length to only the number of elements we care about. Note 5048 // that for slideup this includes the offset. 5049 SDValue VL = 5050 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5051 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5052 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5053 SubVec, SlideupAmt, Mask, VL); 5054 if (VecVT.isFixedLengthVector()) 5055 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5056 return DAG.getBitcast(Op.getValueType(), Slideup); 5057 } 5058 5059 unsigned SubRegIdx, RemIdx; 5060 std::tie(SubRegIdx, RemIdx) = 5061 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5062 VecVT, SubVecVT, OrigIdx, TRI); 5063 5064 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5065 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5066 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5067 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5068 5069 // 1. If the Idx has been completely eliminated and this subvector's size is 5070 // a vector register or a multiple thereof, or the surrounding elements are 5071 // undef, then this is a subvector insert which naturally aligns to a vector 5072 // register. These can easily be handled using subregister manipulation. 5073 // 2. If the subvector is smaller than a vector register, then the insertion 5074 // must preserve the undisturbed elements of the register. We do this by 5075 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5076 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5077 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5078 // LMUL=1 type back into the larger vector (resolving to another subregister 5079 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5080 // to avoid allocating a large register group to hold our subvector. 5081 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5082 return Op; 5083 5084 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5085 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5086 // (in our case undisturbed). This means we can set up a subvector insertion 5087 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5088 // size of the subvector. 5089 MVT InterSubVT = VecVT; 5090 SDValue AlignedExtract = Vec; 5091 unsigned AlignedIdx = OrigIdx - RemIdx; 5092 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5093 InterSubVT = getLMUL1VT(VecVT); 5094 // Extract a subvector equal to the nearest full vector register type. This 5095 // should resolve to a EXTRACT_SUBREG instruction. 5096 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5097 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5098 } 5099 5100 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5101 // For scalable vectors this must be further multiplied by vscale. 5102 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5103 5104 SDValue Mask, VL; 5105 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5106 5107 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5108 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5109 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5110 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5111 5112 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5113 DAG.getUNDEF(InterSubVT), SubVec, 5114 DAG.getConstant(0, DL, XLenVT)); 5115 5116 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5117 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5118 5119 // If required, insert this subvector back into the correct vector register. 5120 // This should resolve to an INSERT_SUBREG instruction. 5121 if (VecVT.bitsGT(InterSubVT)) 5122 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5123 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5124 5125 // We might have bitcast from a mask type: cast back to the original type if 5126 // required. 5127 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5128 } 5129 5130 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5131 SelectionDAG &DAG) const { 5132 SDValue Vec = Op.getOperand(0); 5133 MVT SubVecVT = Op.getSimpleValueType(); 5134 MVT VecVT = Vec.getSimpleValueType(); 5135 5136 SDLoc DL(Op); 5137 MVT XLenVT = Subtarget.getXLenVT(); 5138 unsigned OrigIdx = Op.getConstantOperandVal(1); 5139 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5140 5141 // We don't have the ability to slide mask vectors down indexed by their i1 5142 // elements; the smallest we can do is i8. Often we are able to bitcast to 5143 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5144 // from a scalable one, we might not necessarily have enough scalable 5145 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5146 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5147 if (VecVT.getVectorMinNumElements() >= 8 && 5148 SubVecVT.getVectorMinNumElements() >= 8) { 5149 assert(OrigIdx % 8 == 0 && "Invalid index"); 5150 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5151 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5152 "Unexpected mask vector lowering"); 5153 OrigIdx /= 8; 5154 SubVecVT = 5155 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5156 SubVecVT.isScalableVector()); 5157 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5158 VecVT.isScalableVector()); 5159 Vec = DAG.getBitcast(VecVT, Vec); 5160 } else { 5161 // We can't slide this mask vector down, indexed by its i1 elements. 5162 // This poses a problem when we wish to extract a scalable vector which 5163 // can't be re-expressed as a larger type. Just choose the slow path and 5164 // extend to a larger type, then truncate back down. 5165 // TODO: We could probably improve this when extracting certain fixed 5166 // from fixed, where we can extract as i8 and shift the correct element 5167 // right to reach the desired subvector? 5168 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5169 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5170 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5171 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5172 Op.getOperand(1)); 5173 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5174 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5175 } 5176 } 5177 5178 // If the subvector vector is a fixed-length type, we cannot use subregister 5179 // manipulation to simplify the codegen; we don't know which register of a 5180 // LMUL group contains the specific subvector as we only know the minimum 5181 // register size. Therefore we must slide the vector group down the full 5182 // amount. 5183 if (SubVecVT.isFixedLengthVector()) { 5184 // With an index of 0 this is a cast-like subvector, which can be performed 5185 // with subregister operations. 5186 if (OrigIdx == 0) 5187 return Op; 5188 MVT ContainerVT = VecVT; 5189 if (VecVT.isFixedLengthVector()) { 5190 ContainerVT = getContainerForFixedLengthVector(VecVT); 5191 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5192 } 5193 SDValue Mask = 5194 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5195 // Set the vector length to only the number of elements we care about. This 5196 // avoids sliding down elements we're going to discard straight away. 5197 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5198 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5199 SDValue Slidedown = 5200 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5201 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5202 // Now we can use a cast-like subvector extract to get the result. 5203 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5204 DAG.getConstant(0, DL, XLenVT)); 5205 return DAG.getBitcast(Op.getValueType(), Slidedown); 5206 } 5207 5208 unsigned SubRegIdx, RemIdx; 5209 std::tie(SubRegIdx, RemIdx) = 5210 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5211 VecVT, SubVecVT, OrigIdx, TRI); 5212 5213 // If the Idx has been completely eliminated then this is a subvector extract 5214 // which naturally aligns to a vector register. These can easily be handled 5215 // using subregister manipulation. 5216 if (RemIdx == 0) 5217 return Op; 5218 5219 // Else we must shift our vector register directly to extract the subvector. 5220 // Do this using VSLIDEDOWN. 5221 5222 // If the vector type is an LMUL-group type, extract a subvector equal to the 5223 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5224 // instruction. 5225 MVT InterSubVT = VecVT; 5226 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5227 InterSubVT = getLMUL1VT(VecVT); 5228 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5229 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5230 } 5231 5232 // Slide this vector register down by the desired number of elements in order 5233 // to place the desired subvector starting at element 0. 5234 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5235 // For scalable vectors this must be further multiplied by vscale. 5236 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5237 5238 SDValue Mask, VL; 5239 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5240 SDValue Slidedown = 5241 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5242 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5243 5244 // Now the vector is in the right position, extract our final subvector. This 5245 // should resolve to a COPY. 5246 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5247 DAG.getConstant(0, DL, XLenVT)); 5248 5249 // We might have bitcast from a mask type: cast back to the original type if 5250 // required. 5251 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5252 } 5253 5254 // Lower step_vector to the vid instruction. Any non-identity step value must 5255 // be accounted for my manual expansion. 5256 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5257 SelectionDAG &DAG) const { 5258 SDLoc DL(Op); 5259 MVT VT = Op.getSimpleValueType(); 5260 MVT XLenVT = Subtarget.getXLenVT(); 5261 SDValue Mask, VL; 5262 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5263 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5264 uint64_t StepValImm = Op.getConstantOperandVal(0); 5265 if (StepValImm != 1) { 5266 if (isPowerOf2_64(StepValImm)) { 5267 SDValue StepVal = 5268 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 5269 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5270 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5271 } else { 5272 SDValue StepVal = lowerScalarSplat( 5273 DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT, 5274 DL, DAG, Subtarget); 5275 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5276 } 5277 } 5278 return StepVec; 5279 } 5280 5281 // Implement vector_reverse using vrgather.vv with indices determined by 5282 // subtracting the id of each element from (VLMAX-1). This will convert 5283 // the indices like so: 5284 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5285 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5286 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5287 SelectionDAG &DAG) const { 5288 SDLoc DL(Op); 5289 MVT VecVT = Op.getSimpleValueType(); 5290 unsigned EltSize = VecVT.getScalarSizeInBits(); 5291 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5292 5293 unsigned MaxVLMAX = 0; 5294 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5295 if (VectorBitsMax != 0) 5296 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 5297 5298 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5299 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5300 5301 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5302 // to use vrgatherei16.vv. 5303 // TODO: It's also possible to use vrgatherei16.vv for other types to 5304 // decrease register width for the index calculation. 5305 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5306 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5307 // Reverse each half, then reassemble them in reverse order. 5308 // NOTE: It's also possible that after splitting that VLMAX no longer 5309 // requires vrgatherei16.vv. 5310 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5311 SDValue Lo, Hi; 5312 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5313 EVT LoVT, HiVT; 5314 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5315 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5316 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5317 // Reassemble the low and high pieces reversed. 5318 // FIXME: This is a CONCAT_VECTORS. 5319 SDValue Res = 5320 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5321 DAG.getIntPtrConstant(0, DL)); 5322 return DAG.getNode( 5323 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5324 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5325 } 5326 5327 // Just promote the int type to i16 which will double the LMUL. 5328 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5329 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5330 } 5331 5332 MVT XLenVT = Subtarget.getXLenVT(); 5333 SDValue Mask, VL; 5334 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5335 5336 // Calculate VLMAX-1 for the desired SEW. 5337 unsigned MinElts = VecVT.getVectorMinNumElements(); 5338 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5339 DAG.getConstant(MinElts, DL, XLenVT)); 5340 SDValue VLMinus1 = 5341 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5342 5343 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5344 bool IsRV32E64 = 5345 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5346 SDValue SplatVL; 5347 if (!IsRV32E64) 5348 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5349 else 5350 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 5351 5352 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5353 SDValue Indices = 5354 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5355 5356 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5357 } 5358 5359 SDValue 5360 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5361 SelectionDAG &DAG) const { 5362 SDLoc DL(Op); 5363 auto *Load = cast<LoadSDNode>(Op); 5364 5365 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5366 Load->getMemoryVT(), 5367 *Load->getMemOperand()) && 5368 "Expecting a correctly-aligned load"); 5369 5370 MVT VT = Op.getSimpleValueType(); 5371 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5372 5373 SDValue VL = 5374 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5375 5376 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5377 SDValue NewLoad = DAG.getMemIntrinsicNode( 5378 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 5379 Load->getMemoryVT(), Load->getMemOperand()); 5380 5381 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5382 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5383 } 5384 5385 SDValue 5386 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5387 SelectionDAG &DAG) const { 5388 SDLoc DL(Op); 5389 auto *Store = cast<StoreSDNode>(Op); 5390 5391 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5392 Store->getMemoryVT(), 5393 *Store->getMemOperand()) && 5394 "Expecting a correctly-aligned store"); 5395 5396 SDValue StoreVal = Store->getValue(); 5397 MVT VT = StoreVal.getSimpleValueType(); 5398 5399 // If the size less than a byte, we need to pad with zeros to make a byte. 5400 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5401 VT = MVT::v8i1; 5402 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5403 DAG.getConstant(0, DL, VT), StoreVal, 5404 DAG.getIntPtrConstant(0, DL)); 5405 } 5406 5407 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5408 5409 SDValue VL = 5410 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5411 5412 SDValue NewValue = 5413 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5414 return DAG.getMemIntrinsicNode( 5415 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 5416 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 5417 Store->getMemoryVT(), Store->getMemOperand()); 5418 } 5419 5420 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5421 SelectionDAG &DAG) const { 5422 SDLoc DL(Op); 5423 MVT VT = Op.getSimpleValueType(); 5424 5425 const auto *MemSD = cast<MemSDNode>(Op); 5426 EVT MemVT = MemSD->getMemoryVT(); 5427 MachineMemOperand *MMO = MemSD->getMemOperand(); 5428 SDValue Chain = MemSD->getChain(); 5429 SDValue BasePtr = MemSD->getBasePtr(); 5430 5431 SDValue Mask, PassThru, VL; 5432 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5433 Mask = VPLoad->getMask(); 5434 PassThru = DAG.getUNDEF(VT); 5435 VL = VPLoad->getVectorLength(); 5436 } else { 5437 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5438 Mask = MLoad->getMask(); 5439 PassThru = MLoad->getPassThru(); 5440 } 5441 5442 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5443 5444 MVT XLenVT = Subtarget.getXLenVT(); 5445 5446 MVT ContainerVT = VT; 5447 if (VT.isFixedLengthVector()) { 5448 ContainerVT = getContainerForFixedLengthVector(VT); 5449 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5450 if (!IsUnmasked) { 5451 MVT MaskVT = 5452 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5453 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5454 } 5455 } 5456 5457 if (!VL) 5458 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5459 5460 unsigned IntID = 5461 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5462 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5463 if (IsUnmasked) 5464 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5465 else 5466 Ops.push_back(PassThru); 5467 Ops.push_back(BasePtr); 5468 if (!IsUnmasked) 5469 Ops.push_back(Mask); 5470 Ops.push_back(VL); 5471 if (!IsUnmasked) 5472 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5473 5474 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5475 5476 SDValue Result = 5477 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5478 Chain = Result.getValue(1); 5479 5480 if (VT.isFixedLengthVector()) 5481 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5482 5483 return DAG.getMergeValues({Result, Chain}, DL); 5484 } 5485 5486 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5487 SelectionDAG &DAG) const { 5488 SDLoc DL(Op); 5489 5490 const auto *MemSD = cast<MemSDNode>(Op); 5491 EVT MemVT = MemSD->getMemoryVT(); 5492 MachineMemOperand *MMO = MemSD->getMemOperand(); 5493 SDValue Chain = MemSD->getChain(); 5494 SDValue BasePtr = MemSD->getBasePtr(); 5495 SDValue Val, Mask, VL; 5496 5497 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5498 Val = VPStore->getValue(); 5499 Mask = VPStore->getMask(); 5500 VL = VPStore->getVectorLength(); 5501 } else { 5502 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5503 Val = MStore->getValue(); 5504 Mask = MStore->getMask(); 5505 } 5506 5507 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5508 5509 MVT VT = Val.getSimpleValueType(); 5510 MVT XLenVT = Subtarget.getXLenVT(); 5511 5512 MVT ContainerVT = VT; 5513 if (VT.isFixedLengthVector()) { 5514 ContainerVT = getContainerForFixedLengthVector(VT); 5515 5516 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5517 if (!IsUnmasked) { 5518 MVT MaskVT = 5519 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5520 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5521 } 5522 } 5523 5524 if (!VL) 5525 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5526 5527 unsigned IntID = 5528 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5529 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5530 Ops.push_back(Val); 5531 Ops.push_back(BasePtr); 5532 if (!IsUnmasked) 5533 Ops.push_back(Mask); 5534 Ops.push_back(VL); 5535 5536 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5537 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5538 } 5539 5540 SDValue 5541 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5542 SelectionDAG &DAG) const { 5543 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5544 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5545 5546 MVT VT = Op.getSimpleValueType(); 5547 5548 SDValue Op1 = 5549 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5550 SDValue Op2 = 5551 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5552 5553 SDLoc DL(Op); 5554 SDValue VL = 5555 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5556 5557 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5558 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 5559 5560 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5561 Op.getOperand(2), Mask, VL); 5562 5563 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5564 } 5565 5566 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5567 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5568 MVT VT = Op.getSimpleValueType(); 5569 5570 if (VT.getVectorElementType() == MVT::i1) 5571 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5572 5573 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5574 } 5575 5576 SDValue 5577 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5578 SelectionDAG &DAG) const { 5579 unsigned Opc; 5580 switch (Op.getOpcode()) { 5581 default: llvm_unreachable("Unexpected opcode!"); 5582 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5583 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5584 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5585 } 5586 5587 return lowerToScalableOp(Op, DAG, Opc); 5588 } 5589 5590 // Lower vector ABS to smax(X, sub(0, X)). 5591 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5592 SDLoc DL(Op); 5593 MVT VT = Op.getSimpleValueType(); 5594 SDValue X = Op.getOperand(0); 5595 5596 assert(VT.isFixedLengthVector() && "Unexpected type"); 5597 5598 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5599 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5600 5601 SDValue Mask, VL; 5602 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5603 5604 SDValue SplatZero = 5605 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 5606 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5607 SDValue NegX = 5608 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5609 SDValue Max = 5610 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5611 5612 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5613 } 5614 5615 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5616 SDValue Op, SelectionDAG &DAG) const { 5617 SDLoc DL(Op); 5618 MVT VT = Op.getSimpleValueType(); 5619 SDValue Mag = Op.getOperand(0); 5620 SDValue Sign = Op.getOperand(1); 5621 assert(Mag.getValueType() == Sign.getValueType() && 5622 "Can only handle COPYSIGN with matching types."); 5623 5624 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5625 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5626 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5627 5628 SDValue Mask, VL; 5629 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5630 5631 SDValue CopySign = 5632 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5633 5634 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5635 } 5636 5637 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5638 SDValue Op, SelectionDAG &DAG) const { 5639 MVT VT = Op.getSimpleValueType(); 5640 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5641 5642 MVT I1ContainerVT = 5643 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5644 5645 SDValue CC = 5646 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5647 SDValue Op1 = 5648 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5649 SDValue Op2 = 5650 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5651 5652 SDLoc DL(Op); 5653 SDValue Mask, VL; 5654 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5655 5656 SDValue Select = 5657 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5658 5659 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5660 } 5661 5662 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5663 unsigned NewOpc, 5664 bool HasMask) const { 5665 MVT VT = Op.getSimpleValueType(); 5666 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5667 5668 // Create list of operands by converting existing ones to scalable types. 5669 SmallVector<SDValue, 6> Ops; 5670 for (const SDValue &V : Op->op_values()) { 5671 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5672 5673 // Pass through non-vector operands. 5674 if (!V.getValueType().isVector()) { 5675 Ops.push_back(V); 5676 continue; 5677 } 5678 5679 // "cast" fixed length vector to a scalable vector. 5680 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 5681 "Only fixed length vectors are supported!"); 5682 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5683 } 5684 5685 SDLoc DL(Op); 5686 SDValue Mask, VL; 5687 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5688 if (HasMask) 5689 Ops.push_back(Mask); 5690 Ops.push_back(VL); 5691 5692 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 5693 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 5694 } 5695 5696 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 5697 // * Operands of each node are assumed to be in the same order. 5698 // * The EVL operand is promoted from i32 to i64 on RV64. 5699 // * Fixed-length vectors are converted to their scalable-vector container 5700 // types. 5701 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 5702 unsigned RISCVISDOpc) const { 5703 SDLoc DL(Op); 5704 MVT VT = Op.getSimpleValueType(); 5705 SmallVector<SDValue, 4> Ops; 5706 5707 for (const auto &OpIdx : enumerate(Op->ops())) { 5708 SDValue V = OpIdx.value(); 5709 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 5710 // Pass through operands which aren't fixed-length vectors. 5711 if (!V.getValueType().isFixedLengthVector()) { 5712 Ops.push_back(V); 5713 continue; 5714 } 5715 // "cast" fixed length vector to a scalable vector. 5716 MVT OpVT = V.getSimpleValueType(); 5717 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 5718 assert(useRVVForFixedLengthVectorVT(OpVT) && 5719 "Only fixed length vectors are supported!"); 5720 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 5721 } 5722 5723 if (!VT.isFixedLengthVector()) 5724 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 5725 5726 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5727 5728 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 5729 5730 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 5731 } 5732 5733 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 5734 unsigned MaskOpc, 5735 unsigned VecOpc) const { 5736 MVT VT = Op.getSimpleValueType(); 5737 if (VT.getVectorElementType() != MVT::i1) 5738 return lowerVPOp(Op, DAG, VecOpc); 5739 5740 // It is safe to drop mask parameter as masked-off elements are undef. 5741 SDValue Op1 = Op->getOperand(0); 5742 SDValue Op2 = Op->getOperand(1); 5743 SDValue VL = Op->getOperand(3); 5744 5745 MVT ContainerVT = VT; 5746 const bool IsFixed = VT.isFixedLengthVector(); 5747 if (IsFixed) { 5748 ContainerVT = getContainerForFixedLengthVector(VT); 5749 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 5750 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 5751 } 5752 5753 SDLoc DL(Op); 5754 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 5755 if (!IsFixed) 5756 return Val; 5757 return convertFromScalableVector(VT, Val, DAG, Subtarget); 5758 } 5759 5760 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 5761 // matched to a RVV indexed load. The RVV indexed load instructions only 5762 // support the "unsigned unscaled" addressing mode; indices are implicitly 5763 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5764 // signed or scaled indexing is extended to the XLEN value type and scaled 5765 // accordingly. 5766 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 5767 SelectionDAG &DAG) const { 5768 SDLoc DL(Op); 5769 MVT VT = Op.getSimpleValueType(); 5770 5771 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5772 EVT MemVT = MemSD->getMemoryVT(); 5773 MachineMemOperand *MMO = MemSD->getMemOperand(); 5774 SDValue Chain = MemSD->getChain(); 5775 SDValue BasePtr = MemSD->getBasePtr(); 5776 5777 ISD::LoadExtType LoadExtType; 5778 SDValue Index, Mask, PassThru, VL; 5779 5780 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 5781 Index = VPGN->getIndex(); 5782 Mask = VPGN->getMask(); 5783 PassThru = DAG.getUNDEF(VT); 5784 VL = VPGN->getVectorLength(); 5785 // VP doesn't support extending loads. 5786 LoadExtType = ISD::NON_EXTLOAD; 5787 } else { 5788 // Else it must be a MGATHER. 5789 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 5790 Index = MGN->getIndex(); 5791 Mask = MGN->getMask(); 5792 PassThru = MGN->getPassThru(); 5793 LoadExtType = MGN->getExtensionType(); 5794 } 5795 5796 MVT IndexVT = Index.getSimpleValueType(); 5797 MVT XLenVT = Subtarget.getXLenVT(); 5798 5799 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5800 "Unexpected VTs!"); 5801 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5802 // Targets have to explicitly opt-in for extending vector loads. 5803 assert(LoadExtType == ISD::NON_EXTLOAD && 5804 "Unexpected extending MGATHER/VP_GATHER"); 5805 (void)LoadExtType; 5806 5807 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5808 // the selection of the masked intrinsics doesn't do this for us. 5809 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5810 5811 MVT ContainerVT = VT; 5812 if (VT.isFixedLengthVector()) { 5813 // We need to use the larger of the result and index type to determine the 5814 // scalable type to use so we don't increase LMUL for any operand/result. 5815 if (VT.bitsGE(IndexVT)) { 5816 ContainerVT = getContainerForFixedLengthVector(VT); 5817 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5818 ContainerVT.getVectorElementCount()); 5819 } else { 5820 IndexVT = getContainerForFixedLengthVector(IndexVT); 5821 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 5822 IndexVT.getVectorElementCount()); 5823 } 5824 5825 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5826 5827 if (!IsUnmasked) { 5828 MVT MaskVT = 5829 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5830 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5831 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5832 } 5833 } 5834 5835 if (!VL) 5836 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5837 5838 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5839 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5840 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 5841 VL); 5842 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 5843 TrueMask, VL); 5844 } 5845 5846 unsigned IntID = 5847 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 5848 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5849 if (IsUnmasked) 5850 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5851 else 5852 Ops.push_back(PassThru); 5853 Ops.push_back(BasePtr); 5854 Ops.push_back(Index); 5855 if (!IsUnmasked) 5856 Ops.push_back(Mask); 5857 Ops.push_back(VL); 5858 if (!IsUnmasked) 5859 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5860 5861 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5862 SDValue Result = 5863 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5864 Chain = Result.getValue(1); 5865 5866 if (VT.isFixedLengthVector()) 5867 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5868 5869 return DAG.getMergeValues({Result, Chain}, DL); 5870 } 5871 5872 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 5873 // matched to a RVV indexed store. The RVV indexed store instructions only 5874 // support the "unsigned unscaled" addressing mode; indices are implicitly 5875 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 5876 // signed or scaled indexing is extended to the XLEN value type and scaled 5877 // accordingly. 5878 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 5879 SelectionDAG &DAG) const { 5880 SDLoc DL(Op); 5881 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 5882 EVT MemVT = MemSD->getMemoryVT(); 5883 MachineMemOperand *MMO = MemSD->getMemOperand(); 5884 SDValue Chain = MemSD->getChain(); 5885 SDValue BasePtr = MemSD->getBasePtr(); 5886 5887 bool IsTruncatingStore = false; 5888 SDValue Index, Mask, Val, VL; 5889 5890 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 5891 Index = VPSN->getIndex(); 5892 Mask = VPSN->getMask(); 5893 Val = VPSN->getValue(); 5894 VL = VPSN->getVectorLength(); 5895 // VP doesn't support truncating stores. 5896 IsTruncatingStore = false; 5897 } else { 5898 // Else it must be a MSCATTER. 5899 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 5900 Index = MSN->getIndex(); 5901 Mask = MSN->getMask(); 5902 Val = MSN->getValue(); 5903 IsTruncatingStore = MSN->isTruncatingStore(); 5904 } 5905 5906 MVT VT = Val.getSimpleValueType(); 5907 MVT IndexVT = Index.getSimpleValueType(); 5908 MVT XLenVT = Subtarget.getXLenVT(); 5909 5910 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 5911 "Unexpected VTs!"); 5912 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 5913 // Targets have to explicitly opt-in for extending vector loads and 5914 // truncating vector stores. 5915 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 5916 (void)IsTruncatingStore; 5917 5918 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5919 // the selection of the masked intrinsics doesn't do this for us. 5920 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5921 5922 MVT ContainerVT = VT; 5923 if (VT.isFixedLengthVector()) { 5924 // We need to use the larger of the value and index type to determine the 5925 // scalable type to use so we don't increase LMUL for any operand/result. 5926 if (VT.bitsGE(IndexVT)) { 5927 ContainerVT = getContainerForFixedLengthVector(VT); 5928 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 5929 ContainerVT.getVectorElementCount()); 5930 } else { 5931 IndexVT = getContainerForFixedLengthVector(IndexVT); 5932 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 5933 IndexVT.getVectorElementCount()); 5934 } 5935 5936 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 5937 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5938 5939 if (!IsUnmasked) { 5940 MVT MaskVT = 5941 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5942 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5943 } 5944 } 5945 5946 if (!VL) 5947 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5948 5949 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 5950 IndexVT = IndexVT.changeVectorElementType(XLenVT); 5951 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 5952 VL); 5953 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 5954 TrueMask, VL); 5955 } 5956 5957 unsigned IntID = 5958 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 5959 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5960 Ops.push_back(Val); 5961 Ops.push_back(BasePtr); 5962 Ops.push_back(Index); 5963 if (!IsUnmasked) 5964 Ops.push_back(Mask); 5965 Ops.push_back(VL); 5966 5967 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5968 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5969 } 5970 5971 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 5972 SelectionDAG &DAG) const { 5973 const MVT XLenVT = Subtarget.getXLenVT(); 5974 SDLoc DL(Op); 5975 SDValue Chain = Op->getOperand(0); 5976 SDValue SysRegNo = DAG.getTargetConstant( 5977 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 5978 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 5979 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 5980 5981 // Encoding used for rounding mode in RISCV differs from that used in 5982 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 5983 // table, which consists of a sequence of 4-bit fields, each representing 5984 // corresponding FLT_ROUNDS mode. 5985 static const int Table = 5986 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 5987 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 5988 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 5989 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 5990 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 5991 5992 SDValue Shift = 5993 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 5994 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 5995 DAG.getConstant(Table, DL, XLenVT), Shift); 5996 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 5997 DAG.getConstant(7, DL, XLenVT)); 5998 5999 return DAG.getMergeValues({Masked, Chain}, DL); 6000 } 6001 6002 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6003 SelectionDAG &DAG) const { 6004 const MVT XLenVT = Subtarget.getXLenVT(); 6005 SDLoc DL(Op); 6006 SDValue Chain = Op->getOperand(0); 6007 SDValue RMValue = Op->getOperand(1); 6008 SDValue SysRegNo = DAG.getTargetConstant( 6009 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6010 6011 // Encoding used for rounding mode in RISCV differs from that used in 6012 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6013 // a table, which consists of a sequence of 4-bit fields, each representing 6014 // corresponding RISCV mode. 6015 static const unsigned Table = 6016 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6017 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6018 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6019 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6020 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6021 6022 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6023 DAG.getConstant(2, DL, XLenVT)); 6024 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6025 DAG.getConstant(Table, DL, XLenVT), Shift); 6026 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6027 DAG.getConstant(0x7, DL, XLenVT)); 6028 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6029 RMValue); 6030 } 6031 6032 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6033 switch (IntNo) { 6034 default: 6035 llvm_unreachable("Unexpected Intrinsic"); 6036 case Intrinsic::riscv_grev: 6037 return RISCVISD::GREVW; 6038 case Intrinsic::riscv_gorc: 6039 return RISCVISD::GORCW; 6040 case Intrinsic::riscv_bcompress: 6041 return RISCVISD::BCOMPRESSW; 6042 case Intrinsic::riscv_bdecompress: 6043 return RISCVISD::BDECOMPRESSW; 6044 case Intrinsic::riscv_bfp: 6045 return RISCVISD::BFPW; 6046 case Intrinsic::riscv_fsl: 6047 return RISCVISD::FSLW; 6048 case Intrinsic::riscv_fsr: 6049 return RISCVISD::FSRW; 6050 } 6051 } 6052 6053 // Converts the given intrinsic to a i64 operation with any extension. 6054 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6055 unsigned IntNo) { 6056 SDLoc DL(N); 6057 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6058 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6059 SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6060 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2); 6061 // ReplaceNodeResults requires we maintain the same type for the return value. 6062 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6063 } 6064 6065 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6066 // form of the given Opcode. 6067 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6068 switch (Opcode) { 6069 default: 6070 llvm_unreachable("Unexpected opcode"); 6071 case ISD::SHL: 6072 return RISCVISD::SLLW; 6073 case ISD::SRA: 6074 return RISCVISD::SRAW; 6075 case ISD::SRL: 6076 return RISCVISD::SRLW; 6077 case ISD::SDIV: 6078 return RISCVISD::DIVW; 6079 case ISD::UDIV: 6080 return RISCVISD::DIVUW; 6081 case ISD::UREM: 6082 return RISCVISD::REMUW; 6083 case ISD::ROTL: 6084 return RISCVISD::ROLW; 6085 case ISD::ROTR: 6086 return RISCVISD::RORW; 6087 case RISCVISD::GREV: 6088 return RISCVISD::GREVW; 6089 case RISCVISD::GORC: 6090 return RISCVISD::GORCW; 6091 } 6092 } 6093 6094 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6095 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6096 // otherwise be promoted to i64, making it difficult to select the 6097 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6098 // type i8/i16/i32 is lost. 6099 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6100 unsigned ExtOpc = ISD::ANY_EXTEND) { 6101 SDLoc DL(N); 6102 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6103 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6104 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6105 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6106 // ReplaceNodeResults requires we maintain the same type for the return value. 6107 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6108 } 6109 6110 // Converts the given 32-bit operation to a i64 operation with signed extension 6111 // semantic to reduce the signed extension instructions. 6112 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6113 SDLoc DL(N); 6114 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6115 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6116 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6117 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6118 DAG.getValueType(MVT::i32)); 6119 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6120 } 6121 6122 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6123 SmallVectorImpl<SDValue> &Results, 6124 SelectionDAG &DAG) const { 6125 SDLoc DL(N); 6126 switch (N->getOpcode()) { 6127 default: 6128 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6129 case ISD::STRICT_FP_TO_SINT: 6130 case ISD::STRICT_FP_TO_UINT: 6131 case ISD::FP_TO_SINT: 6132 case ISD::FP_TO_UINT: { 6133 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6134 "Unexpected custom legalisation"); 6135 bool IsStrict = N->isStrictFPOpcode(); 6136 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6137 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6138 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6139 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6140 TargetLowering::TypeSoftenFloat) { 6141 if (!isTypeLegal(Op0.getValueType())) 6142 return; 6143 if (IsStrict) { 6144 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6145 : RISCVISD::STRICT_FCVT_WU_RV64; 6146 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6147 SDValue Res = DAG.getNode( 6148 Opc, DL, VTs, N->getOperand(0), Op0, 6149 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6150 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6151 Results.push_back(Res.getValue(1)); 6152 return; 6153 } 6154 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6155 SDValue Res = 6156 DAG.getNode(Opc, DL, MVT::i64, Op0, 6157 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6158 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6159 return; 6160 } 6161 // If the FP type needs to be softened, emit a library call using the 'si' 6162 // version. If we left it to default legalization we'd end up with 'di'. If 6163 // the FP type doesn't need to be softened just let generic type 6164 // legalization promote the result type. 6165 RTLIB::Libcall LC; 6166 if (IsSigned) 6167 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6168 else 6169 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6170 MakeLibCallOptions CallOptions; 6171 EVT OpVT = Op0.getValueType(); 6172 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6173 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6174 SDValue Result; 6175 std::tie(Result, Chain) = 6176 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6177 Results.push_back(Result); 6178 if (IsStrict) 6179 Results.push_back(Chain); 6180 break; 6181 } 6182 case ISD::READCYCLECOUNTER: { 6183 assert(!Subtarget.is64Bit() && 6184 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6185 6186 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6187 SDValue RCW = 6188 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6189 6190 Results.push_back( 6191 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6192 Results.push_back(RCW.getValue(2)); 6193 break; 6194 } 6195 case ISD::MUL: { 6196 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6197 unsigned XLen = Subtarget.getXLen(); 6198 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6199 if (Size > XLen) { 6200 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6201 SDValue LHS = N->getOperand(0); 6202 SDValue RHS = N->getOperand(1); 6203 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6204 6205 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6206 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6207 // We need exactly one side to be unsigned. 6208 if (LHSIsU == RHSIsU) 6209 return; 6210 6211 auto MakeMULPair = [&](SDValue S, SDValue U) { 6212 MVT XLenVT = Subtarget.getXLenVT(); 6213 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6214 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6215 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6216 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6217 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6218 }; 6219 6220 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6221 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6222 6223 // The other operand should be signed, but still prefer MULH when 6224 // possible. 6225 if (RHSIsU && LHSIsS && !RHSIsS) 6226 Results.push_back(MakeMULPair(LHS, RHS)); 6227 else if (LHSIsU && RHSIsS && !LHSIsS) 6228 Results.push_back(MakeMULPair(RHS, LHS)); 6229 6230 return; 6231 } 6232 LLVM_FALLTHROUGH; 6233 } 6234 case ISD::ADD: 6235 case ISD::SUB: 6236 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6237 "Unexpected custom legalisation"); 6238 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6239 break; 6240 case ISD::SHL: 6241 case ISD::SRA: 6242 case ISD::SRL: 6243 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6244 "Unexpected custom legalisation"); 6245 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6246 Results.push_back(customLegalizeToWOp(N, DAG)); 6247 break; 6248 } 6249 6250 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6251 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6252 // shift amount. 6253 if (N->getOpcode() == ISD::SHL) { 6254 SDLoc DL(N); 6255 SDValue NewOp0 = 6256 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6257 SDValue NewOp1 = 6258 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6259 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6260 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6261 DAG.getValueType(MVT::i32)); 6262 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6263 } 6264 6265 break; 6266 case ISD::ROTL: 6267 case ISD::ROTR: 6268 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6269 "Unexpected custom legalisation"); 6270 Results.push_back(customLegalizeToWOp(N, DAG)); 6271 break; 6272 case ISD::CTTZ: 6273 case ISD::CTTZ_ZERO_UNDEF: 6274 case ISD::CTLZ: 6275 case ISD::CTLZ_ZERO_UNDEF: { 6276 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6277 "Unexpected custom legalisation"); 6278 6279 SDValue NewOp0 = 6280 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6281 bool IsCTZ = 6282 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6283 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6284 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6285 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6286 return; 6287 } 6288 case ISD::SDIV: 6289 case ISD::UDIV: 6290 case ISD::UREM: { 6291 MVT VT = N->getSimpleValueType(0); 6292 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6293 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6294 "Unexpected custom legalisation"); 6295 // Don't promote division/remainder by constant since we should expand those 6296 // to multiply by magic constant. 6297 // FIXME: What if the expansion is disabled for minsize. 6298 if (N->getOperand(1).getOpcode() == ISD::Constant) 6299 return; 6300 6301 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6302 // the upper 32 bits. For other types we need to sign or zero extend 6303 // based on the opcode. 6304 unsigned ExtOpc = ISD::ANY_EXTEND; 6305 if (VT != MVT::i32) 6306 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6307 : ISD::ZERO_EXTEND; 6308 6309 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6310 break; 6311 } 6312 case ISD::UADDO: 6313 case ISD::USUBO: { 6314 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6315 "Unexpected custom legalisation"); 6316 bool IsAdd = N->getOpcode() == ISD::UADDO; 6317 // Create an ADDW or SUBW. 6318 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6319 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6320 SDValue Res = 6321 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6322 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6323 DAG.getValueType(MVT::i32)); 6324 6325 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 6326 // Since the inputs are sign extended from i32, this is equivalent to 6327 // comparing the lower 32 bits. 6328 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6329 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6330 IsAdd ? ISD::SETULT : ISD::SETUGT); 6331 6332 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6333 Results.push_back(Overflow); 6334 return; 6335 } 6336 case ISD::UADDSAT: 6337 case ISD::USUBSAT: { 6338 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6339 "Unexpected custom legalisation"); 6340 if (Subtarget.hasStdExtZbb()) { 6341 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6342 // sign extend allows overflow of the lower 32 bits to be detected on 6343 // the promoted size. 6344 SDValue LHS = 6345 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6346 SDValue RHS = 6347 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6348 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6349 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6350 return; 6351 } 6352 6353 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6354 // promotion for UADDO/USUBO. 6355 Results.push_back(expandAddSubSat(N, DAG)); 6356 return; 6357 } 6358 case ISD::BITCAST: { 6359 EVT VT = N->getValueType(0); 6360 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6361 SDValue Op0 = N->getOperand(0); 6362 EVT Op0VT = Op0.getValueType(); 6363 MVT XLenVT = Subtarget.getXLenVT(); 6364 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6365 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6366 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6367 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6368 Subtarget.hasStdExtF()) { 6369 SDValue FPConv = 6370 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6371 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6372 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6373 isTypeLegal(Op0VT)) { 6374 // Custom-legalize bitcasts from fixed-length vector types to illegal 6375 // scalar types in order to improve codegen. Bitcast the vector to a 6376 // one-element vector type whose element type is the same as the result 6377 // type, and extract the first element. 6378 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6379 if (isTypeLegal(BVT)) { 6380 SDValue BVec = DAG.getBitcast(BVT, Op0); 6381 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6382 DAG.getConstant(0, DL, XLenVT))); 6383 } 6384 } 6385 break; 6386 } 6387 case RISCVISD::GREV: 6388 case RISCVISD::GORC: { 6389 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6390 "Unexpected custom legalisation"); 6391 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6392 // This is similar to customLegalizeToWOp, except that we pass the second 6393 // operand (a TargetConstant) straight through: it is already of type 6394 // XLenVT. 6395 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6396 SDValue NewOp0 = 6397 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6398 SDValue NewOp1 = 6399 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6400 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6401 // ReplaceNodeResults requires we maintain the same type for the return 6402 // value. 6403 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6404 break; 6405 } 6406 case RISCVISD::SHFL: { 6407 // There is no SHFLIW instruction, but we can just promote the operation. 6408 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6409 "Unexpected custom legalisation"); 6410 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6411 SDValue NewOp0 = 6412 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6413 SDValue NewOp1 = 6414 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6415 SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1); 6416 // ReplaceNodeResults requires we maintain the same type for the return 6417 // value. 6418 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6419 break; 6420 } 6421 case ISD::BSWAP: 6422 case ISD::BITREVERSE: { 6423 MVT VT = N->getSimpleValueType(0); 6424 MVT XLenVT = Subtarget.getXLenVT(); 6425 assert((VT == MVT::i8 || VT == MVT::i16 || 6426 (VT == MVT::i32 && Subtarget.is64Bit())) && 6427 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 6428 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6429 unsigned Imm = VT.getSizeInBits() - 1; 6430 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 6431 if (N->getOpcode() == ISD::BSWAP) 6432 Imm &= ~0x7U; 6433 unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV; 6434 SDValue GREVI = 6435 DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT)); 6436 // ReplaceNodeResults requires we maintain the same type for the return 6437 // value. 6438 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 6439 break; 6440 } 6441 case ISD::FSHL: 6442 case ISD::FSHR: { 6443 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6444 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 6445 SDValue NewOp0 = 6446 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6447 SDValue NewOp1 = 6448 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6449 SDValue NewShAmt = 6450 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6451 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 6452 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 6453 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 6454 DAG.getConstant(0x1f, DL, MVT::i64)); 6455 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 6456 // instruction use different orders. fshl will return its first operand for 6457 // shift of zero, fshr will return its second operand. fsl and fsr both 6458 // return rs1 so the ISD nodes need to have different operand orders. 6459 // Shift amount is in rs2. 6460 unsigned Opc = RISCVISD::FSLW; 6461 if (N->getOpcode() == ISD::FSHR) { 6462 std::swap(NewOp0, NewOp1); 6463 Opc = RISCVISD::FSRW; 6464 } 6465 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 6466 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 6467 break; 6468 } 6469 case ISD::EXTRACT_VECTOR_ELT: { 6470 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 6471 // type is illegal (currently only vXi64 RV32). 6472 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 6473 // transferred to the destination register. We issue two of these from the 6474 // upper- and lower- halves of the SEW-bit vector element, slid down to the 6475 // first element. 6476 SDValue Vec = N->getOperand(0); 6477 SDValue Idx = N->getOperand(1); 6478 6479 // The vector type hasn't been legalized yet so we can't issue target 6480 // specific nodes if it needs legalization. 6481 // FIXME: We would manually legalize if it's important. 6482 if (!isTypeLegal(Vec.getValueType())) 6483 return; 6484 6485 MVT VecVT = Vec.getSimpleValueType(); 6486 6487 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 6488 VecVT.getVectorElementType() == MVT::i64 && 6489 "Unexpected EXTRACT_VECTOR_ELT legalization"); 6490 6491 // If this is a fixed vector, we need to convert it to a scalable vector. 6492 MVT ContainerVT = VecVT; 6493 if (VecVT.isFixedLengthVector()) { 6494 ContainerVT = getContainerForFixedLengthVector(VecVT); 6495 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 6496 } 6497 6498 MVT XLenVT = Subtarget.getXLenVT(); 6499 6500 // Use a VL of 1 to avoid processing more elements than we need. 6501 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6502 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6503 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6504 6505 // Unless the index is known to be 0, we must slide the vector down to get 6506 // the desired element into index 0. 6507 if (!isNullConstant(Idx)) { 6508 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 6509 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 6510 } 6511 6512 // Extract the lower XLEN bits of the correct vector element. 6513 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6514 6515 // To extract the upper XLEN bits of the vector element, shift the first 6516 // element right by 32 bits and re-extract the lower XLEN bits. 6517 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6518 DAG.getConstant(32, DL, XLenVT), VL); 6519 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 6520 ThirtyTwoV, Mask, VL); 6521 6522 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6523 6524 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6525 break; 6526 } 6527 case ISD::INTRINSIC_WO_CHAIN: { 6528 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6529 switch (IntNo) { 6530 default: 6531 llvm_unreachable( 6532 "Don't know how to custom type legalize this intrinsic!"); 6533 case Intrinsic::riscv_grev: 6534 case Intrinsic::riscv_gorc: 6535 case Intrinsic::riscv_bcompress: 6536 case Intrinsic::riscv_bdecompress: 6537 case Intrinsic::riscv_bfp: { 6538 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6539 "Unexpected custom legalisation"); 6540 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 6541 break; 6542 } 6543 case Intrinsic::riscv_fsl: 6544 case Intrinsic::riscv_fsr: { 6545 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6546 "Unexpected custom legalisation"); 6547 SDValue NewOp1 = 6548 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6549 SDValue NewOp2 = 6550 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6551 SDValue NewOp3 = 6552 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3)); 6553 unsigned Opc = getRISCVWOpcodeByIntr(IntNo); 6554 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3); 6555 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6556 break; 6557 } 6558 case Intrinsic::riscv_orc_b: { 6559 // Lower to the GORCI encoding for orc.b with the operand extended. 6560 SDValue NewOp = 6561 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6562 // If Zbp is enabled, use GORCIW which will sign extend the result. 6563 unsigned Opc = 6564 Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC; 6565 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp, 6566 DAG.getConstant(7, DL, MVT::i64)); 6567 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6568 return; 6569 } 6570 case Intrinsic::riscv_shfl: 6571 case Intrinsic::riscv_unshfl: { 6572 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6573 "Unexpected custom legalisation"); 6574 SDValue NewOp1 = 6575 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6576 SDValue NewOp2 = 6577 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 6578 unsigned Opc = 6579 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 6580 if (isa<ConstantSDNode>(N->getOperand(2))) { 6581 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 6582 DAG.getConstant(0xf, DL, MVT::i64)); 6583 Opc = 6584 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 6585 } 6586 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 6587 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6588 break; 6589 } 6590 case Intrinsic::riscv_vmv_x_s: { 6591 EVT VT = N->getValueType(0); 6592 MVT XLenVT = Subtarget.getXLenVT(); 6593 if (VT.bitsLT(XLenVT)) { 6594 // Simple case just extract using vmv.x.s and truncate. 6595 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 6596 Subtarget.getXLenVT(), N->getOperand(1)); 6597 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 6598 return; 6599 } 6600 6601 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 6602 "Unexpected custom legalization"); 6603 6604 // We need to do the move in two steps. 6605 SDValue Vec = N->getOperand(1); 6606 MVT VecVT = Vec.getSimpleValueType(); 6607 6608 // First extract the lower XLEN bits of the element. 6609 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 6610 6611 // To extract the upper XLEN bits of the vector element, shift the first 6612 // element right by 32 bits and re-extract the lower XLEN bits. 6613 SDValue VL = DAG.getConstant(1, DL, XLenVT); 6614 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 6615 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 6616 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 6617 DAG.getConstant(32, DL, XLenVT), VL); 6618 SDValue LShr32 = 6619 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 6620 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 6621 6622 Results.push_back( 6623 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 6624 break; 6625 } 6626 } 6627 break; 6628 } 6629 case ISD::VECREDUCE_ADD: 6630 case ISD::VECREDUCE_AND: 6631 case ISD::VECREDUCE_OR: 6632 case ISD::VECREDUCE_XOR: 6633 case ISD::VECREDUCE_SMAX: 6634 case ISD::VECREDUCE_UMAX: 6635 case ISD::VECREDUCE_SMIN: 6636 case ISD::VECREDUCE_UMIN: 6637 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 6638 Results.push_back(V); 6639 break; 6640 case ISD::VP_REDUCE_ADD: 6641 case ISD::VP_REDUCE_AND: 6642 case ISD::VP_REDUCE_OR: 6643 case ISD::VP_REDUCE_XOR: 6644 case ISD::VP_REDUCE_SMAX: 6645 case ISD::VP_REDUCE_UMAX: 6646 case ISD::VP_REDUCE_SMIN: 6647 case ISD::VP_REDUCE_UMIN: 6648 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 6649 Results.push_back(V); 6650 break; 6651 case ISD::FLT_ROUNDS_: { 6652 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 6653 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 6654 Results.push_back(Res.getValue(0)); 6655 Results.push_back(Res.getValue(1)); 6656 break; 6657 } 6658 } 6659 } 6660 6661 // A structure to hold one of the bit-manipulation patterns below. Together, a 6662 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 6663 // (or (and (shl x, 1), 0xAAAAAAAA), 6664 // (and (srl x, 1), 0x55555555)) 6665 struct RISCVBitmanipPat { 6666 SDValue Op; 6667 unsigned ShAmt; 6668 bool IsSHL; 6669 6670 bool formsPairWith(const RISCVBitmanipPat &Other) const { 6671 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 6672 } 6673 }; 6674 6675 // Matches patterns of the form 6676 // (and (shl x, C2), (C1 << C2)) 6677 // (and (srl x, C2), C1) 6678 // (shl (and x, C1), C2) 6679 // (srl (and x, (C1 << C2)), C2) 6680 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 6681 // The expected masks for each shift amount are specified in BitmanipMasks where 6682 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 6683 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 6684 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 6685 // XLen is 64. 6686 static Optional<RISCVBitmanipPat> 6687 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 6688 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 6689 "Unexpected number of masks"); 6690 Optional<uint64_t> Mask; 6691 // Optionally consume a mask around the shift operation. 6692 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 6693 Mask = Op.getConstantOperandVal(1); 6694 Op = Op.getOperand(0); 6695 } 6696 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 6697 return None; 6698 bool IsSHL = Op.getOpcode() == ISD::SHL; 6699 6700 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6701 return None; 6702 uint64_t ShAmt = Op.getConstantOperandVal(1); 6703 6704 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6705 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 6706 return None; 6707 // If we don't have enough masks for 64 bit, then we must be trying to 6708 // match SHFL so we're only allowed to shift 1/4 of the width. 6709 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 6710 return None; 6711 6712 SDValue Src = Op.getOperand(0); 6713 6714 // The expected mask is shifted left when the AND is found around SHL 6715 // patterns. 6716 // ((x >> 1) & 0x55555555) 6717 // ((x << 1) & 0xAAAAAAAA) 6718 bool SHLExpMask = IsSHL; 6719 6720 if (!Mask) { 6721 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 6722 // the mask is all ones: consume that now. 6723 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 6724 Mask = Src.getConstantOperandVal(1); 6725 Src = Src.getOperand(0); 6726 // The expected mask is now in fact shifted left for SRL, so reverse the 6727 // decision. 6728 // ((x & 0xAAAAAAAA) >> 1) 6729 // ((x & 0x55555555) << 1) 6730 SHLExpMask = !SHLExpMask; 6731 } else { 6732 // Use a default shifted mask of all-ones if there's no AND, truncated 6733 // down to the expected width. This simplifies the logic later on. 6734 Mask = maskTrailingOnes<uint64_t>(Width); 6735 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 6736 } 6737 } 6738 6739 unsigned MaskIdx = Log2_32(ShAmt); 6740 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6741 6742 if (SHLExpMask) 6743 ExpMask <<= ShAmt; 6744 6745 if (Mask != ExpMask) 6746 return None; 6747 6748 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 6749 } 6750 6751 // Matches any of the following bit-manipulation patterns: 6752 // (and (shl x, 1), (0x55555555 << 1)) 6753 // (and (srl x, 1), 0x55555555) 6754 // (shl (and x, 0x55555555), 1) 6755 // (srl (and x, (0x55555555 << 1)), 1) 6756 // where the shift amount and mask may vary thus: 6757 // [1] = 0x55555555 / 0xAAAAAAAA 6758 // [2] = 0x33333333 / 0xCCCCCCCC 6759 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 6760 // [8] = 0x00FF00FF / 0xFF00FF00 6761 // [16] = 0x0000FFFF / 0xFFFFFFFF 6762 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 6763 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 6764 // These are the unshifted masks which we use to match bit-manipulation 6765 // patterns. They may be shifted left in certain circumstances. 6766 static const uint64_t BitmanipMasks[] = { 6767 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 6768 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 6769 6770 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6771 } 6772 6773 // Match the following pattern as a GREVI(W) operation 6774 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 6775 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 6776 const RISCVSubtarget &Subtarget) { 6777 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6778 EVT VT = Op.getValueType(); 6779 6780 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6781 auto LHS = matchGREVIPat(Op.getOperand(0)); 6782 auto RHS = matchGREVIPat(Op.getOperand(1)); 6783 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 6784 SDLoc DL(Op); 6785 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 6786 DAG.getConstant(LHS->ShAmt, DL, VT)); 6787 } 6788 } 6789 return SDValue(); 6790 } 6791 6792 // Matches any the following pattern as a GORCI(W) operation 6793 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 6794 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 6795 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 6796 // Note that with the variant of 3., 6797 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 6798 // the inner pattern will first be matched as GREVI and then the outer 6799 // pattern will be matched to GORC via the first rule above. 6800 // 4. (or (rotl/rotr x, bitwidth/2), x) 6801 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 6802 const RISCVSubtarget &Subtarget) { 6803 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6804 EVT VT = Op.getValueType(); 6805 6806 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 6807 SDLoc DL(Op); 6808 SDValue Op0 = Op.getOperand(0); 6809 SDValue Op1 = Op.getOperand(1); 6810 6811 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 6812 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 6813 isa<ConstantSDNode>(Reverse.getOperand(1)) && 6814 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 6815 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 6816 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 6817 if ((Reverse.getOpcode() == ISD::ROTL || 6818 Reverse.getOpcode() == ISD::ROTR) && 6819 Reverse.getOperand(0) == X && 6820 isa<ConstantSDNode>(Reverse.getOperand(1))) { 6821 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 6822 if (RotAmt == (VT.getSizeInBits() / 2)) 6823 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 6824 DAG.getConstant(RotAmt, DL, VT)); 6825 } 6826 return SDValue(); 6827 }; 6828 6829 // Check for either commutable permutation of (or (GREVI x, shamt), x) 6830 if (SDValue V = MatchOROfReverse(Op0, Op1)) 6831 return V; 6832 if (SDValue V = MatchOROfReverse(Op1, Op0)) 6833 return V; 6834 6835 // OR is commutable so canonicalize its OR operand to the left 6836 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 6837 std::swap(Op0, Op1); 6838 if (Op0.getOpcode() != ISD::OR) 6839 return SDValue(); 6840 SDValue OrOp0 = Op0.getOperand(0); 6841 SDValue OrOp1 = Op0.getOperand(1); 6842 auto LHS = matchGREVIPat(OrOp0); 6843 // OR is commutable so swap the operands and try again: x might have been 6844 // on the left 6845 if (!LHS) { 6846 std::swap(OrOp0, OrOp1); 6847 LHS = matchGREVIPat(OrOp0); 6848 } 6849 auto RHS = matchGREVIPat(Op1); 6850 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 6851 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 6852 DAG.getConstant(LHS->ShAmt, DL, VT)); 6853 } 6854 } 6855 return SDValue(); 6856 } 6857 6858 // Matches any of the following bit-manipulation patterns: 6859 // (and (shl x, 1), (0x22222222 << 1)) 6860 // (and (srl x, 1), 0x22222222) 6861 // (shl (and x, 0x22222222), 1) 6862 // (srl (and x, (0x22222222 << 1)), 1) 6863 // where the shift amount and mask may vary thus: 6864 // [1] = 0x22222222 / 0x44444444 6865 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 6866 // [4] = 0x00F000F0 / 0x0F000F00 6867 // [8] = 0x0000FF00 / 0x00FF0000 6868 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 6869 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 6870 // These are the unshifted masks which we use to match bit-manipulation 6871 // patterns. They may be shifted left in certain circumstances. 6872 static const uint64_t BitmanipMasks[] = { 6873 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 6874 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 6875 6876 return matchRISCVBitmanipPat(Op, BitmanipMasks); 6877 } 6878 6879 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 6880 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 6881 const RISCVSubtarget &Subtarget) { 6882 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 6883 EVT VT = Op.getValueType(); 6884 6885 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 6886 return SDValue(); 6887 6888 SDValue Op0 = Op.getOperand(0); 6889 SDValue Op1 = Op.getOperand(1); 6890 6891 // Or is commutable so canonicalize the second OR to the LHS. 6892 if (Op0.getOpcode() != ISD::OR) 6893 std::swap(Op0, Op1); 6894 if (Op0.getOpcode() != ISD::OR) 6895 return SDValue(); 6896 6897 // We found an inner OR, so our operands are the operands of the inner OR 6898 // and the other operand of the outer OR. 6899 SDValue A = Op0.getOperand(0); 6900 SDValue B = Op0.getOperand(1); 6901 SDValue C = Op1; 6902 6903 auto Match1 = matchSHFLPat(A); 6904 auto Match2 = matchSHFLPat(B); 6905 6906 // If neither matched, we failed. 6907 if (!Match1 && !Match2) 6908 return SDValue(); 6909 6910 // We had at least one match. if one failed, try the remaining C operand. 6911 if (!Match1) { 6912 std::swap(A, C); 6913 Match1 = matchSHFLPat(A); 6914 if (!Match1) 6915 return SDValue(); 6916 } else if (!Match2) { 6917 std::swap(B, C); 6918 Match2 = matchSHFLPat(B); 6919 if (!Match2) 6920 return SDValue(); 6921 } 6922 assert(Match1 && Match2); 6923 6924 // Make sure our matches pair up. 6925 if (!Match1->formsPairWith(*Match2)) 6926 return SDValue(); 6927 6928 // All the remains is to make sure C is an AND with the same input, that masks 6929 // out the bits that are being shuffled. 6930 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 6931 C.getOperand(0) != Match1->Op) 6932 return SDValue(); 6933 6934 uint64_t Mask = C.getConstantOperandVal(1); 6935 6936 static const uint64_t BitmanipMasks[] = { 6937 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 6938 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 6939 }; 6940 6941 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 6942 unsigned MaskIdx = Log2_32(Match1->ShAmt); 6943 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 6944 6945 if (Mask != ExpMask) 6946 return SDValue(); 6947 6948 SDLoc DL(Op); 6949 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 6950 DAG.getConstant(Match1->ShAmt, DL, VT)); 6951 } 6952 6953 // Optimize (add (shl x, c0), (shl y, c1)) -> 6954 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 6955 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 6956 const RISCVSubtarget &Subtarget) { 6957 // Perform this optimization only in the zba extension. 6958 if (!Subtarget.hasStdExtZba()) 6959 return SDValue(); 6960 6961 // Skip for vector types and larger types. 6962 EVT VT = N->getValueType(0); 6963 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 6964 return SDValue(); 6965 6966 // The two operand nodes must be SHL and have no other use. 6967 SDValue N0 = N->getOperand(0); 6968 SDValue N1 = N->getOperand(1); 6969 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 6970 !N0->hasOneUse() || !N1->hasOneUse()) 6971 return SDValue(); 6972 6973 // Check c0 and c1. 6974 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 6975 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 6976 if (!N0C || !N1C) 6977 return SDValue(); 6978 int64_t C0 = N0C->getSExtValue(); 6979 int64_t C1 = N1C->getSExtValue(); 6980 if (C0 <= 0 || C1 <= 0) 6981 return SDValue(); 6982 6983 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 6984 int64_t Bits = std::min(C0, C1); 6985 int64_t Diff = std::abs(C0 - C1); 6986 if (Diff != 1 && Diff != 2 && Diff != 3) 6987 return SDValue(); 6988 6989 // Build nodes. 6990 SDLoc DL(N); 6991 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 6992 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 6993 SDValue NA0 = 6994 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 6995 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 6996 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 6997 } 6998 6999 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7000 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7001 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7002 // not undo itself, but they are redundant. 7003 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7004 SDValue Src = N->getOperand(0); 7005 7006 if (Src.getOpcode() != N->getOpcode()) 7007 return SDValue(); 7008 7009 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7010 !isa<ConstantSDNode>(Src.getOperand(1))) 7011 return SDValue(); 7012 7013 unsigned ShAmt1 = N->getConstantOperandVal(1); 7014 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7015 Src = Src.getOperand(0); 7016 7017 unsigned CombinedShAmt; 7018 if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW) 7019 CombinedShAmt = ShAmt1 | ShAmt2; 7020 else 7021 CombinedShAmt = ShAmt1 ^ ShAmt2; 7022 7023 if (CombinedShAmt == 0) 7024 return Src; 7025 7026 SDLoc DL(N); 7027 return DAG.getNode( 7028 N->getOpcode(), DL, N->getValueType(0), Src, 7029 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7030 } 7031 7032 // Combine a constant select operand into its use: 7033 // 7034 // (and (select cond, -1, c), x) 7035 // -> (select cond, x, (and x, c)) [AllOnes=1] 7036 // (or (select cond, 0, c), x) 7037 // -> (select cond, x, (or x, c)) [AllOnes=0] 7038 // (xor (select cond, 0, c), x) 7039 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7040 // (add (select cond, 0, c), x) 7041 // -> (select cond, x, (add x, c)) [AllOnes=0] 7042 // (sub x, (select cond, 0, c)) 7043 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7044 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7045 SelectionDAG &DAG, bool AllOnes) { 7046 EVT VT = N->getValueType(0); 7047 7048 // Skip vectors. 7049 if (VT.isVector()) 7050 return SDValue(); 7051 7052 if ((Slct.getOpcode() != ISD::SELECT && 7053 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7054 !Slct.hasOneUse()) 7055 return SDValue(); 7056 7057 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7058 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7059 }; 7060 7061 bool SwapSelectOps; 7062 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7063 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7064 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7065 SDValue NonConstantVal; 7066 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7067 SwapSelectOps = false; 7068 NonConstantVal = FalseVal; 7069 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7070 SwapSelectOps = true; 7071 NonConstantVal = TrueVal; 7072 } else 7073 return SDValue(); 7074 7075 // Slct is now know to be the desired identity constant when CC is true. 7076 TrueVal = OtherOp; 7077 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7078 // Unless SwapSelectOps says the condition should be false. 7079 if (SwapSelectOps) 7080 std::swap(TrueVal, FalseVal); 7081 7082 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7083 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7084 {Slct.getOperand(0), Slct.getOperand(1), 7085 Slct.getOperand(2), TrueVal, FalseVal}); 7086 7087 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7088 {Slct.getOperand(0), TrueVal, FalseVal}); 7089 } 7090 7091 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7092 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7093 bool AllOnes) { 7094 SDValue N0 = N->getOperand(0); 7095 SDValue N1 = N->getOperand(1); 7096 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7097 return Result; 7098 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7099 return Result; 7100 return SDValue(); 7101 } 7102 7103 // Transform (add (mul x, c0), c1) -> 7104 // (add (mul (add x, c1/c0), c0), c1%c0). 7105 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7106 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7107 // to an infinite loop in DAGCombine if transformed. 7108 // Or transform (add (mul x, c0), c1) -> 7109 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7110 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7111 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7112 // lead to an infinite loop in DAGCombine if transformed. 7113 // Or transform (add (mul x, c0), c1) -> 7114 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7115 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7116 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7117 // lead to an infinite loop in DAGCombine if transformed. 7118 // Or transform (add (mul x, c0), c1) -> 7119 // (mul (add x, c1/c0), c0). 7120 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7121 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7122 const RISCVSubtarget &Subtarget) { 7123 // Skip for vector types and larger types. 7124 EVT VT = N->getValueType(0); 7125 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7126 return SDValue(); 7127 // The first operand node must be a MUL and has no other use. 7128 SDValue N0 = N->getOperand(0); 7129 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7130 return SDValue(); 7131 // Check if c0 and c1 match above conditions. 7132 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7133 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7134 if (!N0C || !N1C) 7135 return SDValue(); 7136 int64_t C0 = N0C->getSExtValue(); 7137 int64_t C1 = N1C->getSExtValue(); 7138 int64_t CA, CB; 7139 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7140 return SDValue(); 7141 // Search for proper CA (non-zero) and CB that both are simm12. 7142 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7143 !isInt<12>(C0 * (C1 / C0))) { 7144 CA = C1 / C0; 7145 CB = C1 % C0; 7146 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7147 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7148 CA = C1 / C0 + 1; 7149 CB = C1 % C0 - C0; 7150 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7151 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7152 CA = C1 / C0 - 1; 7153 CB = C1 % C0 + C0; 7154 } else 7155 return SDValue(); 7156 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7157 SDLoc DL(N); 7158 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7159 DAG.getConstant(CA, DL, VT)); 7160 SDValue New1 = 7161 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7162 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7163 } 7164 7165 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7166 const RISCVSubtarget &Subtarget) { 7167 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7168 return V; 7169 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7170 return V; 7171 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7172 // (select lhs, rhs, cc, x, (add x, y)) 7173 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7174 } 7175 7176 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7177 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7178 // (select lhs, rhs, cc, x, (sub x, y)) 7179 SDValue N0 = N->getOperand(0); 7180 SDValue N1 = N->getOperand(1); 7181 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7182 } 7183 7184 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7185 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7186 // (select lhs, rhs, cc, x, (and x, y)) 7187 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7188 } 7189 7190 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7191 const RISCVSubtarget &Subtarget) { 7192 if (Subtarget.hasStdExtZbp()) { 7193 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7194 return GREV; 7195 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7196 return GORC; 7197 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7198 return SHFL; 7199 } 7200 7201 // fold (or (select cond, 0, y), x) -> 7202 // (select cond, x, (or x, y)) 7203 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7204 } 7205 7206 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7207 // fold (xor (select cond, 0, y), x) -> 7208 // (select cond, x, (xor x, y)) 7209 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7210 } 7211 7212 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND 7213 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free 7214 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be 7215 // removed during type legalization leaving an ADD/SUB/MUL use that won't use 7216 // ADDW/SUBW/MULW. 7217 static SDValue performANY_EXTENDCombine(SDNode *N, 7218 TargetLowering::DAGCombinerInfo &DCI, 7219 const RISCVSubtarget &Subtarget) { 7220 if (!Subtarget.is64Bit()) 7221 return SDValue(); 7222 7223 SelectionDAG &DAG = DCI.DAG; 7224 7225 SDValue Src = N->getOperand(0); 7226 EVT VT = N->getValueType(0); 7227 if (VT != MVT::i64 || Src.getValueType() != MVT::i32) 7228 return SDValue(); 7229 7230 // The opcode must be one that can implicitly sign_extend. 7231 // FIXME: Additional opcodes. 7232 switch (Src.getOpcode()) { 7233 default: 7234 return SDValue(); 7235 case ISD::MUL: 7236 if (!Subtarget.hasStdExtM()) 7237 return SDValue(); 7238 LLVM_FALLTHROUGH; 7239 case ISD::ADD: 7240 case ISD::SUB: 7241 break; 7242 } 7243 7244 // Only handle cases where the result is used by a CopyToReg. That likely 7245 // means the value is a liveout of the basic block. This helps prevent 7246 // infinite combine loops like PR51206. 7247 if (none_of(N->uses(), 7248 [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; })) 7249 return SDValue(); 7250 7251 SmallVector<SDNode *, 4> SetCCs; 7252 for (SDNode::use_iterator UI = Src.getNode()->use_begin(), 7253 UE = Src.getNode()->use_end(); 7254 UI != UE; ++UI) { 7255 SDNode *User = *UI; 7256 if (User == N) 7257 continue; 7258 if (UI.getUse().getResNo() != Src.getResNo()) 7259 continue; 7260 // All i32 setccs are legalized by sign extending operands. 7261 if (User->getOpcode() == ISD::SETCC) { 7262 SetCCs.push_back(User); 7263 continue; 7264 } 7265 // We don't know if we can extend this user. 7266 break; 7267 } 7268 7269 // If we don't have any SetCCs, this isn't worthwhile. 7270 if (SetCCs.empty()) 7271 return SDValue(); 7272 7273 SDLoc DL(N); 7274 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src); 7275 DCI.CombineTo(N, SExt); 7276 7277 // Promote all the setccs. 7278 for (SDNode *SetCC : SetCCs) { 7279 SmallVector<SDValue, 4> Ops; 7280 7281 for (unsigned j = 0; j != 2; ++j) { 7282 SDValue SOp = SetCC->getOperand(j); 7283 if (SOp == Src) 7284 Ops.push_back(SExt); 7285 else 7286 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp)); 7287 } 7288 7289 Ops.push_back(SetCC->getOperand(2)); 7290 DCI.CombineTo(SetCC, 7291 DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 7292 } 7293 return SDValue(N, 0); 7294 } 7295 7296 // Try to form VWMUL, VWMULU or VWMULSU. 7297 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 7298 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 7299 bool Commute) { 7300 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 7301 SDValue Op0 = N->getOperand(0); 7302 SDValue Op1 = N->getOperand(1); 7303 if (Commute) 7304 std::swap(Op0, Op1); 7305 7306 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 7307 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 7308 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 7309 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 7310 return SDValue(); 7311 7312 SDValue Mask = N->getOperand(2); 7313 SDValue VL = N->getOperand(3); 7314 7315 // Make sure the mask and VL match. 7316 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 7317 return SDValue(); 7318 7319 MVT VT = N->getSimpleValueType(0); 7320 7321 // Determine the narrow size for a widening multiply. 7322 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7323 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7324 VT.getVectorElementCount()); 7325 7326 SDLoc DL(N); 7327 7328 // See if the other operand is the same opcode. 7329 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 7330 if (!Op1.hasOneUse()) 7331 return SDValue(); 7332 7333 // Make sure the mask and VL match. 7334 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 7335 return SDValue(); 7336 7337 Op1 = Op1.getOperand(0); 7338 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 7339 // The operand is a splat of a scalar. 7340 7341 // The VL must be the same. 7342 if (Op1.getOperand(1) != VL) 7343 return SDValue(); 7344 7345 // Get the scalar value. 7346 Op1 = Op1.getOperand(0); 7347 7348 // See if have enough sign bits or zero bits in the scalar to use a 7349 // widening multiply by splatting to smaller element size. 7350 unsigned EltBits = VT.getScalarSizeInBits(); 7351 unsigned ScalarBits = Op1.getValueSizeInBits(); 7352 // Make sure we're getting all element bits from the scalar register. 7353 // FIXME: Support implicit sign extension of vmv.v.x? 7354 if (ScalarBits < EltBits) 7355 return SDValue(); 7356 7357 if (IsSignExt) { 7358 if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize)) 7359 return SDValue(); 7360 } else { 7361 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 7362 if (!DAG.MaskedValueIsZero(Op1, Mask)) 7363 return SDValue(); 7364 } 7365 7366 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL); 7367 } else 7368 return SDValue(); 7369 7370 Op0 = Op0.getOperand(0); 7371 7372 // Re-introduce narrower extends if needed. 7373 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 7374 if (Op0.getValueType() != NarrowVT) 7375 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 7376 if (Op1.getValueType() != NarrowVT) 7377 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7378 7379 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 7380 if (!IsVWMULSU) 7381 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 7382 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 7383 } 7384 7385 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 7386 switch (Op.getOpcode()) { 7387 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 7388 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 7389 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 7390 case ISD::FCEIL: return RISCVFPRndMode::RUP; 7391 case ISD::FROUND: return RISCVFPRndMode::RMM; 7392 } 7393 7394 return RISCVFPRndMode::Invalid; 7395 } 7396 7397 // Fold 7398 // (fp_to_int (froundeven X)) -> fcvt X, rne 7399 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 7400 // (fp_to_int (ffloor X)) -> fcvt X, rdn 7401 // (fp_to_int (fceil X)) -> fcvt X, rup 7402 // (fp_to_int (fround X)) -> fcvt X, rmm 7403 static SDValue performFP_TO_INTCombine(SDNode *N, 7404 TargetLowering::DAGCombinerInfo &DCI, 7405 const RISCVSubtarget &Subtarget) { 7406 SelectionDAG &DAG = DCI.DAG; 7407 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7408 MVT XLenVT = Subtarget.getXLenVT(); 7409 7410 // Only handle XLen or i32 types. Other types narrower than XLen will 7411 // eventually be legalized to XLenVT. 7412 EVT VT = N->getValueType(0); 7413 if (VT != MVT::i32 && VT != XLenVT) 7414 return SDValue(); 7415 7416 SDValue Src = N->getOperand(0); 7417 7418 // Ensure the FP type is also legal. 7419 if (!TLI.isTypeLegal(Src.getValueType())) 7420 return SDValue(); 7421 7422 // Don't do this for f16 with Zfhmin and not Zfh. 7423 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7424 return SDValue(); 7425 7426 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7427 if (FRM == RISCVFPRndMode::Invalid) 7428 return SDValue(); 7429 7430 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7431 7432 unsigned Opc; 7433 if (VT == XLenVT) 7434 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7435 else 7436 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7437 7438 SDLoc DL(N); 7439 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 7440 DAG.getTargetConstant(FRM, DL, XLenVT)); 7441 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 7442 } 7443 7444 // Fold 7445 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 7446 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 7447 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 7448 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 7449 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 7450 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 7451 TargetLowering::DAGCombinerInfo &DCI, 7452 const RISCVSubtarget &Subtarget) { 7453 SelectionDAG &DAG = DCI.DAG; 7454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7455 MVT XLenVT = Subtarget.getXLenVT(); 7456 7457 // Only handle XLen types. Other types narrower than XLen will eventually be 7458 // legalized to XLenVT. 7459 EVT DstVT = N->getValueType(0); 7460 if (DstVT != XLenVT) 7461 return SDValue(); 7462 7463 SDValue Src = N->getOperand(0); 7464 7465 // Ensure the FP type is also legal. 7466 if (!TLI.isTypeLegal(Src.getValueType())) 7467 return SDValue(); 7468 7469 // Don't do this for f16 with Zfhmin and not Zfh. 7470 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 7471 return SDValue(); 7472 7473 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7474 7475 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 7476 if (FRM == RISCVFPRndMode::Invalid) 7477 return SDValue(); 7478 7479 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 7480 7481 unsigned Opc; 7482 if (SatVT == DstVT) 7483 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 7484 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 7485 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 7486 else 7487 return SDValue(); 7488 // FIXME: Support other SatVTs by clamping before or after the conversion. 7489 7490 Src = Src.getOperand(0); 7491 7492 SDLoc DL(N); 7493 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 7494 DAG.getTargetConstant(FRM, DL, XLenVT)); 7495 7496 // RISCV FP-to-int conversions saturate to the destination register size, but 7497 // don't produce 0 for nan. 7498 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 7499 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 7500 } 7501 7502 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 7503 DAGCombinerInfo &DCI) const { 7504 SelectionDAG &DAG = DCI.DAG; 7505 7506 // Helper to call SimplifyDemandedBits on an operand of N where only some low 7507 // bits are demanded. N will be added to the Worklist if it was not deleted. 7508 // Caller should return SDValue(N, 0) if this returns true. 7509 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 7510 SDValue Op = N->getOperand(OpNo); 7511 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 7512 if (!SimplifyDemandedBits(Op, Mask, DCI)) 7513 return false; 7514 7515 if (N->getOpcode() != ISD::DELETED_NODE) 7516 DCI.AddToWorklist(N); 7517 return true; 7518 }; 7519 7520 switch (N->getOpcode()) { 7521 default: 7522 break; 7523 case RISCVISD::SplitF64: { 7524 SDValue Op0 = N->getOperand(0); 7525 // If the input to SplitF64 is just BuildPairF64 then the operation is 7526 // redundant. Instead, use BuildPairF64's operands directly. 7527 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 7528 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 7529 7530 SDLoc DL(N); 7531 7532 // It's cheaper to materialise two 32-bit integers than to load a double 7533 // from the constant pool and transfer it to integer registers through the 7534 // stack. 7535 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 7536 APInt V = C->getValueAPF().bitcastToAPInt(); 7537 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 7538 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 7539 return DCI.CombineTo(N, Lo, Hi); 7540 } 7541 7542 // This is a target-specific version of a DAGCombine performed in 7543 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7544 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7545 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7546 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7547 !Op0.getNode()->hasOneUse()) 7548 break; 7549 SDValue NewSplitF64 = 7550 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 7551 Op0.getOperand(0)); 7552 SDValue Lo = NewSplitF64.getValue(0); 7553 SDValue Hi = NewSplitF64.getValue(1); 7554 APInt SignBit = APInt::getSignMask(32); 7555 if (Op0.getOpcode() == ISD::FNEG) { 7556 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 7557 DAG.getConstant(SignBit, DL, MVT::i32)); 7558 return DCI.CombineTo(N, Lo, NewHi); 7559 } 7560 assert(Op0.getOpcode() == ISD::FABS); 7561 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 7562 DAG.getConstant(~SignBit, DL, MVT::i32)); 7563 return DCI.CombineTo(N, Lo, NewHi); 7564 } 7565 case RISCVISD::SLLW: 7566 case RISCVISD::SRAW: 7567 case RISCVISD::SRLW: 7568 case RISCVISD::ROLW: 7569 case RISCVISD::RORW: { 7570 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7571 if (SimplifyDemandedLowBitsHelper(0, 32) || 7572 SimplifyDemandedLowBitsHelper(1, 5)) 7573 return SDValue(N, 0); 7574 break; 7575 } 7576 case RISCVISD::CLZW: 7577 case RISCVISD::CTZW: { 7578 // Only the lower 32 bits of the first operand are read 7579 if (SimplifyDemandedLowBitsHelper(0, 32)) 7580 return SDValue(N, 0); 7581 break; 7582 } 7583 case RISCVISD::GREV: 7584 case RISCVISD::GORC: { 7585 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 7586 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7587 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7588 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 7589 return SDValue(N, 0); 7590 7591 return combineGREVI_GORCI(N, DAG); 7592 } 7593 case RISCVISD::GREVW: 7594 case RISCVISD::GORCW: { 7595 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 7596 if (SimplifyDemandedLowBitsHelper(0, 32) || 7597 SimplifyDemandedLowBitsHelper(1, 5)) 7598 return SDValue(N, 0); 7599 7600 return combineGREVI_GORCI(N, DAG); 7601 } 7602 case RISCVISD::SHFL: 7603 case RISCVISD::UNSHFL: { 7604 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 7605 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 7606 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 7607 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 7608 return SDValue(N, 0); 7609 7610 break; 7611 } 7612 case RISCVISD::SHFLW: 7613 case RISCVISD::UNSHFLW: { 7614 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 7615 SDValue LHS = N->getOperand(0); 7616 SDValue RHS = N->getOperand(1); 7617 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 7618 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4); 7619 if (SimplifyDemandedLowBitsHelper(0, 32) || 7620 SimplifyDemandedLowBitsHelper(1, 4)) 7621 return SDValue(N, 0); 7622 7623 break; 7624 } 7625 case RISCVISD::BCOMPRESSW: 7626 case RISCVISD::BDECOMPRESSW: { 7627 // Only the lower 32 bits of LHS and RHS are read. 7628 if (SimplifyDemandedLowBitsHelper(0, 32) || 7629 SimplifyDemandedLowBitsHelper(1, 32)) 7630 return SDValue(N, 0); 7631 7632 break; 7633 } 7634 case RISCVISD::FMV_X_ANYEXTH: 7635 case RISCVISD::FMV_X_ANYEXTW_RV64: { 7636 SDLoc DL(N); 7637 SDValue Op0 = N->getOperand(0); 7638 MVT VT = N->getSimpleValueType(0); 7639 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 7640 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 7641 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 7642 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 7643 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 7644 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7645 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 7646 assert(Op0.getOperand(0).getValueType() == VT && 7647 "Unexpected value type!"); 7648 return Op0.getOperand(0); 7649 } 7650 7651 // This is a target-specific version of a DAGCombine performed in 7652 // DAGCombiner::visitBITCAST. It performs the equivalent of: 7653 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7654 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7655 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 7656 !Op0.getNode()->hasOneUse()) 7657 break; 7658 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 7659 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 7660 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 7661 if (Op0.getOpcode() == ISD::FNEG) 7662 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 7663 DAG.getConstant(SignBit, DL, VT)); 7664 7665 assert(Op0.getOpcode() == ISD::FABS); 7666 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 7667 DAG.getConstant(~SignBit, DL, VT)); 7668 } 7669 case ISD::ADD: 7670 return performADDCombine(N, DAG, Subtarget); 7671 case ISD::SUB: 7672 return performSUBCombine(N, DAG); 7673 case ISD::AND: 7674 return performANDCombine(N, DAG); 7675 case ISD::OR: 7676 return performORCombine(N, DAG, Subtarget); 7677 case ISD::XOR: 7678 return performXORCombine(N, DAG); 7679 case ISD::ANY_EXTEND: 7680 return performANY_EXTENDCombine(N, DCI, Subtarget); 7681 case ISD::ZERO_EXTEND: 7682 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 7683 // type legalization. This is safe because fp_to_uint produces poison if 7684 // it overflows. 7685 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 7686 SDValue Src = N->getOperand(0); 7687 if (Src.getOpcode() == ISD::FP_TO_UINT && 7688 isTypeLegal(Src.getOperand(0).getValueType())) 7689 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 7690 Src.getOperand(0)); 7691 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 7692 isTypeLegal(Src.getOperand(1).getValueType())) { 7693 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 7694 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 7695 Src.getOperand(0), Src.getOperand(1)); 7696 DCI.CombineTo(N, Res); 7697 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 7698 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 7699 return SDValue(N, 0); // Return N so it doesn't get rechecked. 7700 } 7701 } 7702 return SDValue(); 7703 case RISCVISD::SELECT_CC: { 7704 // Transform 7705 SDValue LHS = N->getOperand(0); 7706 SDValue RHS = N->getOperand(1); 7707 SDValue TrueV = N->getOperand(3); 7708 SDValue FalseV = N->getOperand(4); 7709 7710 // If the True and False values are the same, we don't need a select_cc. 7711 if (TrueV == FalseV) 7712 return TrueV; 7713 7714 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7715 if (!ISD::isIntEqualitySetCC(CCVal)) 7716 break; 7717 7718 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 7719 // (select_cc X, Y, lt, trueV, falseV) 7720 // Sometimes the setcc is introduced after select_cc has been formed. 7721 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7722 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7723 // If we're looking for eq 0 instead of ne 0, we need to invert the 7724 // condition. 7725 bool Invert = CCVal == ISD::SETEQ; 7726 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7727 if (Invert) 7728 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7729 7730 SDLoc DL(N); 7731 RHS = LHS.getOperand(1); 7732 LHS = LHS.getOperand(0); 7733 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7734 7735 SDValue TargetCC = DAG.getCondCode(CCVal); 7736 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7737 {LHS, RHS, TargetCC, TrueV, FalseV}); 7738 } 7739 7740 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 7741 // (select_cc X, Y, eq/ne, trueV, falseV) 7742 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7743 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 7744 {LHS.getOperand(0), LHS.getOperand(1), 7745 N->getOperand(2), TrueV, FalseV}); 7746 // (select_cc X, 1, setne, trueV, falseV) -> 7747 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 7748 // This can occur when legalizing some floating point comparisons. 7749 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7750 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7751 SDLoc DL(N); 7752 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7753 SDValue TargetCC = DAG.getCondCode(CCVal); 7754 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7755 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 7756 {LHS, RHS, TargetCC, TrueV, FalseV}); 7757 } 7758 7759 break; 7760 } 7761 case RISCVISD::BR_CC: { 7762 SDValue LHS = N->getOperand(1); 7763 SDValue RHS = N->getOperand(2); 7764 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 7765 if (!ISD::isIntEqualitySetCC(CCVal)) 7766 break; 7767 7768 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 7769 // (br_cc X, Y, lt, dest) 7770 // Sometimes the setcc is introduced after br_cc has been formed. 7771 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 7772 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 7773 // If we're looking for eq 0 instead of ne 0, we need to invert the 7774 // condition. 7775 bool Invert = CCVal == ISD::SETEQ; 7776 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7777 if (Invert) 7778 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7779 7780 SDLoc DL(N); 7781 RHS = LHS.getOperand(1); 7782 LHS = LHS.getOperand(0); 7783 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 7784 7785 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7786 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 7787 N->getOperand(4)); 7788 } 7789 7790 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 7791 // (br_cc X, Y, eq/ne, trueV, falseV) 7792 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 7793 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 7794 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 7795 N->getOperand(3), N->getOperand(4)); 7796 7797 // (br_cc X, 1, setne, br_cc) -> 7798 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 7799 // This can occur when legalizing some floating point comparisons. 7800 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 7801 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 7802 SDLoc DL(N); 7803 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 7804 SDValue TargetCC = DAG.getCondCode(CCVal); 7805 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 7806 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 7807 N->getOperand(0), LHS, RHS, TargetCC, 7808 N->getOperand(4)); 7809 } 7810 break; 7811 } 7812 case ISD::FP_TO_SINT: 7813 case ISD::FP_TO_UINT: 7814 return performFP_TO_INTCombine(N, DCI, Subtarget); 7815 case ISD::FP_TO_SINT_SAT: 7816 case ISD::FP_TO_UINT_SAT: 7817 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 7818 case ISD::FCOPYSIGN: { 7819 EVT VT = N->getValueType(0); 7820 if (!VT.isVector()) 7821 break; 7822 // There is a form of VFSGNJ which injects the negated sign of its second 7823 // operand. Try and bubble any FNEG up after the extend/round to produce 7824 // this optimized pattern. Avoid modifying cases where FP_ROUND and 7825 // TRUNC=1. 7826 SDValue In2 = N->getOperand(1); 7827 // Avoid cases where the extend/round has multiple uses, as duplicating 7828 // those is typically more expensive than removing a fneg. 7829 if (!In2.hasOneUse()) 7830 break; 7831 if (In2.getOpcode() != ISD::FP_EXTEND && 7832 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 7833 break; 7834 In2 = In2.getOperand(0); 7835 if (In2.getOpcode() != ISD::FNEG) 7836 break; 7837 SDLoc DL(N); 7838 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 7839 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 7840 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 7841 } 7842 case ISD::MGATHER: 7843 case ISD::MSCATTER: 7844 case ISD::VP_GATHER: 7845 case ISD::VP_SCATTER: { 7846 if (!DCI.isBeforeLegalize()) 7847 break; 7848 SDValue Index, ScaleOp; 7849 bool IsIndexScaled = false; 7850 bool IsIndexSigned = false; 7851 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 7852 Index = VPGSN->getIndex(); 7853 ScaleOp = VPGSN->getScale(); 7854 IsIndexScaled = VPGSN->isIndexScaled(); 7855 IsIndexSigned = VPGSN->isIndexSigned(); 7856 } else { 7857 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 7858 Index = MGSN->getIndex(); 7859 ScaleOp = MGSN->getScale(); 7860 IsIndexScaled = MGSN->isIndexScaled(); 7861 IsIndexSigned = MGSN->isIndexSigned(); 7862 } 7863 EVT IndexVT = Index.getValueType(); 7864 MVT XLenVT = Subtarget.getXLenVT(); 7865 // RISCV indexed loads only support the "unsigned unscaled" addressing 7866 // mode, so anything else must be manually legalized. 7867 bool NeedsIdxLegalization = 7868 IsIndexScaled || 7869 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 7870 if (!NeedsIdxLegalization) 7871 break; 7872 7873 SDLoc DL(N); 7874 7875 // Any index legalization should first promote to XLenVT, so we don't lose 7876 // bits when scaling. This may create an illegal index type so we let 7877 // LLVM's legalization take care of the splitting. 7878 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 7879 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 7880 IndexVT = IndexVT.changeVectorElementType(XLenVT); 7881 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 7882 DL, IndexVT, Index); 7883 } 7884 7885 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 7886 if (IsIndexScaled && Scale != 1) { 7887 // Manually scale the indices by the element size. 7888 // TODO: Sanitize the scale operand here? 7889 // TODO: For VP nodes, should we use VP_SHL here? 7890 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 7891 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 7892 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 7893 } 7894 7895 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 7896 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 7897 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 7898 {VPGN->getChain(), VPGN->getBasePtr(), Index, 7899 VPGN->getScale(), VPGN->getMask(), 7900 VPGN->getVectorLength()}, 7901 VPGN->getMemOperand(), NewIndexTy); 7902 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 7903 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 7904 {VPSN->getChain(), VPSN->getValue(), 7905 VPSN->getBasePtr(), Index, VPSN->getScale(), 7906 VPSN->getMask(), VPSN->getVectorLength()}, 7907 VPSN->getMemOperand(), NewIndexTy); 7908 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 7909 return DAG.getMaskedGather( 7910 N->getVTList(), MGN->getMemoryVT(), DL, 7911 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 7912 MGN->getBasePtr(), Index, MGN->getScale()}, 7913 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 7914 const auto *MSN = cast<MaskedScatterSDNode>(N); 7915 return DAG.getMaskedScatter( 7916 N->getVTList(), MSN->getMemoryVT(), DL, 7917 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 7918 Index, MSN->getScale()}, 7919 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 7920 } 7921 case RISCVISD::SRA_VL: 7922 case RISCVISD::SRL_VL: 7923 case RISCVISD::SHL_VL: { 7924 SDValue ShAmt = N->getOperand(1); 7925 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7926 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7927 SDLoc DL(N); 7928 SDValue VL = N->getOperand(3); 7929 EVT VT = N->getValueType(0); 7930 ShAmt = 7931 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL); 7932 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 7933 N->getOperand(2), N->getOperand(3)); 7934 } 7935 break; 7936 } 7937 case ISD::SRA: 7938 case ISD::SRL: 7939 case ISD::SHL: { 7940 SDValue ShAmt = N->getOperand(1); 7941 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 7942 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 7943 SDLoc DL(N); 7944 EVT VT = N->getValueType(0); 7945 ShAmt = 7946 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0)); 7947 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 7948 } 7949 break; 7950 } 7951 case RISCVISD::MUL_VL: 7952 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 7953 return V; 7954 // Mul is commutative. 7955 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 7956 case ISD::STORE: { 7957 auto *Store = cast<StoreSDNode>(N); 7958 SDValue Val = Store->getValue(); 7959 // Combine store of vmv.x.s to vse with VL of 1. 7960 // FIXME: Support FP. 7961 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 7962 SDValue Src = Val.getOperand(0); 7963 EVT VecVT = Src.getValueType(); 7964 EVT MemVT = Store->getMemoryVT(); 7965 // The memory VT and the element type must match. 7966 if (VecVT.getVectorElementType() == MemVT) { 7967 SDLoc DL(N); 7968 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 7969 return DAG.getStoreVP( 7970 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 7971 DAG.getConstant(1, DL, MaskVT), 7972 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 7973 Store->getMemOperand(), Store->getAddressingMode(), 7974 Store->isTruncatingStore(), /*IsCompress*/ false); 7975 } 7976 } 7977 7978 break; 7979 } 7980 } 7981 7982 return SDValue(); 7983 } 7984 7985 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 7986 const SDNode *N, CombineLevel Level) const { 7987 // The following folds are only desirable if `(OP _, c1 << c2)` can be 7988 // materialised in fewer instructions than `(OP _, c1)`: 7989 // 7990 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 7991 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 7992 SDValue N0 = N->getOperand(0); 7993 EVT Ty = N0.getValueType(); 7994 if (Ty.isScalarInteger() && 7995 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 7996 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7997 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7998 if (C1 && C2) { 7999 const APInt &C1Int = C1->getAPIntValue(); 8000 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8001 8002 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8003 // and the combine should happen, to potentially allow further combines 8004 // later. 8005 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8006 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8007 return true; 8008 8009 // We can materialise `c1` in an add immediate, so it's "free", and the 8010 // combine should be prevented. 8011 if (C1Int.getMinSignedBits() <= 64 && 8012 isLegalAddImmediate(C1Int.getSExtValue())) 8013 return false; 8014 8015 // Neither constant will fit into an immediate, so find materialisation 8016 // costs. 8017 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8018 Subtarget.getFeatureBits(), 8019 /*CompressionCost*/true); 8020 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8021 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8022 /*CompressionCost*/true); 8023 8024 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8025 // combine should be prevented. 8026 if (C1Cost < ShiftedC1Cost) 8027 return false; 8028 } 8029 } 8030 return true; 8031 } 8032 8033 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8034 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8035 TargetLoweringOpt &TLO) const { 8036 // Delay this optimization as late as possible. 8037 if (!TLO.LegalOps) 8038 return false; 8039 8040 EVT VT = Op.getValueType(); 8041 if (VT.isVector()) 8042 return false; 8043 8044 // Only handle AND for now. 8045 if (Op.getOpcode() != ISD::AND) 8046 return false; 8047 8048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8049 if (!C) 8050 return false; 8051 8052 const APInt &Mask = C->getAPIntValue(); 8053 8054 // Clear all non-demanded bits initially. 8055 APInt ShrunkMask = Mask & DemandedBits; 8056 8057 // Try to make a smaller immediate by setting undemanded bits. 8058 8059 APInt ExpandedMask = Mask | ~DemandedBits; 8060 8061 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8062 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8063 }; 8064 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8065 if (NewMask == Mask) 8066 return true; 8067 SDLoc DL(Op); 8068 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8069 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8070 return TLO.CombineTo(Op, NewOp); 8071 }; 8072 8073 // If the shrunk mask fits in sign extended 12 bits, let the target 8074 // independent code apply it. 8075 if (ShrunkMask.isSignedIntN(12)) 8076 return false; 8077 8078 // Preserve (and X, 0xffff) when zext.h is supported. 8079 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8080 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8081 if (IsLegalMask(NewMask)) 8082 return UseMask(NewMask); 8083 } 8084 8085 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8086 if (VT == MVT::i64) { 8087 APInt NewMask = APInt(64, 0xffffffff); 8088 if (IsLegalMask(NewMask)) 8089 return UseMask(NewMask); 8090 } 8091 8092 // For the remaining optimizations, we need to be able to make a negative 8093 // number through a combination of mask and undemanded bits. 8094 if (!ExpandedMask.isNegative()) 8095 return false; 8096 8097 // What is the fewest number of bits we need to represent the negative number. 8098 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8099 8100 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8101 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8102 APInt NewMask = ShrunkMask; 8103 if (MinSignedBits <= 12) 8104 NewMask.setBitsFrom(11); 8105 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 8106 NewMask.setBitsFrom(31); 8107 else 8108 return false; 8109 8110 // Check that our new mask is a subset of the demanded mask. 8111 assert(IsLegalMask(NewMask)); 8112 return UseMask(NewMask); 8113 } 8114 8115 static void computeGREV(APInt &Src, unsigned ShAmt) { 8116 ShAmt &= Src.getBitWidth() - 1; 8117 uint64_t x = Src.getZExtValue(); 8118 if (ShAmt & 1) 8119 x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1); 8120 if (ShAmt & 2) 8121 x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2); 8122 if (ShAmt & 4) 8123 x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4); 8124 if (ShAmt & 8) 8125 x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8); 8126 if (ShAmt & 16) 8127 x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16); 8128 if (ShAmt & 32) 8129 x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32); 8130 Src = x; 8131 } 8132 8133 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 8134 KnownBits &Known, 8135 const APInt &DemandedElts, 8136 const SelectionDAG &DAG, 8137 unsigned Depth) const { 8138 unsigned BitWidth = Known.getBitWidth(); 8139 unsigned Opc = Op.getOpcode(); 8140 assert((Opc >= ISD::BUILTIN_OP_END || 8141 Opc == ISD::INTRINSIC_WO_CHAIN || 8142 Opc == ISD::INTRINSIC_W_CHAIN || 8143 Opc == ISD::INTRINSIC_VOID) && 8144 "Should use MaskedValueIsZero if you don't know whether Op" 8145 " is a target node!"); 8146 8147 Known.resetAll(); 8148 switch (Opc) { 8149 default: break; 8150 case RISCVISD::SELECT_CC: { 8151 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 8152 // If we don't know any bits, early out. 8153 if (Known.isUnknown()) 8154 break; 8155 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 8156 8157 // Only known if known in both the LHS and RHS. 8158 Known = KnownBits::commonBits(Known, Known2); 8159 break; 8160 } 8161 case RISCVISD::REMUW: { 8162 KnownBits Known2; 8163 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8164 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8165 // We only care about the lower 32 bits. 8166 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 8167 // Restore the original width by sign extending. 8168 Known = Known.sext(BitWidth); 8169 break; 8170 } 8171 case RISCVISD::DIVUW: { 8172 KnownBits Known2; 8173 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 8174 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 8175 // We only care about the lower 32 bits. 8176 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 8177 // Restore the original width by sign extending. 8178 Known = Known.sext(BitWidth); 8179 break; 8180 } 8181 case RISCVISD::CTZW: { 8182 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8183 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 8184 unsigned LowBits = Log2_32(PossibleTZ) + 1; 8185 Known.Zero.setBitsFrom(LowBits); 8186 break; 8187 } 8188 case RISCVISD::CLZW: { 8189 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8190 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 8191 unsigned LowBits = Log2_32(PossibleLZ) + 1; 8192 Known.Zero.setBitsFrom(LowBits); 8193 break; 8194 } 8195 case RISCVISD::GREV: 8196 case RISCVISD::GREVW: { 8197 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8198 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 8199 if (Opc == RISCVISD::GREVW) 8200 Known = Known.trunc(32); 8201 unsigned ShAmt = C->getZExtValue(); 8202 computeGREV(Known.Zero, ShAmt); 8203 computeGREV(Known.One, ShAmt); 8204 if (Opc == RISCVISD::GREVW) 8205 Known = Known.sext(BitWidth); 8206 } 8207 break; 8208 } 8209 case RISCVISD::READ_VLENB: 8210 // We assume VLENB is at least 16 bytes. 8211 Known.Zero.setLowBits(4); 8212 // We assume VLENB is no more than 65536 / 8 bytes. 8213 Known.Zero.setBitsFrom(14); 8214 break; 8215 case ISD::INTRINSIC_W_CHAIN: 8216 case ISD::INTRINSIC_WO_CHAIN: { 8217 unsigned IntNo = 8218 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 8219 switch (IntNo) { 8220 default: 8221 // We can't do anything for most intrinsics. 8222 break; 8223 case Intrinsic::riscv_vsetvli: 8224 case Intrinsic::riscv_vsetvlimax: 8225 case Intrinsic::riscv_vsetvli_opt: 8226 case Intrinsic::riscv_vsetvlimax_opt: 8227 // Assume that VL output is positive and would fit in an int32_t. 8228 // TODO: VLEN might be capped at 16 bits in a future V spec update. 8229 if (BitWidth >= 32) 8230 Known.Zero.setBitsFrom(31); 8231 break; 8232 } 8233 break; 8234 } 8235 } 8236 } 8237 8238 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 8239 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 8240 unsigned Depth) const { 8241 switch (Op.getOpcode()) { 8242 default: 8243 break; 8244 case RISCVISD::SELECT_CC: { 8245 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 8246 if (Tmp == 1) return 1; // Early out. 8247 unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 8248 return std::min(Tmp, Tmp2); 8249 } 8250 case RISCVISD::SLLW: 8251 case RISCVISD::SRAW: 8252 case RISCVISD::SRLW: 8253 case RISCVISD::DIVW: 8254 case RISCVISD::DIVUW: 8255 case RISCVISD::REMUW: 8256 case RISCVISD::ROLW: 8257 case RISCVISD::RORW: 8258 case RISCVISD::GREVW: 8259 case RISCVISD::GORCW: 8260 case RISCVISD::FSLW: 8261 case RISCVISD::FSRW: 8262 case RISCVISD::SHFLW: 8263 case RISCVISD::UNSHFLW: 8264 case RISCVISD::BCOMPRESSW: 8265 case RISCVISD::BDECOMPRESSW: 8266 case RISCVISD::BFPW: 8267 case RISCVISD::FCVT_W_RV64: 8268 case RISCVISD::FCVT_WU_RV64: 8269 case RISCVISD::STRICT_FCVT_W_RV64: 8270 case RISCVISD::STRICT_FCVT_WU_RV64: 8271 // TODO: As the result is sign-extended, this is conservatively correct. A 8272 // more precise answer could be calculated for SRAW depending on known 8273 // bits in the shift amount. 8274 return 33; 8275 case RISCVISD::SHFL: 8276 case RISCVISD::UNSHFL: { 8277 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 8278 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 8279 // will stay within the upper 32 bits. If there were more than 32 sign bits 8280 // before there will be at least 33 sign bits after. 8281 if (Op.getValueType() == MVT::i64 && 8282 isa<ConstantSDNode>(Op.getOperand(1)) && 8283 (Op.getConstantOperandVal(1) & 0x10) == 0) { 8284 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 8285 if (Tmp > 32) 8286 return 33; 8287 } 8288 break; 8289 } 8290 case RISCVISD::VMV_X_S: 8291 // The number of sign bits of the scalar result is computed by obtaining the 8292 // element type of the input vector operand, subtracting its width from the 8293 // XLEN, and then adding one (sign bit within the element type). If the 8294 // element type is wider than XLen, the least-significant XLEN bits are 8295 // taken. 8296 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 8297 return 1; 8298 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 8299 } 8300 8301 return 1; 8302 } 8303 8304 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 8305 MachineBasicBlock *BB) { 8306 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 8307 8308 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 8309 // Should the count have wrapped while it was being read, we need to try 8310 // again. 8311 // ... 8312 // read: 8313 // rdcycleh x3 # load high word of cycle 8314 // rdcycle x2 # load low word of cycle 8315 // rdcycleh x4 # load high word of cycle 8316 // bne x3, x4, read # check if high word reads match, otherwise try again 8317 // ... 8318 8319 MachineFunction &MF = *BB->getParent(); 8320 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8321 MachineFunction::iterator It = ++BB->getIterator(); 8322 8323 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8324 MF.insert(It, LoopMBB); 8325 8326 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 8327 MF.insert(It, DoneMBB); 8328 8329 // Transfer the remainder of BB and its successor edges to DoneMBB. 8330 DoneMBB->splice(DoneMBB->begin(), BB, 8331 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8332 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 8333 8334 BB->addSuccessor(LoopMBB); 8335 8336 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8337 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 8338 Register LoReg = MI.getOperand(0).getReg(); 8339 Register HiReg = MI.getOperand(1).getReg(); 8340 DebugLoc DL = MI.getDebugLoc(); 8341 8342 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 8343 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 8344 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8345 .addReg(RISCV::X0); 8346 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 8347 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 8348 .addReg(RISCV::X0); 8349 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 8350 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 8351 .addReg(RISCV::X0); 8352 8353 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 8354 .addReg(HiReg) 8355 .addReg(ReadAgainReg) 8356 .addMBB(LoopMBB); 8357 8358 LoopMBB->addSuccessor(LoopMBB); 8359 LoopMBB->addSuccessor(DoneMBB); 8360 8361 MI.eraseFromParent(); 8362 8363 return DoneMBB; 8364 } 8365 8366 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 8367 MachineBasicBlock *BB) { 8368 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 8369 8370 MachineFunction &MF = *BB->getParent(); 8371 DebugLoc DL = MI.getDebugLoc(); 8372 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8373 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8374 Register LoReg = MI.getOperand(0).getReg(); 8375 Register HiReg = MI.getOperand(1).getReg(); 8376 Register SrcReg = MI.getOperand(2).getReg(); 8377 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 8378 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8379 8380 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 8381 RI); 8382 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8383 MachineMemOperand *MMOLo = 8384 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 8385 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8386 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 8387 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 8388 .addFrameIndex(FI) 8389 .addImm(0) 8390 .addMemOperand(MMOLo); 8391 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 8392 .addFrameIndex(FI) 8393 .addImm(4) 8394 .addMemOperand(MMOHi); 8395 MI.eraseFromParent(); // The pseudo instruction is gone now. 8396 return BB; 8397 } 8398 8399 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 8400 MachineBasicBlock *BB) { 8401 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 8402 "Unexpected instruction"); 8403 8404 MachineFunction &MF = *BB->getParent(); 8405 DebugLoc DL = MI.getDebugLoc(); 8406 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 8407 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 8408 Register DstReg = MI.getOperand(0).getReg(); 8409 Register LoReg = MI.getOperand(1).getReg(); 8410 Register HiReg = MI.getOperand(2).getReg(); 8411 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 8412 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 8413 8414 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 8415 MachineMemOperand *MMOLo = 8416 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 8417 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 8418 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 8419 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8420 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 8421 .addFrameIndex(FI) 8422 .addImm(0) 8423 .addMemOperand(MMOLo); 8424 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 8425 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 8426 .addFrameIndex(FI) 8427 .addImm(4) 8428 .addMemOperand(MMOHi); 8429 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 8430 MI.eraseFromParent(); // The pseudo instruction is gone now. 8431 return BB; 8432 } 8433 8434 static bool isSelectPseudo(MachineInstr &MI) { 8435 switch (MI.getOpcode()) { 8436 default: 8437 return false; 8438 case RISCV::Select_GPR_Using_CC_GPR: 8439 case RISCV::Select_FPR16_Using_CC_GPR: 8440 case RISCV::Select_FPR32_Using_CC_GPR: 8441 case RISCV::Select_FPR64_Using_CC_GPR: 8442 return true; 8443 } 8444 } 8445 8446 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 8447 unsigned RelOpcode, unsigned EqOpcode, 8448 const RISCVSubtarget &Subtarget) { 8449 DebugLoc DL = MI.getDebugLoc(); 8450 Register DstReg = MI.getOperand(0).getReg(); 8451 Register Src1Reg = MI.getOperand(1).getReg(); 8452 Register Src2Reg = MI.getOperand(2).getReg(); 8453 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 8454 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 8455 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 8456 8457 // Save the current FFLAGS. 8458 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 8459 8460 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 8461 .addReg(Src1Reg) 8462 .addReg(Src2Reg); 8463 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8464 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 8465 8466 // Restore the FFLAGS. 8467 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 8468 .addReg(SavedFFlags, RegState::Kill); 8469 8470 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 8471 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 8472 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 8473 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 8474 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 8475 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 8476 8477 // Erase the pseudoinstruction. 8478 MI.eraseFromParent(); 8479 return BB; 8480 } 8481 8482 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 8483 MachineBasicBlock *BB, 8484 const RISCVSubtarget &Subtarget) { 8485 // To "insert" Select_* instructions, we actually have to insert the triangle 8486 // control-flow pattern. The incoming instructions know the destination vreg 8487 // to set, the condition code register to branch on, the true/false values to 8488 // select between, and the condcode to use to select the appropriate branch. 8489 // 8490 // We produce the following control flow: 8491 // HeadMBB 8492 // | \ 8493 // | IfFalseMBB 8494 // | / 8495 // TailMBB 8496 // 8497 // When we find a sequence of selects we attempt to optimize their emission 8498 // by sharing the control flow. Currently we only handle cases where we have 8499 // multiple selects with the exact same condition (same LHS, RHS and CC). 8500 // The selects may be interleaved with other instructions if the other 8501 // instructions meet some requirements we deem safe: 8502 // - They are debug instructions. Otherwise, 8503 // - They do not have side-effects, do not access memory and their inputs do 8504 // not depend on the results of the select pseudo-instructions. 8505 // The TrueV/FalseV operands of the selects cannot depend on the result of 8506 // previous selects in the sequence. 8507 // These conditions could be further relaxed. See the X86 target for a 8508 // related approach and more information. 8509 Register LHS = MI.getOperand(1).getReg(); 8510 Register RHS = MI.getOperand(2).getReg(); 8511 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 8512 8513 SmallVector<MachineInstr *, 4> SelectDebugValues; 8514 SmallSet<Register, 4> SelectDests; 8515 SelectDests.insert(MI.getOperand(0).getReg()); 8516 8517 MachineInstr *LastSelectPseudo = &MI; 8518 8519 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 8520 SequenceMBBI != E; ++SequenceMBBI) { 8521 if (SequenceMBBI->isDebugInstr()) 8522 continue; 8523 else if (isSelectPseudo(*SequenceMBBI)) { 8524 if (SequenceMBBI->getOperand(1).getReg() != LHS || 8525 SequenceMBBI->getOperand(2).getReg() != RHS || 8526 SequenceMBBI->getOperand(3).getImm() != CC || 8527 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 8528 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 8529 break; 8530 LastSelectPseudo = &*SequenceMBBI; 8531 SequenceMBBI->collectDebugValues(SelectDebugValues); 8532 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 8533 } else { 8534 if (SequenceMBBI->hasUnmodeledSideEffects() || 8535 SequenceMBBI->mayLoadOrStore()) 8536 break; 8537 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 8538 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 8539 })) 8540 break; 8541 } 8542 } 8543 8544 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 8545 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8546 DebugLoc DL = MI.getDebugLoc(); 8547 MachineFunction::iterator I = ++BB->getIterator(); 8548 8549 MachineBasicBlock *HeadMBB = BB; 8550 MachineFunction *F = BB->getParent(); 8551 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 8552 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 8553 8554 F->insert(I, IfFalseMBB); 8555 F->insert(I, TailMBB); 8556 8557 // Transfer debug instructions associated with the selects to TailMBB. 8558 for (MachineInstr *DebugInstr : SelectDebugValues) { 8559 TailMBB->push_back(DebugInstr->removeFromParent()); 8560 } 8561 8562 // Move all instructions after the sequence to TailMBB. 8563 TailMBB->splice(TailMBB->end(), HeadMBB, 8564 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 8565 // Update machine-CFG edges by transferring all successors of the current 8566 // block to the new block which will contain the Phi nodes for the selects. 8567 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 8568 // Set the successors for HeadMBB. 8569 HeadMBB->addSuccessor(IfFalseMBB); 8570 HeadMBB->addSuccessor(TailMBB); 8571 8572 // Insert appropriate branch. 8573 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 8574 .addReg(LHS) 8575 .addReg(RHS) 8576 .addMBB(TailMBB); 8577 8578 // IfFalseMBB just falls through to TailMBB. 8579 IfFalseMBB->addSuccessor(TailMBB); 8580 8581 // Create PHIs for all of the select pseudo-instructions. 8582 auto SelectMBBI = MI.getIterator(); 8583 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 8584 auto InsertionPoint = TailMBB->begin(); 8585 while (SelectMBBI != SelectEnd) { 8586 auto Next = std::next(SelectMBBI); 8587 if (isSelectPseudo(*SelectMBBI)) { 8588 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 8589 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 8590 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 8591 .addReg(SelectMBBI->getOperand(4).getReg()) 8592 .addMBB(HeadMBB) 8593 .addReg(SelectMBBI->getOperand(5).getReg()) 8594 .addMBB(IfFalseMBB); 8595 SelectMBBI->eraseFromParent(); 8596 } 8597 SelectMBBI = Next; 8598 } 8599 8600 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 8601 return TailMBB; 8602 } 8603 8604 MachineBasicBlock * 8605 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8606 MachineBasicBlock *BB) const { 8607 switch (MI.getOpcode()) { 8608 default: 8609 llvm_unreachable("Unexpected instr type to insert"); 8610 case RISCV::ReadCycleWide: 8611 assert(!Subtarget.is64Bit() && 8612 "ReadCycleWrite is only to be used on riscv32"); 8613 return emitReadCycleWidePseudo(MI, BB); 8614 case RISCV::Select_GPR_Using_CC_GPR: 8615 case RISCV::Select_FPR16_Using_CC_GPR: 8616 case RISCV::Select_FPR32_Using_CC_GPR: 8617 case RISCV::Select_FPR64_Using_CC_GPR: 8618 return emitSelectPseudo(MI, BB, Subtarget); 8619 case RISCV::BuildPairF64Pseudo: 8620 return emitBuildPairF64Pseudo(MI, BB); 8621 case RISCV::SplitF64Pseudo: 8622 return emitSplitF64Pseudo(MI, BB); 8623 case RISCV::PseudoQuietFLE_H: 8624 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 8625 case RISCV::PseudoQuietFLT_H: 8626 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 8627 case RISCV::PseudoQuietFLE_S: 8628 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 8629 case RISCV::PseudoQuietFLT_S: 8630 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 8631 case RISCV::PseudoQuietFLE_D: 8632 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 8633 case RISCV::PseudoQuietFLT_D: 8634 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 8635 } 8636 } 8637 8638 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 8639 SDNode *Node) const { 8640 // Add FRM dependency to any instructions with dynamic rounding mode. 8641 unsigned Opc = MI.getOpcode(); 8642 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 8643 if (Idx < 0) 8644 return; 8645 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 8646 return; 8647 // If the instruction already reads FRM, don't add another read. 8648 if (MI.readsRegister(RISCV::FRM)) 8649 return; 8650 MI.addOperand( 8651 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 8652 } 8653 8654 // Calling Convention Implementation. 8655 // The expectations for frontend ABI lowering vary from target to target. 8656 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 8657 // details, but this is a longer term goal. For now, we simply try to keep the 8658 // role of the frontend as simple and well-defined as possible. The rules can 8659 // be summarised as: 8660 // * Never split up large scalar arguments. We handle them here. 8661 // * If a hardfloat calling convention is being used, and the struct may be 8662 // passed in a pair of registers (fp+fp, int+fp), and both registers are 8663 // available, then pass as two separate arguments. If either the GPRs or FPRs 8664 // are exhausted, then pass according to the rule below. 8665 // * If a struct could never be passed in registers or directly in a stack 8666 // slot (as it is larger than 2*XLEN and the floating point rules don't 8667 // apply), then pass it using a pointer with the byval attribute. 8668 // * If a struct is less than 2*XLEN, then coerce to either a two-element 8669 // word-sized array or a 2*XLEN scalar (depending on alignment). 8670 // * The frontend can determine whether a struct is returned by reference or 8671 // not based on its size and fields. If it will be returned by reference, the 8672 // frontend must modify the prototype so a pointer with the sret annotation is 8673 // passed as the first argument. This is not necessary for large scalar 8674 // returns. 8675 // * Struct return values and varargs should be coerced to structs containing 8676 // register-size fields in the same situations they would be for fixed 8677 // arguments. 8678 8679 static const MCPhysReg ArgGPRs[] = { 8680 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 8681 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 8682 }; 8683 static const MCPhysReg ArgFPR16s[] = { 8684 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 8685 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 8686 }; 8687 static const MCPhysReg ArgFPR32s[] = { 8688 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 8689 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 8690 }; 8691 static const MCPhysReg ArgFPR64s[] = { 8692 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 8693 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 8694 }; 8695 // This is an interim calling convention and it may be changed in the future. 8696 static const MCPhysReg ArgVRs[] = { 8697 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 8698 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 8699 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 8700 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 8701 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 8702 RISCV::V20M2, RISCV::V22M2}; 8703 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 8704 RISCV::V20M4}; 8705 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 8706 8707 // Pass a 2*XLEN argument that has been split into two XLEN values through 8708 // registers or the stack as necessary. 8709 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 8710 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 8711 MVT ValVT2, MVT LocVT2, 8712 ISD::ArgFlagsTy ArgFlags2) { 8713 unsigned XLenInBytes = XLen / 8; 8714 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8715 // At least one half can be passed via register. 8716 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 8717 VA1.getLocVT(), CCValAssign::Full)); 8718 } else { 8719 // Both halves must be passed on the stack, with proper alignment. 8720 Align StackAlign = 8721 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 8722 State.addLoc( 8723 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 8724 State.AllocateStack(XLenInBytes, StackAlign), 8725 VA1.getLocVT(), CCValAssign::Full)); 8726 State.addLoc(CCValAssign::getMem( 8727 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8728 LocVT2, CCValAssign::Full)); 8729 return false; 8730 } 8731 8732 if (Register Reg = State.AllocateReg(ArgGPRs)) { 8733 // The second half can also be passed via register. 8734 State.addLoc( 8735 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 8736 } else { 8737 // The second half is passed via the stack, without additional alignment. 8738 State.addLoc(CCValAssign::getMem( 8739 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 8740 LocVT2, CCValAssign::Full)); 8741 } 8742 8743 return false; 8744 } 8745 8746 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 8747 Optional<unsigned> FirstMaskArgument, 8748 CCState &State, const RISCVTargetLowering &TLI) { 8749 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 8750 if (RC == &RISCV::VRRegClass) { 8751 // Assign the first mask argument to V0. 8752 // This is an interim calling convention and it may be changed in the 8753 // future. 8754 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 8755 return State.AllocateReg(RISCV::V0); 8756 return State.AllocateReg(ArgVRs); 8757 } 8758 if (RC == &RISCV::VRM2RegClass) 8759 return State.AllocateReg(ArgVRM2s); 8760 if (RC == &RISCV::VRM4RegClass) 8761 return State.AllocateReg(ArgVRM4s); 8762 if (RC == &RISCV::VRM8RegClass) 8763 return State.AllocateReg(ArgVRM8s); 8764 llvm_unreachable("Unhandled register class for ValueType"); 8765 } 8766 8767 // Implements the RISC-V calling convention. Returns true upon failure. 8768 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 8769 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 8770 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 8771 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 8772 Optional<unsigned> FirstMaskArgument) { 8773 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 8774 assert(XLen == 32 || XLen == 64); 8775 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 8776 8777 // Any return value split in to more than two values can't be returned 8778 // directly. Vectors are returned via the available vector registers. 8779 if (!LocVT.isVector() && IsRet && ValNo > 1) 8780 return true; 8781 8782 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 8783 // variadic argument, or if no F16/F32 argument registers are available. 8784 bool UseGPRForF16_F32 = true; 8785 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 8786 // variadic argument, or if no F64 argument registers are available. 8787 bool UseGPRForF64 = true; 8788 8789 switch (ABI) { 8790 default: 8791 llvm_unreachable("Unexpected ABI"); 8792 case RISCVABI::ABI_ILP32: 8793 case RISCVABI::ABI_LP64: 8794 break; 8795 case RISCVABI::ABI_ILP32F: 8796 case RISCVABI::ABI_LP64F: 8797 UseGPRForF16_F32 = !IsFixed; 8798 break; 8799 case RISCVABI::ABI_ILP32D: 8800 case RISCVABI::ABI_LP64D: 8801 UseGPRForF16_F32 = !IsFixed; 8802 UseGPRForF64 = !IsFixed; 8803 break; 8804 } 8805 8806 // FPR16, FPR32, and FPR64 alias each other. 8807 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 8808 UseGPRForF16_F32 = true; 8809 UseGPRForF64 = true; 8810 } 8811 8812 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 8813 // similar local variables rather than directly checking against the target 8814 // ABI. 8815 8816 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 8817 LocVT = XLenVT; 8818 LocInfo = CCValAssign::BCvt; 8819 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 8820 LocVT = MVT::i64; 8821 LocInfo = CCValAssign::BCvt; 8822 } 8823 8824 // If this is a variadic argument, the RISC-V calling convention requires 8825 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 8826 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 8827 // be used regardless of whether the original argument was split during 8828 // legalisation or not. The argument will not be passed by registers if the 8829 // original type is larger than 2*XLEN, so the register alignment rule does 8830 // not apply. 8831 unsigned TwoXLenInBytes = (2 * XLen) / 8; 8832 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 8833 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 8834 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 8835 // Skip 'odd' register if necessary. 8836 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 8837 State.AllocateReg(ArgGPRs); 8838 } 8839 8840 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 8841 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 8842 State.getPendingArgFlags(); 8843 8844 assert(PendingLocs.size() == PendingArgFlags.size() && 8845 "PendingLocs and PendingArgFlags out of sync"); 8846 8847 // Handle passing f64 on RV32D with a soft float ABI or when floating point 8848 // registers are exhausted. 8849 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 8850 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 8851 "Can't lower f64 if it is split"); 8852 // Depending on available argument GPRS, f64 may be passed in a pair of 8853 // GPRs, split between a GPR and the stack, or passed completely on the 8854 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 8855 // cases. 8856 Register Reg = State.AllocateReg(ArgGPRs); 8857 LocVT = MVT::i32; 8858 if (!Reg) { 8859 unsigned StackOffset = State.AllocateStack(8, Align(8)); 8860 State.addLoc( 8861 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8862 return false; 8863 } 8864 if (!State.AllocateReg(ArgGPRs)) 8865 State.AllocateStack(4, Align(4)); 8866 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8867 return false; 8868 } 8869 8870 // Fixed-length vectors are located in the corresponding scalable-vector 8871 // container types. 8872 if (ValVT.isFixedLengthVector()) 8873 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 8874 8875 // Split arguments might be passed indirectly, so keep track of the pending 8876 // values. Split vectors are passed via a mix of registers and indirectly, so 8877 // treat them as we would any other argument. 8878 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 8879 LocVT = XLenVT; 8880 LocInfo = CCValAssign::Indirect; 8881 PendingLocs.push_back( 8882 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 8883 PendingArgFlags.push_back(ArgFlags); 8884 if (!ArgFlags.isSplitEnd()) { 8885 return false; 8886 } 8887 } 8888 8889 // If the split argument only had two elements, it should be passed directly 8890 // in registers or on the stack. 8891 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 8892 PendingLocs.size() <= 2) { 8893 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 8894 // Apply the normal calling convention rules to the first half of the 8895 // split argument. 8896 CCValAssign VA = PendingLocs[0]; 8897 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 8898 PendingLocs.clear(); 8899 PendingArgFlags.clear(); 8900 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 8901 ArgFlags); 8902 } 8903 8904 // Allocate to a register if possible, or else a stack slot. 8905 Register Reg; 8906 unsigned StoreSizeBytes = XLen / 8; 8907 Align StackAlign = Align(XLen / 8); 8908 8909 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 8910 Reg = State.AllocateReg(ArgFPR16s); 8911 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 8912 Reg = State.AllocateReg(ArgFPR32s); 8913 else if (ValVT == MVT::f64 && !UseGPRForF64) 8914 Reg = State.AllocateReg(ArgFPR64s); 8915 else if (ValVT.isVector()) { 8916 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 8917 if (!Reg) { 8918 // For return values, the vector must be passed fully via registers or 8919 // via the stack. 8920 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 8921 // but we're using all of them. 8922 if (IsRet) 8923 return true; 8924 // Try using a GPR to pass the address 8925 if ((Reg = State.AllocateReg(ArgGPRs))) { 8926 LocVT = XLenVT; 8927 LocInfo = CCValAssign::Indirect; 8928 } else if (ValVT.isScalableVector()) { 8929 LocVT = XLenVT; 8930 LocInfo = CCValAssign::Indirect; 8931 } else { 8932 // Pass fixed-length vectors on the stack. 8933 LocVT = ValVT; 8934 StoreSizeBytes = ValVT.getStoreSize(); 8935 // Align vectors to their element sizes, being careful for vXi1 8936 // vectors. 8937 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 8938 } 8939 } 8940 } else { 8941 Reg = State.AllocateReg(ArgGPRs); 8942 } 8943 8944 unsigned StackOffset = 8945 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 8946 8947 // If we reach this point and PendingLocs is non-empty, we must be at the 8948 // end of a split argument that must be passed indirectly. 8949 if (!PendingLocs.empty()) { 8950 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 8951 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 8952 8953 for (auto &It : PendingLocs) { 8954 if (Reg) 8955 It.convertToReg(Reg); 8956 else 8957 It.convertToMem(StackOffset); 8958 State.addLoc(It); 8959 } 8960 PendingLocs.clear(); 8961 PendingArgFlags.clear(); 8962 return false; 8963 } 8964 8965 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 8966 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 8967 "Expected an XLenVT or vector types at this stage"); 8968 8969 if (Reg) { 8970 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 8971 return false; 8972 } 8973 8974 // When a floating-point value is passed on the stack, no bit-conversion is 8975 // needed. 8976 if (ValVT.isFloatingPoint()) { 8977 LocVT = ValVT; 8978 LocInfo = CCValAssign::Full; 8979 } 8980 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 8981 return false; 8982 } 8983 8984 template <typename ArgTy> 8985 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 8986 for (const auto &ArgIdx : enumerate(Args)) { 8987 MVT ArgVT = ArgIdx.value().VT; 8988 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 8989 return ArgIdx.index(); 8990 } 8991 return None; 8992 } 8993 8994 void RISCVTargetLowering::analyzeInputArgs( 8995 MachineFunction &MF, CCState &CCInfo, 8996 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 8997 RISCVCCAssignFn Fn) const { 8998 unsigned NumArgs = Ins.size(); 8999 FunctionType *FType = MF.getFunction().getFunctionType(); 9000 9001 Optional<unsigned> FirstMaskArgument; 9002 if (Subtarget.hasVInstructions()) 9003 FirstMaskArgument = preAssignMask(Ins); 9004 9005 for (unsigned i = 0; i != NumArgs; ++i) { 9006 MVT ArgVT = Ins[i].VT; 9007 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9008 9009 Type *ArgTy = nullptr; 9010 if (IsRet) 9011 ArgTy = FType->getReturnType(); 9012 else if (Ins[i].isOrigArg()) 9013 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9014 9015 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9016 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9017 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9018 FirstMaskArgument)) { 9019 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9020 << EVT(ArgVT).getEVTString() << '\n'); 9021 llvm_unreachable(nullptr); 9022 } 9023 } 9024 } 9025 9026 void RISCVTargetLowering::analyzeOutputArgs( 9027 MachineFunction &MF, CCState &CCInfo, 9028 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9029 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9030 unsigned NumArgs = Outs.size(); 9031 9032 Optional<unsigned> FirstMaskArgument; 9033 if (Subtarget.hasVInstructions()) 9034 FirstMaskArgument = preAssignMask(Outs); 9035 9036 for (unsigned i = 0; i != NumArgs; i++) { 9037 MVT ArgVT = Outs[i].VT; 9038 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9039 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9040 9041 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9042 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9043 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9044 FirstMaskArgument)) { 9045 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9046 << EVT(ArgVT).getEVTString() << "\n"); 9047 llvm_unreachable(nullptr); 9048 } 9049 } 9050 } 9051 9052 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9053 // values. 9054 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9055 const CCValAssign &VA, const SDLoc &DL, 9056 const RISCVSubtarget &Subtarget) { 9057 switch (VA.getLocInfo()) { 9058 default: 9059 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9060 case CCValAssign::Full: 9061 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9062 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9063 break; 9064 case CCValAssign::BCvt: 9065 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9066 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9067 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9068 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9069 else 9070 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9071 break; 9072 } 9073 return Val; 9074 } 9075 9076 // The caller is responsible for loading the full value if the argument is 9077 // passed with CCValAssign::Indirect. 9078 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9079 const CCValAssign &VA, const SDLoc &DL, 9080 const RISCVTargetLowering &TLI) { 9081 MachineFunction &MF = DAG.getMachineFunction(); 9082 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9083 EVT LocVT = VA.getLocVT(); 9084 SDValue Val; 9085 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9086 Register VReg = RegInfo.createVirtualRegister(RC); 9087 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9088 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9089 9090 if (VA.getLocInfo() == CCValAssign::Indirect) 9091 return Val; 9092 9093 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9094 } 9095 9096 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 9097 const CCValAssign &VA, const SDLoc &DL, 9098 const RISCVSubtarget &Subtarget) { 9099 EVT LocVT = VA.getLocVT(); 9100 9101 switch (VA.getLocInfo()) { 9102 default: 9103 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9104 case CCValAssign::Full: 9105 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 9106 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 9107 break; 9108 case CCValAssign::BCvt: 9109 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9110 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 9111 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9112 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 9113 else 9114 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 9115 break; 9116 } 9117 return Val; 9118 } 9119 9120 // The caller is responsible for loading the full value if the argument is 9121 // passed with CCValAssign::Indirect. 9122 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 9123 const CCValAssign &VA, const SDLoc &DL) { 9124 MachineFunction &MF = DAG.getMachineFunction(); 9125 MachineFrameInfo &MFI = MF.getFrameInfo(); 9126 EVT LocVT = VA.getLocVT(); 9127 EVT ValVT = VA.getValVT(); 9128 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 9129 if (ValVT.isScalableVector()) { 9130 // When the value is a scalable vector, we save the pointer which points to 9131 // the scalable vector value in the stack. The ValVT will be the pointer 9132 // type, instead of the scalable vector type. 9133 ValVT = LocVT; 9134 } 9135 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 9136 /*IsImmutable=*/true); 9137 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 9138 SDValue Val; 9139 9140 ISD::LoadExtType ExtType; 9141 switch (VA.getLocInfo()) { 9142 default: 9143 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9144 case CCValAssign::Full: 9145 case CCValAssign::Indirect: 9146 case CCValAssign::BCvt: 9147 ExtType = ISD::NON_EXTLOAD; 9148 break; 9149 } 9150 Val = DAG.getExtLoad( 9151 ExtType, DL, LocVT, Chain, FIN, 9152 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 9153 return Val; 9154 } 9155 9156 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 9157 const CCValAssign &VA, const SDLoc &DL) { 9158 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 9159 "Unexpected VA"); 9160 MachineFunction &MF = DAG.getMachineFunction(); 9161 MachineFrameInfo &MFI = MF.getFrameInfo(); 9162 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9163 9164 if (VA.isMemLoc()) { 9165 // f64 is passed on the stack. 9166 int FI = 9167 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 9168 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9169 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 9170 MachinePointerInfo::getFixedStack(MF, FI)); 9171 } 9172 9173 assert(VA.isRegLoc() && "Expected register VA assignment"); 9174 9175 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9176 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 9177 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 9178 SDValue Hi; 9179 if (VA.getLocReg() == RISCV::X17) { 9180 // Second half of f64 is passed on the stack. 9181 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 9182 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 9183 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 9184 MachinePointerInfo::getFixedStack(MF, FI)); 9185 } else { 9186 // Second half of f64 is passed in another GPR. 9187 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9188 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 9189 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 9190 } 9191 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 9192 } 9193 9194 // FastCC has less than 1% performance improvement for some particular 9195 // benchmark. But theoretically, it may has benenfit for some cases. 9196 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 9197 unsigned ValNo, MVT ValVT, MVT LocVT, 9198 CCValAssign::LocInfo LocInfo, 9199 ISD::ArgFlagsTy ArgFlags, CCState &State, 9200 bool IsFixed, bool IsRet, Type *OrigTy, 9201 const RISCVTargetLowering &TLI, 9202 Optional<unsigned> FirstMaskArgument) { 9203 9204 // X5 and X6 might be used for save-restore libcall. 9205 static const MCPhysReg GPRList[] = { 9206 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 9207 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 9208 RISCV::X29, RISCV::X30, RISCV::X31}; 9209 9210 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9211 if (unsigned Reg = State.AllocateReg(GPRList)) { 9212 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9213 return false; 9214 } 9215 } 9216 9217 if (LocVT == MVT::f16) { 9218 static const MCPhysReg FPR16List[] = { 9219 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 9220 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 9221 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 9222 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 9223 if (unsigned Reg = State.AllocateReg(FPR16List)) { 9224 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9225 return false; 9226 } 9227 } 9228 9229 if (LocVT == MVT::f32) { 9230 static const MCPhysReg FPR32List[] = { 9231 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 9232 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 9233 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 9234 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 9235 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9236 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9237 return false; 9238 } 9239 } 9240 9241 if (LocVT == MVT::f64) { 9242 static const MCPhysReg FPR64List[] = { 9243 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 9244 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 9245 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 9246 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 9247 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9248 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9249 return false; 9250 } 9251 } 9252 9253 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 9254 unsigned Offset4 = State.AllocateStack(4, Align(4)); 9255 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 9256 return false; 9257 } 9258 9259 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 9260 unsigned Offset5 = State.AllocateStack(8, Align(8)); 9261 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 9262 return false; 9263 } 9264 9265 if (LocVT.isVector()) { 9266 if (unsigned Reg = 9267 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 9268 // Fixed-length vectors are located in the corresponding scalable-vector 9269 // container types. 9270 if (ValVT.isFixedLengthVector()) 9271 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9272 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9273 } else { 9274 // Try and pass the address via a "fast" GPR. 9275 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 9276 LocInfo = CCValAssign::Indirect; 9277 LocVT = TLI.getSubtarget().getXLenVT(); 9278 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 9279 } else if (ValVT.isFixedLengthVector()) { 9280 auto StackAlign = 9281 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9282 unsigned StackOffset = 9283 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 9284 State.addLoc( 9285 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9286 } else { 9287 // Can't pass scalable vectors on the stack. 9288 return true; 9289 } 9290 } 9291 9292 return false; 9293 } 9294 9295 return true; // CC didn't match. 9296 } 9297 9298 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 9299 CCValAssign::LocInfo LocInfo, 9300 ISD::ArgFlagsTy ArgFlags, CCState &State) { 9301 9302 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 9303 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 9304 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 9305 static const MCPhysReg GPRList[] = { 9306 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 9307 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 9308 if (unsigned Reg = State.AllocateReg(GPRList)) { 9309 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9310 return false; 9311 } 9312 } 9313 9314 if (LocVT == MVT::f32) { 9315 // Pass in STG registers: F1, ..., F6 9316 // fs0 ... fs5 9317 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 9318 RISCV::F18_F, RISCV::F19_F, 9319 RISCV::F20_F, RISCV::F21_F}; 9320 if (unsigned Reg = State.AllocateReg(FPR32List)) { 9321 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9322 return false; 9323 } 9324 } 9325 9326 if (LocVT == MVT::f64) { 9327 // Pass in STG registers: D1, ..., D6 9328 // fs6 ... fs11 9329 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 9330 RISCV::F24_D, RISCV::F25_D, 9331 RISCV::F26_D, RISCV::F27_D}; 9332 if (unsigned Reg = State.AllocateReg(FPR64List)) { 9333 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9334 return false; 9335 } 9336 } 9337 9338 report_fatal_error("No registers left in GHC calling convention"); 9339 return true; 9340 } 9341 9342 // Transform physical registers into virtual registers. 9343 SDValue RISCVTargetLowering::LowerFormalArguments( 9344 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 9345 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 9346 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 9347 9348 MachineFunction &MF = DAG.getMachineFunction(); 9349 9350 switch (CallConv) { 9351 default: 9352 report_fatal_error("Unsupported calling convention"); 9353 case CallingConv::C: 9354 case CallingConv::Fast: 9355 break; 9356 case CallingConv::GHC: 9357 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 9358 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 9359 report_fatal_error( 9360 "GHC calling convention requires the F and D instruction set extensions"); 9361 } 9362 9363 const Function &Func = MF.getFunction(); 9364 if (Func.hasFnAttribute("interrupt")) { 9365 if (!Func.arg_empty()) 9366 report_fatal_error( 9367 "Functions with the interrupt attribute cannot have arguments!"); 9368 9369 StringRef Kind = 9370 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9371 9372 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 9373 report_fatal_error( 9374 "Function interrupt attribute argument not supported!"); 9375 } 9376 9377 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9378 MVT XLenVT = Subtarget.getXLenVT(); 9379 unsigned XLenInBytes = Subtarget.getXLen() / 8; 9380 // Used with vargs to acumulate store chains. 9381 std::vector<SDValue> OutChains; 9382 9383 // Assign locations to all of the incoming arguments. 9384 SmallVector<CCValAssign, 16> ArgLocs; 9385 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9386 9387 if (CallConv == CallingConv::GHC) 9388 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 9389 else 9390 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 9391 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9392 : CC_RISCV); 9393 9394 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 9395 CCValAssign &VA = ArgLocs[i]; 9396 SDValue ArgValue; 9397 // Passing f64 on RV32D with a soft float ABI must be handled as a special 9398 // case. 9399 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 9400 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 9401 else if (VA.isRegLoc()) 9402 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 9403 else 9404 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 9405 9406 if (VA.getLocInfo() == CCValAssign::Indirect) { 9407 // If the original argument was split and passed by reference (e.g. i128 9408 // on RV32), we need to load all parts of it here (using the same 9409 // address). Vectors may be partly split to registers and partly to the 9410 // stack, in which case the base address is partly offset and subsequent 9411 // stores are relative to that. 9412 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 9413 MachinePointerInfo())); 9414 unsigned ArgIndex = Ins[i].OrigArgIndex; 9415 unsigned ArgPartOffset = Ins[i].PartOffset; 9416 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9417 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 9418 CCValAssign &PartVA = ArgLocs[i + 1]; 9419 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 9420 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9421 if (PartVA.getValVT().isScalableVector()) 9422 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9423 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 9424 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 9425 MachinePointerInfo())); 9426 ++i; 9427 } 9428 continue; 9429 } 9430 InVals.push_back(ArgValue); 9431 } 9432 9433 if (IsVarArg) { 9434 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 9435 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 9436 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 9437 MachineFrameInfo &MFI = MF.getFrameInfo(); 9438 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9439 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 9440 9441 // Offset of the first variable argument from stack pointer, and size of 9442 // the vararg save area. For now, the varargs save area is either zero or 9443 // large enough to hold a0-a7. 9444 int VaArgOffset, VarArgsSaveSize; 9445 9446 // If all registers are allocated, then all varargs must be passed on the 9447 // stack and we don't need to save any argregs. 9448 if (ArgRegs.size() == Idx) { 9449 VaArgOffset = CCInfo.getNextStackOffset(); 9450 VarArgsSaveSize = 0; 9451 } else { 9452 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 9453 VaArgOffset = -VarArgsSaveSize; 9454 } 9455 9456 // Record the frame index of the first variable argument 9457 // which is a value necessary to VASTART. 9458 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9459 RVFI->setVarArgsFrameIndex(FI); 9460 9461 // If saving an odd number of registers then create an extra stack slot to 9462 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 9463 // offsets to even-numbered registered remain 2*XLEN-aligned. 9464 if (Idx % 2) { 9465 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 9466 VarArgsSaveSize += XLenInBytes; 9467 } 9468 9469 // Copy the integer registers that may have been used for passing varargs 9470 // to the vararg save area. 9471 for (unsigned I = Idx; I < ArgRegs.size(); 9472 ++I, VaArgOffset += XLenInBytes) { 9473 const Register Reg = RegInfo.createVirtualRegister(RC); 9474 RegInfo.addLiveIn(ArgRegs[I], Reg); 9475 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 9476 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 9477 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9478 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 9479 MachinePointerInfo::getFixedStack(MF, FI)); 9480 cast<StoreSDNode>(Store.getNode()) 9481 ->getMemOperand() 9482 ->setValue((Value *)nullptr); 9483 OutChains.push_back(Store); 9484 } 9485 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 9486 } 9487 9488 // All stores are grouped in one node to allow the matching between 9489 // the size of Ins and InVals. This only happens for vararg functions. 9490 if (!OutChains.empty()) { 9491 OutChains.push_back(Chain); 9492 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 9493 } 9494 9495 return Chain; 9496 } 9497 9498 /// isEligibleForTailCallOptimization - Check whether the call is eligible 9499 /// for tail call optimization. 9500 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 9501 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 9502 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 9503 const SmallVector<CCValAssign, 16> &ArgLocs) const { 9504 9505 auto &Callee = CLI.Callee; 9506 auto CalleeCC = CLI.CallConv; 9507 auto &Outs = CLI.Outs; 9508 auto &Caller = MF.getFunction(); 9509 auto CallerCC = Caller.getCallingConv(); 9510 9511 // Exception-handling functions need a special set of instructions to 9512 // indicate a return to the hardware. Tail-calling another function would 9513 // probably break this. 9514 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 9515 // should be expanded as new function attributes are introduced. 9516 if (Caller.hasFnAttribute("interrupt")) 9517 return false; 9518 9519 // Do not tail call opt if the stack is used to pass parameters. 9520 if (CCInfo.getNextStackOffset() != 0) 9521 return false; 9522 9523 // Do not tail call opt if any parameters need to be passed indirectly. 9524 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 9525 // passed indirectly. So the address of the value will be passed in a 9526 // register, or if not available, then the address is put on the stack. In 9527 // order to pass indirectly, space on the stack often needs to be allocated 9528 // in order to store the value. In this case the CCInfo.getNextStackOffset() 9529 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 9530 // are passed CCValAssign::Indirect. 9531 for (auto &VA : ArgLocs) 9532 if (VA.getLocInfo() == CCValAssign::Indirect) 9533 return false; 9534 9535 // Do not tail call opt if either caller or callee uses struct return 9536 // semantics. 9537 auto IsCallerStructRet = Caller.hasStructRetAttr(); 9538 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 9539 if (IsCallerStructRet || IsCalleeStructRet) 9540 return false; 9541 9542 // Externally-defined functions with weak linkage should not be 9543 // tail-called. The behaviour of branch instructions in this situation (as 9544 // used for tail calls) is implementation-defined, so we cannot rely on the 9545 // linker replacing the tail call with a return. 9546 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 9547 const GlobalValue *GV = G->getGlobal(); 9548 if (GV->hasExternalWeakLinkage()) 9549 return false; 9550 } 9551 9552 // The callee has to preserve all registers the caller needs to preserve. 9553 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9554 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 9555 if (CalleeCC != CallerCC) { 9556 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 9557 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 9558 return false; 9559 } 9560 9561 // Byval parameters hand the function a pointer directly into the stack area 9562 // we want to reuse during a tail call. Working around this *is* possible 9563 // but less efficient and uglier in LowerCall. 9564 for (auto &Arg : Outs) 9565 if (Arg.Flags.isByVal()) 9566 return false; 9567 9568 return true; 9569 } 9570 9571 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 9572 return DAG.getDataLayout().getPrefTypeAlign( 9573 VT.getTypeForEVT(*DAG.getContext())); 9574 } 9575 9576 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 9577 // and output parameter nodes. 9578 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 9579 SmallVectorImpl<SDValue> &InVals) const { 9580 SelectionDAG &DAG = CLI.DAG; 9581 SDLoc &DL = CLI.DL; 9582 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 9583 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 9584 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 9585 SDValue Chain = CLI.Chain; 9586 SDValue Callee = CLI.Callee; 9587 bool &IsTailCall = CLI.IsTailCall; 9588 CallingConv::ID CallConv = CLI.CallConv; 9589 bool IsVarArg = CLI.IsVarArg; 9590 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9591 MVT XLenVT = Subtarget.getXLenVT(); 9592 9593 MachineFunction &MF = DAG.getMachineFunction(); 9594 9595 // Analyze the operands of the call, assigning locations to each operand. 9596 SmallVector<CCValAssign, 16> ArgLocs; 9597 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 9598 9599 if (CallConv == CallingConv::GHC) 9600 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 9601 else 9602 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 9603 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 9604 : CC_RISCV); 9605 9606 // Check if it's really possible to do a tail call. 9607 if (IsTailCall) 9608 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 9609 9610 if (IsTailCall) 9611 ++NumTailCalls; 9612 else if (CLI.CB && CLI.CB->isMustTailCall()) 9613 report_fatal_error("failed to perform tail call elimination on a call " 9614 "site marked musttail"); 9615 9616 // Get a count of how many bytes are to be pushed on the stack. 9617 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 9618 9619 // Create local copies for byval args 9620 SmallVector<SDValue, 8> ByValArgs; 9621 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9622 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9623 if (!Flags.isByVal()) 9624 continue; 9625 9626 SDValue Arg = OutVals[i]; 9627 unsigned Size = Flags.getByValSize(); 9628 Align Alignment = Flags.getNonZeroByValAlign(); 9629 9630 int FI = 9631 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 9632 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 9633 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 9634 9635 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 9636 /*IsVolatile=*/false, 9637 /*AlwaysInline=*/false, IsTailCall, 9638 MachinePointerInfo(), MachinePointerInfo()); 9639 ByValArgs.push_back(FIPtr); 9640 } 9641 9642 if (!IsTailCall) 9643 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 9644 9645 // Copy argument values to their designated locations. 9646 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 9647 SmallVector<SDValue, 8> MemOpChains; 9648 SDValue StackPtr; 9649 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 9650 CCValAssign &VA = ArgLocs[i]; 9651 SDValue ArgValue = OutVals[i]; 9652 ISD::ArgFlagsTy Flags = Outs[i].Flags; 9653 9654 // Handle passing f64 on RV32D with a soft float ABI as a special case. 9655 bool IsF64OnRV32DSoftABI = 9656 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 9657 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 9658 SDValue SplitF64 = DAG.getNode( 9659 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 9660 SDValue Lo = SplitF64.getValue(0); 9661 SDValue Hi = SplitF64.getValue(1); 9662 9663 Register RegLo = VA.getLocReg(); 9664 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 9665 9666 if (RegLo == RISCV::X17) { 9667 // Second half of f64 is passed on the stack. 9668 // Work out the address of the stack slot. 9669 if (!StackPtr.getNode()) 9670 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9671 // Emit the store. 9672 MemOpChains.push_back( 9673 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 9674 } else { 9675 // Second half of f64 is passed in another GPR. 9676 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9677 Register RegHigh = RegLo + 1; 9678 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 9679 } 9680 continue; 9681 } 9682 9683 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 9684 // as any other MemLoc. 9685 9686 // Promote the value if needed. 9687 // For now, only handle fully promoted and indirect arguments. 9688 if (VA.getLocInfo() == CCValAssign::Indirect) { 9689 // Store the argument in a stack slot and pass its address. 9690 Align StackAlign = 9691 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 9692 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 9693 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 9694 // If the original argument was split (e.g. i128), we need 9695 // to store the required parts of it here (and pass just one address). 9696 // Vectors may be partly split to registers and partly to the stack, in 9697 // which case the base address is partly offset and subsequent stores are 9698 // relative to that. 9699 unsigned ArgIndex = Outs[i].OrigArgIndex; 9700 unsigned ArgPartOffset = Outs[i].PartOffset; 9701 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 9702 // Calculate the total size to store. We don't have access to what we're 9703 // actually storing other than performing the loop and collecting the 9704 // info. 9705 SmallVector<std::pair<SDValue, SDValue>> Parts; 9706 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 9707 SDValue PartValue = OutVals[i + 1]; 9708 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 9709 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 9710 EVT PartVT = PartValue.getValueType(); 9711 if (PartVT.isScalableVector()) 9712 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 9713 StoredSize += PartVT.getStoreSize(); 9714 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 9715 Parts.push_back(std::make_pair(PartValue, Offset)); 9716 ++i; 9717 } 9718 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 9719 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 9720 MemOpChains.push_back( 9721 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 9722 MachinePointerInfo::getFixedStack(MF, FI))); 9723 for (const auto &Part : Parts) { 9724 SDValue PartValue = Part.first; 9725 SDValue PartOffset = Part.second; 9726 SDValue Address = 9727 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 9728 MemOpChains.push_back( 9729 DAG.getStore(Chain, DL, PartValue, Address, 9730 MachinePointerInfo::getFixedStack(MF, FI))); 9731 } 9732 ArgValue = SpillSlot; 9733 } else { 9734 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 9735 } 9736 9737 // Use local copy if it is a byval arg. 9738 if (Flags.isByVal()) 9739 ArgValue = ByValArgs[j++]; 9740 9741 if (VA.isRegLoc()) { 9742 // Queue up the argument copies and emit them at the end. 9743 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 9744 } else { 9745 assert(VA.isMemLoc() && "Argument not register or memory"); 9746 assert(!IsTailCall && "Tail call not allowed if stack is used " 9747 "for passing parameters"); 9748 9749 // Work out the address of the stack slot. 9750 if (!StackPtr.getNode()) 9751 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 9752 SDValue Address = 9753 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 9754 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 9755 9756 // Emit the store. 9757 MemOpChains.push_back( 9758 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 9759 } 9760 } 9761 9762 // Join the stores, which are independent of one another. 9763 if (!MemOpChains.empty()) 9764 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 9765 9766 SDValue Glue; 9767 9768 // Build a sequence of copy-to-reg nodes, chained and glued together. 9769 for (auto &Reg : RegsToPass) { 9770 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 9771 Glue = Chain.getValue(1); 9772 } 9773 9774 // Validate that none of the argument registers have been marked as 9775 // reserved, if so report an error. Do the same for the return address if this 9776 // is not a tailcall. 9777 validateCCReservedRegs(RegsToPass, MF); 9778 if (!IsTailCall && 9779 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 9780 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9781 MF.getFunction(), 9782 "Return address register required, but has been reserved."}); 9783 9784 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 9785 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 9786 // split it and then direct call can be matched by PseudoCALL. 9787 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 9788 const GlobalValue *GV = S->getGlobal(); 9789 9790 unsigned OpFlags = RISCVII::MO_CALL; 9791 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 9792 OpFlags = RISCVII::MO_PLT; 9793 9794 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 9795 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 9796 unsigned OpFlags = RISCVII::MO_CALL; 9797 9798 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 9799 nullptr)) 9800 OpFlags = RISCVII::MO_PLT; 9801 9802 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 9803 } 9804 9805 // The first call operand is the chain and the second is the target address. 9806 SmallVector<SDValue, 8> Ops; 9807 Ops.push_back(Chain); 9808 Ops.push_back(Callee); 9809 9810 // Add argument registers to the end of the list so that they are 9811 // known live into the call. 9812 for (auto &Reg : RegsToPass) 9813 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 9814 9815 if (!IsTailCall) { 9816 // Add a register mask operand representing the call-preserved registers. 9817 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9818 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 9819 assert(Mask && "Missing call preserved mask for calling convention"); 9820 Ops.push_back(DAG.getRegisterMask(Mask)); 9821 } 9822 9823 // Glue the call to the argument copies, if any. 9824 if (Glue.getNode()) 9825 Ops.push_back(Glue); 9826 9827 // Emit the call. 9828 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9829 9830 if (IsTailCall) { 9831 MF.getFrameInfo().setHasTailCall(); 9832 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 9833 } 9834 9835 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 9836 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 9837 Glue = Chain.getValue(1); 9838 9839 // Mark the end of the call, which is glued to the call itself. 9840 Chain = DAG.getCALLSEQ_END(Chain, 9841 DAG.getConstant(NumBytes, DL, PtrVT, true), 9842 DAG.getConstant(0, DL, PtrVT, true), 9843 Glue, DL); 9844 Glue = Chain.getValue(1); 9845 9846 // Assign locations to each value returned by this call. 9847 SmallVector<CCValAssign, 16> RVLocs; 9848 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 9849 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 9850 9851 // Copy all of the result registers out of their specified physreg. 9852 for (auto &VA : RVLocs) { 9853 // Copy the value out 9854 SDValue RetValue = 9855 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 9856 // Glue the RetValue to the end of the call sequence 9857 Chain = RetValue.getValue(1); 9858 Glue = RetValue.getValue(2); 9859 9860 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9861 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 9862 SDValue RetValue2 = 9863 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 9864 Chain = RetValue2.getValue(1); 9865 Glue = RetValue2.getValue(2); 9866 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 9867 RetValue2); 9868 } 9869 9870 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 9871 9872 InVals.push_back(RetValue); 9873 } 9874 9875 return Chain; 9876 } 9877 9878 bool RISCVTargetLowering::CanLowerReturn( 9879 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 9880 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 9881 SmallVector<CCValAssign, 16> RVLocs; 9882 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 9883 9884 Optional<unsigned> FirstMaskArgument; 9885 if (Subtarget.hasVInstructions()) 9886 FirstMaskArgument = preAssignMask(Outs); 9887 9888 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 9889 MVT VT = Outs[i].VT; 9890 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9891 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9892 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 9893 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 9894 *this, FirstMaskArgument)) 9895 return false; 9896 } 9897 return true; 9898 } 9899 9900 SDValue 9901 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 9902 bool IsVarArg, 9903 const SmallVectorImpl<ISD::OutputArg> &Outs, 9904 const SmallVectorImpl<SDValue> &OutVals, 9905 const SDLoc &DL, SelectionDAG &DAG) const { 9906 const MachineFunction &MF = DAG.getMachineFunction(); 9907 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 9908 9909 // Stores the assignment of the return value to a location. 9910 SmallVector<CCValAssign, 16> RVLocs; 9911 9912 // Info about the registers and stack slot. 9913 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 9914 *DAG.getContext()); 9915 9916 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 9917 nullptr, CC_RISCV); 9918 9919 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 9920 report_fatal_error("GHC functions return void only"); 9921 9922 SDValue Glue; 9923 SmallVector<SDValue, 4> RetOps(1, Chain); 9924 9925 // Copy the result values into the output registers. 9926 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 9927 SDValue Val = OutVals[i]; 9928 CCValAssign &VA = RVLocs[i]; 9929 assert(VA.isRegLoc() && "Can only return in registers!"); 9930 9931 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 9932 // Handle returning f64 on RV32D with a soft float ABI. 9933 assert(VA.isRegLoc() && "Expected return via registers"); 9934 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 9935 DAG.getVTList(MVT::i32, MVT::i32), Val); 9936 SDValue Lo = SplitF64.getValue(0); 9937 SDValue Hi = SplitF64.getValue(1); 9938 Register RegLo = VA.getLocReg(); 9939 assert(RegLo < RISCV::X31 && "Invalid register pair"); 9940 Register RegHi = RegLo + 1; 9941 9942 if (STI.isRegisterReservedByUser(RegLo) || 9943 STI.isRegisterReservedByUser(RegHi)) 9944 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9945 MF.getFunction(), 9946 "Return value register required, but has been reserved."}); 9947 9948 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 9949 Glue = Chain.getValue(1); 9950 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 9951 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 9952 Glue = Chain.getValue(1); 9953 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 9954 } else { 9955 // Handle a 'normal' return. 9956 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 9957 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 9958 9959 if (STI.isRegisterReservedByUser(VA.getLocReg())) 9960 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 9961 MF.getFunction(), 9962 "Return value register required, but has been reserved."}); 9963 9964 // Guarantee that all emitted copies are stuck together. 9965 Glue = Chain.getValue(1); 9966 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 9967 } 9968 } 9969 9970 RetOps[0] = Chain; // Update chain. 9971 9972 // Add the glue node if we have it. 9973 if (Glue.getNode()) { 9974 RetOps.push_back(Glue); 9975 } 9976 9977 unsigned RetOpc = RISCVISD::RET_FLAG; 9978 // Interrupt service routines use different return instructions. 9979 const Function &Func = DAG.getMachineFunction().getFunction(); 9980 if (Func.hasFnAttribute("interrupt")) { 9981 if (!Func.getReturnType()->isVoidTy()) 9982 report_fatal_error( 9983 "Functions with the interrupt attribute must have void return type!"); 9984 9985 MachineFunction &MF = DAG.getMachineFunction(); 9986 StringRef Kind = 9987 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 9988 9989 if (Kind == "user") 9990 RetOpc = RISCVISD::URET_FLAG; 9991 else if (Kind == "supervisor") 9992 RetOpc = RISCVISD::SRET_FLAG; 9993 else 9994 RetOpc = RISCVISD::MRET_FLAG; 9995 } 9996 9997 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 9998 } 9999 10000 void RISCVTargetLowering::validateCCReservedRegs( 10001 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10002 MachineFunction &MF) const { 10003 const Function &F = MF.getFunction(); 10004 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10005 10006 if (llvm::any_of(Regs, [&STI](auto Reg) { 10007 return STI.isRegisterReservedByUser(Reg.first); 10008 })) 10009 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10010 F, "Argument register required, but has been reserved."}); 10011 } 10012 10013 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10014 return CI->isTailCall(); 10015 } 10016 10017 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10018 #define NODE_NAME_CASE(NODE) \ 10019 case RISCVISD::NODE: \ 10020 return "RISCVISD::" #NODE; 10021 // clang-format off 10022 switch ((RISCVISD::NodeType)Opcode) { 10023 case RISCVISD::FIRST_NUMBER: 10024 break; 10025 NODE_NAME_CASE(RET_FLAG) 10026 NODE_NAME_CASE(URET_FLAG) 10027 NODE_NAME_CASE(SRET_FLAG) 10028 NODE_NAME_CASE(MRET_FLAG) 10029 NODE_NAME_CASE(CALL) 10030 NODE_NAME_CASE(SELECT_CC) 10031 NODE_NAME_CASE(BR_CC) 10032 NODE_NAME_CASE(BuildPairF64) 10033 NODE_NAME_CASE(SplitF64) 10034 NODE_NAME_CASE(TAIL) 10035 NODE_NAME_CASE(MULHSU) 10036 NODE_NAME_CASE(SLLW) 10037 NODE_NAME_CASE(SRAW) 10038 NODE_NAME_CASE(SRLW) 10039 NODE_NAME_CASE(DIVW) 10040 NODE_NAME_CASE(DIVUW) 10041 NODE_NAME_CASE(REMUW) 10042 NODE_NAME_CASE(ROLW) 10043 NODE_NAME_CASE(RORW) 10044 NODE_NAME_CASE(CLZW) 10045 NODE_NAME_CASE(CTZW) 10046 NODE_NAME_CASE(FSLW) 10047 NODE_NAME_CASE(FSRW) 10048 NODE_NAME_CASE(FSL) 10049 NODE_NAME_CASE(FSR) 10050 NODE_NAME_CASE(FMV_H_X) 10051 NODE_NAME_CASE(FMV_X_ANYEXTH) 10052 NODE_NAME_CASE(FMV_W_X_RV64) 10053 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10054 NODE_NAME_CASE(FCVT_X) 10055 NODE_NAME_CASE(FCVT_XU) 10056 NODE_NAME_CASE(FCVT_W_RV64) 10057 NODE_NAME_CASE(FCVT_WU_RV64) 10058 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10059 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10060 NODE_NAME_CASE(READ_CYCLE_WIDE) 10061 NODE_NAME_CASE(GREV) 10062 NODE_NAME_CASE(GREVW) 10063 NODE_NAME_CASE(GORC) 10064 NODE_NAME_CASE(GORCW) 10065 NODE_NAME_CASE(SHFL) 10066 NODE_NAME_CASE(SHFLW) 10067 NODE_NAME_CASE(UNSHFL) 10068 NODE_NAME_CASE(UNSHFLW) 10069 NODE_NAME_CASE(BFP) 10070 NODE_NAME_CASE(BFPW) 10071 NODE_NAME_CASE(BCOMPRESS) 10072 NODE_NAME_CASE(BCOMPRESSW) 10073 NODE_NAME_CASE(BDECOMPRESS) 10074 NODE_NAME_CASE(BDECOMPRESSW) 10075 NODE_NAME_CASE(VMV_V_X_VL) 10076 NODE_NAME_CASE(VFMV_V_F_VL) 10077 NODE_NAME_CASE(VMV_X_S) 10078 NODE_NAME_CASE(VMV_S_X_VL) 10079 NODE_NAME_CASE(VFMV_S_F_VL) 10080 NODE_NAME_CASE(SPLAT_VECTOR_I64) 10081 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10082 NODE_NAME_CASE(READ_VLENB) 10083 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10084 NODE_NAME_CASE(VSLIDEUP_VL) 10085 NODE_NAME_CASE(VSLIDE1UP_VL) 10086 NODE_NAME_CASE(VSLIDEDOWN_VL) 10087 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10088 NODE_NAME_CASE(VID_VL) 10089 NODE_NAME_CASE(VFNCVT_ROD_VL) 10090 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10091 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10092 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10093 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10094 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10095 NODE_NAME_CASE(VECREDUCE_AND_VL) 10096 NODE_NAME_CASE(VECREDUCE_OR_VL) 10097 NODE_NAME_CASE(VECREDUCE_XOR_VL) 10098 NODE_NAME_CASE(VECREDUCE_FADD_VL) 10099 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 10100 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 10101 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 10102 NODE_NAME_CASE(ADD_VL) 10103 NODE_NAME_CASE(AND_VL) 10104 NODE_NAME_CASE(MUL_VL) 10105 NODE_NAME_CASE(OR_VL) 10106 NODE_NAME_CASE(SDIV_VL) 10107 NODE_NAME_CASE(SHL_VL) 10108 NODE_NAME_CASE(SREM_VL) 10109 NODE_NAME_CASE(SRA_VL) 10110 NODE_NAME_CASE(SRL_VL) 10111 NODE_NAME_CASE(SUB_VL) 10112 NODE_NAME_CASE(UDIV_VL) 10113 NODE_NAME_CASE(UREM_VL) 10114 NODE_NAME_CASE(XOR_VL) 10115 NODE_NAME_CASE(SADDSAT_VL) 10116 NODE_NAME_CASE(UADDSAT_VL) 10117 NODE_NAME_CASE(SSUBSAT_VL) 10118 NODE_NAME_CASE(USUBSAT_VL) 10119 NODE_NAME_CASE(FADD_VL) 10120 NODE_NAME_CASE(FSUB_VL) 10121 NODE_NAME_CASE(FMUL_VL) 10122 NODE_NAME_CASE(FDIV_VL) 10123 NODE_NAME_CASE(FNEG_VL) 10124 NODE_NAME_CASE(FABS_VL) 10125 NODE_NAME_CASE(FSQRT_VL) 10126 NODE_NAME_CASE(FMA_VL) 10127 NODE_NAME_CASE(FCOPYSIGN_VL) 10128 NODE_NAME_CASE(SMIN_VL) 10129 NODE_NAME_CASE(SMAX_VL) 10130 NODE_NAME_CASE(UMIN_VL) 10131 NODE_NAME_CASE(UMAX_VL) 10132 NODE_NAME_CASE(FMINNUM_VL) 10133 NODE_NAME_CASE(FMAXNUM_VL) 10134 NODE_NAME_CASE(MULHS_VL) 10135 NODE_NAME_CASE(MULHU_VL) 10136 NODE_NAME_CASE(FP_TO_SINT_VL) 10137 NODE_NAME_CASE(FP_TO_UINT_VL) 10138 NODE_NAME_CASE(SINT_TO_FP_VL) 10139 NODE_NAME_CASE(UINT_TO_FP_VL) 10140 NODE_NAME_CASE(FP_EXTEND_VL) 10141 NODE_NAME_CASE(FP_ROUND_VL) 10142 NODE_NAME_CASE(VWMUL_VL) 10143 NODE_NAME_CASE(VWMULU_VL) 10144 NODE_NAME_CASE(VWMULSU_VL) 10145 NODE_NAME_CASE(VWADDU_VL) 10146 NODE_NAME_CASE(SETCC_VL) 10147 NODE_NAME_CASE(VSELECT_VL) 10148 NODE_NAME_CASE(VP_MERGE_VL) 10149 NODE_NAME_CASE(VMAND_VL) 10150 NODE_NAME_CASE(VMOR_VL) 10151 NODE_NAME_CASE(VMXOR_VL) 10152 NODE_NAME_CASE(VMCLR_VL) 10153 NODE_NAME_CASE(VMSET_VL) 10154 NODE_NAME_CASE(VRGATHER_VX_VL) 10155 NODE_NAME_CASE(VRGATHER_VV_VL) 10156 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 10157 NODE_NAME_CASE(VSEXT_VL) 10158 NODE_NAME_CASE(VZEXT_VL) 10159 NODE_NAME_CASE(VCPOP_VL) 10160 NODE_NAME_CASE(VLE_VL) 10161 NODE_NAME_CASE(VSE_VL) 10162 NODE_NAME_CASE(READ_CSR) 10163 NODE_NAME_CASE(WRITE_CSR) 10164 NODE_NAME_CASE(SWAP_CSR) 10165 } 10166 // clang-format on 10167 return nullptr; 10168 #undef NODE_NAME_CASE 10169 } 10170 10171 /// getConstraintType - Given a constraint letter, return the type of 10172 /// constraint it is for this target. 10173 RISCVTargetLowering::ConstraintType 10174 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 10175 if (Constraint.size() == 1) { 10176 switch (Constraint[0]) { 10177 default: 10178 break; 10179 case 'f': 10180 return C_RegisterClass; 10181 case 'I': 10182 case 'J': 10183 case 'K': 10184 return C_Immediate; 10185 case 'A': 10186 return C_Memory; 10187 case 'S': // A symbolic address 10188 return C_Other; 10189 } 10190 } else { 10191 if (Constraint == "vr" || Constraint == "vm") 10192 return C_RegisterClass; 10193 } 10194 return TargetLowering::getConstraintType(Constraint); 10195 } 10196 10197 std::pair<unsigned, const TargetRegisterClass *> 10198 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10199 StringRef Constraint, 10200 MVT VT) const { 10201 // First, see if this is a constraint that directly corresponds to a 10202 // RISCV register class. 10203 if (Constraint.size() == 1) { 10204 switch (Constraint[0]) { 10205 case 'r': 10206 // TODO: Support fixed vectors up to XLen for P extension? 10207 if (VT.isVector()) 10208 break; 10209 return std::make_pair(0U, &RISCV::GPRRegClass); 10210 case 'f': 10211 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 10212 return std::make_pair(0U, &RISCV::FPR16RegClass); 10213 if (Subtarget.hasStdExtF() && VT == MVT::f32) 10214 return std::make_pair(0U, &RISCV::FPR32RegClass); 10215 if (Subtarget.hasStdExtD() && VT == MVT::f64) 10216 return std::make_pair(0U, &RISCV::FPR64RegClass); 10217 break; 10218 default: 10219 break; 10220 } 10221 } else if (Constraint == "vr") { 10222 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 10223 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10224 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 10225 return std::make_pair(0U, RC); 10226 } 10227 } else if (Constraint == "vm") { 10228 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 10229 return std::make_pair(0U, &RISCV::VMV0RegClass); 10230 } 10231 10232 // Clang will correctly decode the usage of register name aliases into their 10233 // official names. However, other frontends like `rustc` do not. This allows 10234 // users of these frontends to use the ABI names for registers in LLVM-style 10235 // register constraints. 10236 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 10237 .Case("{zero}", RISCV::X0) 10238 .Case("{ra}", RISCV::X1) 10239 .Case("{sp}", RISCV::X2) 10240 .Case("{gp}", RISCV::X3) 10241 .Case("{tp}", RISCV::X4) 10242 .Case("{t0}", RISCV::X5) 10243 .Case("{t1}", RISCV::X6) 10244 .Case("{t2}", RISCV::X7) 10245 .Cases("{s0}", "{fp}", RISCV::X8) 10246 .Case("{s1}", RISCV::X9) 10247 .Case("{a0}", RISCV::X10) 10248 .Case("{a1}", RISCV::X11) 10249 .Case("{a2}", RISCV::X12) 10250 .Case("{a3}", RISCV::X13) 10251 .Case("{a4}", RISCV::X14) 10252 .Case("{a5}", RISCV::X15) 10253 .Case("{a6}", RISCV::X16) 10254 .Case("{a7}", RISCV::X17) 10255 .Case("{s2}", RISCV::X18) 10256 .Case("{s3}", RISCV::X19) 10257 .Case("{s4}", RISCV::X20) 10258 .Case("{s5}", RISCV::X21) 10259 .Case("{s6}", RISCV::X22) 10260 .Case("{s7}", RISCV::X23) 10261 .Case("{s8}", RISCV::X24) 10262 .Case("{s9}", RISCV::X25) 10263 .Case("{s10}", RISCV::X26) 10264 .Case("{s11}", RISCV::X27) 10265 .Case("{t3}", RISCV::X28) 10266 .Case("{t4}", RISCV::X29) 10267 .Case("{t5}", RISCV::X30) 10268 .Case("{t6}", RISCV::X31) 10269 .Default(RISCV::NoRegister); 10270 if (XRegFromAlias != RISCV::NoRegister) 10271 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 10272 10273 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 10274 // TableGen record rather than the AsmName to choose registers for InlineAsm 10275 // constraints, plus we want to match those names to the widest floating point 10276 // register type available, manually select floating point registers here. 10277 // 10278 // The second case is the ABI name of the register, so that frontends can also 10279 // use the ABI names in register constraint lists. 10280 if (Subtarget.hasStdExtF()) { 10281 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 10282 .Cases("{f0}", "{ft0}", RISCV::F0_F) 10283 .Cases("{f1}", "{ft1}", RISCV::F1_F) 10284 .Cases("{f2}", "{ft2}", RISCV::F2_F) 10285 .Cases("{f3}", "{ft3}", RISCV::F3_F) 10286 .Cases("{f4}", "{ft4}", RISCV::F4_F) 10287 .Cases("{f5}", "{ft5}", RISCV::F5_F) 10288 .Cases("{f6}", "{ft6}", RISCV::F6_F) 10289 .Cases("{f7}", "{ft7}", RISCV::F7_F) 10290 .Cases("{f8}", "{fs0}", RISCV::F8_F) 10291 .Cases("{f9}", "{fs1}", RISCV::F9_F) 10292 .Cases("{f10}", "{fa0}", RISCV::F10_F) 10293 .Cases("{f11}", "{fa1}", RISCV::F11_F) 10294 .Cases("{f12}", "{fa2}", RISCV::F12_F) 10295 .Cases("{f13}", "{fa3}", RISCV::F13_F) 10296 .Cases("{f14}", "{fa4}", RISCV::F14_F) 10297 .Cases("{f15}", "{fa5}", RISCV::F15_F) 10298 .Cases("{f16}", "{fa6}", RISCV::F16_F) 10299 .Cases("{f17}", "{fa7}", RISCV::F17_F) 10300 .Cases("{f18}", "{fs2}", RISCV::F18_F) 10301 .Cases("{f19}", "{fs3}", RISCV::F19_F) 10302 .Cases("{f20}", "{fs4}", RISCV::F20_F) 10303 .Cases("{f21}", "{fs5}", RISCV::F21_F) 10304 .Cases("{f22}", "{fs6}", RISCV::F22_F) 10305 .Cases("{f23}", "{fs7}", RISCV::F23_F) 10306 .Cases("{f24}", "{fs8}", RISCV::F24_F) 10307 .Cases("{f25}", "{fs9}", RISCV::F25_F) 10308 .Cases("{f26}", "{fs10}", RISCV::F26_F) 10309 .Cases("{f27}", "{fs11}", RISCV::F27_F) 10310 .Cases("{f28}", "{ft8}", RISCV::F28_F) 10311 .Cases("{f29}", "{ft9}", RISCV::F29_F) 10312 .Cases("{f30}", "{ft10}", RISCV::F30_F) 10313 .Cases("{f31}", "{ft11}", RISCV::F31_F) 10314 .Default(RISCV::NoRegister); 10315 if (FReg != RISCV::NoRegister) { 10316 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 10317 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 10318 unsigned RegNo = FReg - RISCV::F0_F; 10319 unsigned DReg = RISCV::F0_D + RegNo; 10320 return std::make_pair(DReg, &RISCV::FPR64RegClass); 10321 } 10322 if (VT == MVT::f32 || VT == MVT::Other) 10323 return std::make_pair(FReg, &RISCV::FPR32RegClass); 10324 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 10325 unsigned RegNo = FReg - RISCV::F0_F; 10326 unsigned HReg = RISCV::F0_H + RegNo; 10327 return std::make_pair(HReg, &RISCV::FPR16RegClass); 10328 } 10329 } 10330 } 10331 10332 if (Subtarget.hasVInstructions()) { 10333 Register VReg = StringSwitch<Register>(Constraint.lower()) 10334 .Case("{v0}", RISCV::V0) 10335 .Case("{v1}", RISCV::V1) 10336 .Case("{v2}", RISCV::V2) 10337 .Case("{v3}", RISCV::V3) 10338 .Case("{v4}", RISCV::V4) 10339 .Case("{v5}", RISCV::V5) 10340 .Case("{v6}", RISCV::V6) 10341 .Case("{v7}", RISCV::V7) 10342 .Case("{v8}", RISCV::V8) 10343 .Case("{v9}", RISCV::V9) 10344 .Case("{v10}", RISCV::V10) 10345 .Case("{v11}", RISCV::V11) 10346 .Case("{v12}", RISCV::V12) 10347 .Case("{v13}", RISCV::V13) 10348 .Case("{v14}", RISCV::V14) 10349 .Case("{v15}", RISCV::V15) 10350 .Case("{v16}", RISCV::V16) 10351 .Case("{v17}", RISCV::V17) 10352 .Case("{v18}", RISCV::V18) 10353 .Case("{v19}", RISCV::V19) 10354 .Case("{v20}", RISCV::V20) 10355 .Case("{v21}", RISCV::V21) 10356 .Case("{v22}", RISCV::V22) 10357 .Case("{v23}", RISCV::V23) 10358 .Case("{v24}", RISCV::V24) 10359 .Case("{v25}", RISCV::V25) 10360 .Case("{v26}", RISCV::V26) 10361 .Case("{v27}", RISCV::V27) 10362 .Case("{v28}", RISCV::V28) 10363 .Case("{v29}", RISCV::V29) 10364 .Case("{v30}", RISCV::V30) 10365 .Case("{v31}", RISCV::V31) 10366 .Default(RISCV::NoRegister); 10367 if (VReg != RISCV::NoRegister) { 10368 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 10369 return std::make_pair(VReg, &RISCV::VMRegClass); 10370 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 10371 return std::make_pair(VReg, &RISCV::VRRegClass); 10372 for (const auto *RC : 10373 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 10374 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 10375 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 10376 return std::make_pair(VReg, RC); 10377 } 10378 } 10379 } 10380 } 10381 10382 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10383 } 10384 10385 unsigned 10386 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 10387 // Currently only support length 1 constraints. 10388 if (ConstraintCode.size() == 1) { 10389 switch (ConstraintCode[0]) { 10390 case 'A': 10391 return InlineAsm::Constraint_A; 10392 default: 10393 break; 10394 } 10395 } 10396 10397 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 10398 } 10399 10400 void RISCVTargetLowering::LowerAsmOperandForConstraint( 10401 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 10402 SelectionDAG &DAG) const { 10403 // Currently only support length 1 constraints. 10404 if (Constraint.length() == 1) { 10405 switch (Constraint[0]) { 10406 case 'I': 10407 // Validate & create a 12-bit signed immediate operand. 10408 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10409 uint64_t CVal = C->getSExtValue(); 10410 if (isInt<12>(CVal)) 10411 Ops.push_back( 10412 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10413 } 10414 return; 10415 case 'J': 10416 // Validate & create an integer zero operand. 10417 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 10418 if (C->getZExtValue() == 0) 10419 Ops.push_back( 10420 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 10421 return; 10422 case 'K': 10423 // Validate & create a 5-bit unsigned immediate operand. 10424 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 10425 uint64_t CVal = C->getZExtValue(); 10426 if (isUInt<5>(CVal)) 10427 Ops.push_back( 10428 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 10429 } 10430 return; 10431 case 'S': 10432 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 10433 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 10434 GA->getValueType(0))); 10435 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 10436 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 10437 BA->getValueType(0))); 10438 } 10439 return; 10440 default: 10441 break; 10442 } 10443 } 10444 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10445 } 10446 10447 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 10448 Instruction *Inst, 10449 AtomicOrdering Ord) const { 10450 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 10451 return Builder.CreateFence(Ord); 10452 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 10453 return Builder.CreateFence(AtomicOrdering::Release); 10454 return nullptr; 10455 } 10456 10457 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 10458 Instruction *Inst, 10459 AtomicOrdering Ord) const { 10460 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 10461 return Builder.CreateFence(AtomicOrdering::Acquire); 10462 return nullptr; 10463 } 10464 10465 TargetLowering::AtomicExpansionKind 10466 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10467 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 10468 // point operations can't be used in an lr/sc sequence without breaking the 10469 // forward-progress guarantee. 10470 if (AI->isFloatingPointOperation()) 10471 return AtomicExpansionKind::CmpXChg; 10472 10473 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10474 if (Size == 8 || Size == 16) 10475 return AtomicExpansionKind::MaskedIntrinsic; 10476 return AtomicExpansionKind::None; 10477 } 10478 10479 static Intrinsic::ID 10480 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 10481 if (XLen == 32) { 10482 switch (BinOp) { 10483 default: 10484 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10485 case AtomicRMWInst::Xchg: 10486 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 10487 case AtomicRMWInst::Add: 10488 return Intrinsic::riscv_masked_atomicrmw_add_i32; 10489 case AtomicRMWInst::Sub: 10490 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 10491 case AtomicRMWInst::Nand: 10492 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 10493 case AtomicRMWInst::Max: 10494 return Intrinsic::riscv_masked_atomicrmw_max_i32; 10495 case AtomicRMWInst::Min: 10496 return Intrinsic::riscv_masked_atomicrmw_min_i32; 10497 case AtomicRMWInst::UMax: 10498 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 10499 case AtomicRMWInst::UMin: 10500 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 10501 } 10502 } 10503 10504 if (XLen == 64) { 10505 switch (BinOp) { 10506 default: 10507 llvm_unreachable("Unexpected AtomicRMW BinOp"); 10508 case AtomicRMWInst::Xchg: 10509 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 10510 case AtomicRMWInst::Add: 10511 return Intrinsic::riscv_masked_atomicrmw_add_i64; 10512 case AtomicRMWInst::Sub: 10513 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 10514 case AtomicRMWInst::Nand: 10515 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 10516 case AtomicRMWInst::Max: 10517 return Intrinsic::riscv_masked_atomicrmw_max_i64; 10518 case AtomicRMWInst::Min: 10519 return Intrinsic::riscv_masked_atomicrmw_min_i64; 10520 case AtomicRMWInst::UMax: 10521 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 10522 case AtomicRMWInst::UMin: 10523 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 10524 } 10525 } 10526 10527 llvm_unreachable("Unexpected XLen\n"); 10528 } 10529 10530 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 10531 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 10532 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 10533 unsigned XLen = Subtarget.getXLen(); 10534 Value *Ordering = 10535 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 10536 Type *Tys[] = {AlignedAddr->getType()}; 10537 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 10538 AI->getModule(), 10539 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 10540 10541 if (XLen == 64) { 10542 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 10543 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10544 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 10545 } 10546 10547 Value *Result; 10548 10549 // Must pass the shift amount needed to sign extend the loaded value prior 10550 // to performing a signed comparison for min/max. ShiftAmt is the number of 10551 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 10552 // is the number of bits to left+right shift the value in order to 10553 // sign-extend. 10554 if (AI->getOperation() == AtomicRMWInst::Min || 10555 AI->getOperation() == AtomicRMWInst::Max) { 10556 const DataLayout &DL = AI->getModule()->getDataLayout(); 10557 unsigned ValWidth = 10558 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 10559 Value *SextShamt = 10560 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 10561 Result = Builder.CreateCall(LrwOpScwLoop, 10562 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 10563 } else { 10564 Result = 10565 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 10566 } 10567 10568 if (XLen == 64) 10569 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10570 return Result; 10571 } 10572 10573 TargetLowering::AtomicExpansionKind 10574 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 10575 AtomicCmpXchgInst *CI) const { 10576 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 10577 if (Size == 8 || Size == 16) 10578 return AtomicExpansionKind::MaskedIntrinsic; 10579 return AtomicExpansionKind::None; 10580 } 10581 10582 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 10583 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 10584 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 10585 unsigned XLen = Subtarget.getXLen(); 10586 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 10587 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 10588 if (XLen == 64) { 10589 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 10590 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 10591 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 10592 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 10593 } 10594 Type *Tys[] = {AlignedAddr->getType()}; 10595 Function *MaskedCmpXchg = 10596 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 10597 Value *Result = Builder.CreateCall( 10598 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 10599 if (XLen == 64) 10600 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 10601 return Result; 10602 } 10603 10604 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 10605 return false; 10606 } 10607 10608 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 10609 EVT VT) const { 10610 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 10611 return false; 10612 10613 switch (FPVT.getSimpleVT().SimpleTy) { 10614 case MVT::f16: 10615 return Subtarget.hasStdExtZfh(); 10616 case MVT::f32: 10617 return Subtarget.hasStdExtF(); 10618 case MVT::f64: 10619 return Subtarget.hasStdExtD(); 10620 default: 10621 return false; 10622 } 10623 } 10624 10625 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 10626 // If we are using the small code model, we can reduce size of jump table 10627 // entry to 4 bytes. 10628 if (Subtarget.is64Bit() && !isPositionIndependent() && 10629 getTargetMachine().getCodeModel() == CodeModel::Small) { 10630 return MachineJumpTableInfo::EK_Custom32; 10631 } 10632 return TargetLowering::getJumpTableEncoding(); 10633 } 10634 10635 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 10636 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 10637 unsigned uid, MCContext &Ctx) const { 10638 assert(Subtarget.is64Bit() && !isPositionIndependent() && 10639 getTargetMachine().getCodeModel() == CodeModel::Small); 10640 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 10641 } 10642 10643 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 10644 EVT VT) const { 10645 VT = VT.getScalarType(); 10646 10647 if (!VT.isSimple()) 10648 return false; 10649 10650 switch (VT.getSimpleVT().SimpleTy) { 10651 case MVT::f16: 10652 return Subtarget.hasStdExtZfh(); 10653 case MVT::f32: 10654 return Subtarget.hasStdExtF(); 10655 case MVT::f64: 10656 return Subtarget.hasStdExtD(); 10657 default: 10658 break; 10659 } 10660 10661 return false; 10662 } 10663 10664 Register RISCVTargetLowering::getExceptionPointerRegister( 10665 const Constant *PersonalityFn) const { 10666 return RISCV::X10; 10667 } 10668 10669 Register RISCVTargetLowering::getExceptionSelectorRegister( 10670 const Constant *PersonalityFn) const { 10671 return RISCV::X11; 10672 } 10673 10674 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 10675 // Return false to suppress the unnecessary extensions if the LibCall 10676 // arguments or return value is f32 type for LP64 ABI. 10677 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 10678 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 10679 return false; 10680 10681 return true; 10682 } 10683 10684 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 10685 if (Subtarget.is64Bit() && Type == MVT::i32) 10686 return true; 10687 10688 return IsSigned; 10689 } 10690 10691 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 10692 SDValue C) const { 10693 // Check integral scalar types. 10694 if (VT.isScalarInteger()) { 10695 // Omit the optimization if the sub target has the M extension and the data 10696 // size exceeds XLen. 10697 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 10698 return false; 10699 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 10700 // Break the MUL to a SLLI and an ADD/SUB. 10701 const APInt &Imm = ConstNode->getAPIntValue(); 10702 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 10703 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 10704 return true; 10705 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 10706 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 10707 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 10708 (Imm - 8).isPowerOf2())) 10709 return true; 10710 // Omit the following optimization if the sub target has the M extension 10711 // and the data size >= XLen. 10712 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 10713 return false; 10714 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 10715 // a pair of LUI/ADDI. 10716 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 10717 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 10718 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 10719 (1 - ImmS).isPowerOf2()) 10720 return true; 10721 } 10722 } 10723 } 10724 10725 return false; 10726 } 10727 10728 bool RISCVTargetLowering::isMulAddWithConstProfitable( 10729 const SDValue &AddNode, const SDValue &ConstNode) const { 10730 // Let the DAGCombiner decide for vectors. 10731 EVT VT = AddNode.getValueType(); 10732 if (VT.isVector()) 10733 return true; 10734 10735 // Let the DAGCombiner decide for larger types. 10736 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 10737 return true; 10738 10739 // It is worse if c1 is simm12 while c1*c2 is not. 10740 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 10741 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 10742 const APInt &C1 = C1Node->getAPIntValue(); 10743 const APInt &C2 = C2Node->getAPIntValue(); 10744 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 10745 return false; 10746 10747 // Default to true and let the DAGCombiner decide. 10748 return true; 10749 } 10750 10751 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 10752 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 10753 bool *Fast) const { 10754 if (!VT.isVector()) 10755 return false; 10756 10757 EVT ElemVT = VT.getVectorElementType(); 10758 if (Alignment >= ElemVT.getStoreSize()) { 10759 if (Fast) 10760 *Fast = true; 10761 return true; 10762 } 10763 10764 return false; 10765 } 10766 10767 bool RISCVTargetLowering::splitValueIntoRegisterParts( 10768 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 10769 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 10770 bool IsABIRegCopy = CC.hasValue(); 10771 EVT ValueVT = Val.getValueType(); 10772 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10773 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 10774 // and cast to f32. 10775 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 10776 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 10777 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 10778 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 10779 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 10780 Parts[0] = Val; 10781 return true; 10782 } 10783 10784 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10785 LLVMContext &Context = *DAG.getContext(); 10786 EVT ValueEltVT = ValueVT.getVectorElementType(); 10787 EVT PartEltVT = PartVT.getVectorElementType(); 10788 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10789 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10790 if (PartVTBitSize % ValueVTBitSize == 0) { 10791 assert(PartVTBitSize >= ValueVTBitSize); 10792 // If the element types are different, bitcast to the same element type of 10793 // PartVT first. 10794 // Give an example here, we want copy a <vscale x 1 x i8> value to 10795 // <vscale x 4 x i16>. 10796 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 10797 // subvector, then we can bitcast to <vscale x 4 x i16>. 10798 if (ValueEltVT != PartEltVT) { 10799 if (PartVTBitSize > ValueVTBitSize) { 10800 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10801 assert(Count != 0 && "The number of element should not be zero."); 10802 EVT SameEltTypeVT = 10803 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10804 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 10805 DAG.getUNDEF(SameEltTypeVT), Val, 10806 DAG.getVectorIdxConstant(0, DL)); 10807 } 10808 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 10809 } else { 10810 Val = 10811 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 10812 Val, DAG.getVectorIdxConstant(0, DL)); 10813 } 10814 Parts[0] = Val; 10815 return true; 10816 } 10817 } 10818 return false; 10819 } 10820 10821 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 10822 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 10823 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 10824 bool IsABIRegCopy = CC.hasValue(); 10825 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 10826 SDValue Val = Parts[0]; 10827 10828 // Cast the f32 to i32, truncate to i16, and cast back to f16. 10829 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 10830 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 10831 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 10832 return Val; 10833 } 10834 10835 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 10836 LLVMContext &Context = *DAG.getContext(); 10837 SDValue Val = Parts[0]; 10838 EVT ValueEltVT = ValueVT.getVectorElementType(); 10839 EVT PartEltVT = PartVT.getVectorElementType(); 10840 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 10841 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 10842 if (PartVTBitSize % ValueVTBitSize == 0) { 10843 assert(PartVTBitSize >= ValueVTBitSize); 10844 EVT SameEltTypeVT = ValueVT; 10845 // If the element types are different, convert it to the same element type 10846 // of PartVT. 10847 // Give an example here, we want copy a <vscale x 1 x i8> value from 10848 // <vscale x 4 x i16>. 10849 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 10850 // then we can extract <vscale x 1 x i8>. 10851 if (ValueEltVT != PartEltVT) { 10852 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 10853 assert(Count != 0 && "The number of element should not be zero."); 10854 SameEltTypeVT = 10855 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 10856 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 10857 } 10858 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 10859 DAG.getVectorIdxConstant(0, DL)); 10860 return Val; 10861 } 10862 } 10863 return SDValue(); 10864 } 10865 10866 SDValue 10867 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 10868 SelectionDAG &DAG, 10869 SmallVectorImpl<SDNode *> &Created) const { 10870 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 10871 if (isIntDivCheap(N->getValueType(0), Attr)) 10872 return SDValue(N, 0); // Lower SDIV as SDIV 10873 10874 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 10875 "Unexpected divisor!"); 10876 10877 // Conditional move is needed, so do the transformation iff Zbt is enabled. 10878 if (!Subtarget.hasStdExtZbt()) 10879 return SDValue(); 10880 10881 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 10882 // Besides, more critical path instructions will be generated when dividing 10883 // by 2. So we keep using the original DAGs for these cases. 10884 unsigned Lg2 = Divisor.countTrailingZeros(); 10885 if (Lg2 == 1 || Lg2 >= 12) 10886 return SDValue(); 10887 10888 // fold (sdiv X, pow2) 10889 EVT VT = N->getValueType(0); 10890 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 10891 return SDValue(); 10892 10893 SDLoc DL(N); 10894 SDValue N0 = N->getOperand(0); 10895 SDValue Zero = DAG.getConstant(0, DL, VT); 10896 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 10897 10898 // Add (N0 < 0) ? Pow2 - 1 : 0; 10899 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 10900 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 10901 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 10902 10903 Created.push_back(Cmp.getNode()); 10904 Created.push_back(Add.getNode()); 10905 Created.push_back(Sel.getNode()); 10906 10907 // Divide by pow2. 10908 SDValue SRA = 10909 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 10910 10911 // If we're dividing by a positive value, we're done. Otherwise, we must 10912 // negate the result. 10913 if (Divisor.isNonNegative()) 10914 return SRA; 10915 10916 Created.push_back(SRA.getNode()); 10917 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 10918 } 10919 10920 #define GET_REGISTER_MATCHER 10921 #include "RISCVGenAsmMatcher.inc" 10922 10923 Register 10924 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 10925 const MachineFunction &MF) const { 10926 Register Reg = MatchRegisterAltName(RegName); 10927 if (Reg == RISCV::NoRegister) 10928 Reg = MatchRegisterName(RegName); 10929 if (Reg == RISCV::NoRegister) 10930 report_fatal_error( 10931 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 10932 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 10933 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 10934 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 10935 StringRef(RegName) + "\".")); 10936 return Reg; 10937 } 10938 10939 namespace llvm { 10940 namespace RISCVVIntrinsicsTable { 10941 10942 #define GET_RISCVVIntrinsicsTable_IMPL 10943 #include "RISCVGenSearchableTables.inc" 10944 10945 } // namespace RISCVVIntrinsicsTable 10946 10947 } // namespace llvm 10948