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/CodeGen/CallingConvLower.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 29 #include "llvm/CodeGen/ValueTypes.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/DiagnosticPrinter.h" 32 #include "llvm/IR/IntrinsicsRISCV.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/KnownBits.h" 36 #include "llvm/Support/MathExtras.h" 37 #include "llvm/Support/raw_ostream.h" 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "riscv-lower" 42 43 STATISTIC(NumTailCalls, "Number of tail calls"); 44 45 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 46 const RISCVSubtarget &STI) 47 : TargetLowering(TM), Subtarget(STI) { 48 49 if (Subtarget.isRV32E()) 50 report_fatal_error("Codegen not yet implemented for RV32E"); 51 52 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 53 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 54 55 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 56 !Subtarget.hasStdExtF()) { 57 errs() << "Hard-float 'f' ABI can't be used for a target that " 58 "doesn't support the F instruction set extension (ignoring " 59 "target-abi)\n"; 60 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 61 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 62 !Subtarget.hasStdExtD()) { 63 errs() << "Hard-float 'd' ABI can't be used for a target that " 64 "doesn't support the D instruction set extension (ignoring " 65 "target-abi)\n"; 66 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 67 } 68 69 switch (ABI) { 70 default: 71 report_fatal_error("Don't know how to lower this ABI"); 72 case RISCVABI::ABI_ILP32: 73 case RISCVABI::ABI_ILP32F: 74 case RISCVABI::ABI_ILP32D: 75 case RISCVABI::ABI_LP64: 76 case RISCVABI::ABI_LP64F: 77 case RISCVABI::ABI_LP64D: 78 break; 79 } 80 81 MVT XLenVT = Subtarget.getXLenVT(); 82 83 // Set up the register classes. 84 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 85 86 if (Subtarget.hasStdExtZfh()) 87 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 88 if (Subtarget.hasStdExtF()) 89 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 90 if (Subtarget.hasStdExtD()) 91 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 92 93 static const MVT::SimpleValueType BoolVecVTs[] = { 94 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 95 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 96 static const MVT::SimpleValueType IntVecVTs[] = { 97 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 98 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 99 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 100 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 101 MVT::nxv4i64, MVT::nxv8i64}; 102 static const MVT::SimpleValueType F16VecVTs[] = { 103 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 104 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 105 static const MVT::SimpleValueType F32VecVTs[] = { 106 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 107 static const MVT::SimpleValueType F64VecVTs[] = { 108 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 109 110 if (Subtarget.hasStdExtV()) { 111 auto addRegClassForRVV = [this](MVT VT) { 112 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 113 assert(Size <= 512 && isPowerOf2_32(Size)); 114 const TargetRegisterClass *RC; 115 if (Size <= 64) 116 RC = &RISCV::VRRegClass; 117 else if (Size == 128) 118 RC = &RISCV::VRM2RegClass; 119 else if (Size == 256) 120 RC = &RISCV::VRM4RegClass; 121 else 122 RC = &RISCV::VRM8RegClass; 123 124 addRegisterClass(VT, RC); 125 }; 126 127 for (MVT VT : BoolVecVTs) 128 addRegClassForRVV(VT); 129 for (MVT VT : IntVecVTs) 130 addRegClassForRVV(VT); 131 132 if (Subtarget.hasStdExtZfh()) 133 for (MVT VT : F16VecVTs) 134 addRegClassForRVV(VT); 135 136 if (Subtarget.hasStdExtF()) 137 for (MVT VT : F32VecVTs) 138 addRegClassForRVV(VT); 139 140 if (Subtarget.hasStdExtD()) 141 for (MVT VT : F64VecVTs) 142 addRegClassForRVV(VT); 143 144 if (Subtarget.useRVVForFixedLengthVectors()) { 145 auto addRegClassForFixedVectors = [this](MVT VT) { 146 unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT); 147 const TargetRegisterClass *RC; 148 if (LMul == 1 || VT.getVectorElementType() == MVT::i1) 149 RC = &RISCV::VRRegClass; 150 else if (LMul == 2) 151 RC = &RISCV::VRM2RegClass; 152 else if (LMul == 4) 153 RC = &RISCV::VRM4RegClass; 154 else if (LMul == 8) 155 RC = &RISCV::VRM8RegClass; 156 else 157 llvm_unreachable("Unexpected LMul!"); 158 159 addRegisterClass(VT, RC); 160 }; 161 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 162 if (useRVVForFixedLengthVectorVT(VT)) 163 addRegClassForFixedVectors(VT); 164 165 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 166 if (useRVVForFixedLengthVectorVT(VT)) 167 addRegClassForFixedVectors(VT); 168 } 169 } 170 171 // Compute derived properties from the register classes. 172 computeRegisterProperties(STI.getRegisterInfo()); 173 174 setStackPointerRegisterToSaveRestore(RISCV::X2); 175 176 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 177 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 178 179 // TODO: add all necessary setOperationAction calls. 180 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 181 182 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 183 setOperationAction(ISD::BR_CC, XLenVT, Expand); 184 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 185 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 186 187 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 188 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 189 190 setOperationAction(ISD::VASTART, MVT::Other, Custom); 191 setOperationAction(ISD::VAARG, MVT::Other, Expand); 192 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 193 setOperationAction(ISD::VAEND, MVT::Other, Expand); 194 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 196 if (!Subtarget.hasStdExtZbb()) { 197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 198 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 199 } 200 201 if (Subtarget.is64Bit()) { 202 setOperationAction(ISD::ADD, MVT::i32, Custom); 203 setOperationAction(ISD::SUB, MVT::i32, Custom); 204 setOperationAction(ISD::SHL, MVT::i32, Custom); 205 setOperationAction(ISD::SRA, MVT::i32, Custom); 206 setOperationAction(ISD::SRL, MVT::i32, Custom); 207 208 setOperationAction(ISD::UADDO, MVT::i32, Custom); 209 setOperationAction(ISD::USUBO, MVT::i32, Custom); 210 setOperationAction(ISD::UADDSAT, MVT::i32, Custom); 211 setOperationAction(ISD::USUBSAT, MVT::i32, Custom); 212 } 213 214 if (!Subtarget.hasStdExtM()) { 215 setOperationAction(ISD::MUL, XLenVT, Expand); 216 setOperationAction(ISD::MULHS, XLenVT, Expand); 217 setOperationAction(ISD::MULHU, XLenVT, Expand); 218 setOperationAction(ISD::SDIV, XLenVT, Expand); 219 setOperationAction(ISD::UDIV, XLenVT, Expand); 220 setOperationAction(ISD::SREM, XLenVT, Expand); 221 setOperationAction(ISD::UREM, XLenVT, Expand); 222 } 223 224 if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) { 225 setOperationAction(ISD::MUL, MVT::i32, Custom); 226 227 setOperationAction(ISD::SDIV, MVT::i8, Custom); 228 setOperationAction(ISD::UDIV, MVT::i8, Custom); 229 setOperationAction(ISD::UREM, MVT::i8, Custom); 230 setOperationAction(ISD::SDIV, MVT::i16, Custom); 231 setOperationAction(ISD::UDIV, MVT::i16, Custom); 232 setOperationAction(ISD::UREM, MVT::i16, Custom); 233 setOperationAction(ISD::SDIV, MVT::i32, Custom); 234 setOperationAction(ISD::UDIV, MVT::i32, Custom); 235 setOperationAction(ISD::UREM, MVT::i32, Custom); 236 } 237 238 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 239 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 240 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 241 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 242 243 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 244 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 245 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 246 247 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 248 if (Subtarget.is64Bit()) { 249 setOperationAction(ISD::ROTL, MVT::i32, Custom); 250 setOperationAction(ISD::ROTR, MVT::i32, Custom); 251 } 252 } else { 253 setOperationAction(ISD::ROTL, XLenVT, Expand); 254 setOperationAction(ISD::ROTR, XLenVT, Expand); 255 } 256 257 if (Subtarget.hasStdExtZbp()) { 258 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 259 // more combining. 260 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 261 setOperationAction(ISD::BSWAP, XLenVT, Custom); 262 263 if (Subtarget.is64Bit()) { 264 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 265 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 266 } 267 } else { 268 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 269 // pattern match it directly in isel. 270 setOperationAction(ISD::BSWAP, XLenVT, 271 Subtarget.hasStdExtZbb() ? Legal : Expand); 272 } 273 274 if (Subtarget.hasStdExtZbb()) { 275 setOperationAction(ISD::SMIN, XLenVT, Legal); 276 setOperationAction(ISD::SMAX, XLenVT, Legal); 277 setOperationAction(ISD::UMIN, XLenVT, Legal); 278 setOperationAction(ISD::UMAX, XLenVT, Legal); 279 } else { 280 setOperationAction(ISD::CTTZ, XLenVT, Expand); 281 setOperationAction(ISD::CTLZ, XLenVT, Expand); 282 setOperationAction(ISD::CTPOP, XLenVT, Expand); 283 } 284 285 if (Subtarget.hasStdExtZbt()) { 286 setOperationAction(ISD::FSHL, XLenVT, Custom); 287 setOperationAction(ISD::FSHR, XLenVT, Custom); 288 setOperationAction(ISD::SELECT, XLenVT, Legal); 289 290 if (Subtarget.is64Bit()) { 291 setOperationAction(ISD::FSHL, MVT::i32, Custom); 292 setOperationAction(ISD::FSHR, MVT::i32, Custom); 293 } 294 } else { 295 setOperationAction(ISD::SELECT, XLenVT, Custom); 296 } 297 298 ISD::CondCode FPCCToExpand[] = { 299 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 300 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 301 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 302 303 ISD::NodeType FPOpToExpand[] = { 304 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP, 305 ISD::FP_TO_FP16}; 306 307 if (Subtarget.hasStdExtZfh()) 308 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 309 310 if (Subtarget.hasStdExtZfh()) { 311 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 312 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 313 for (auto CC : FPCCToExpand) 314 setCondCodeAction(CC, MVT::f16, Expand); 315 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 316 setOperationAction(ISD::SELECT, MVT::f16, Custom); 317 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 318 for (auto Op : FPOpToExpand) 319 setOperationAction(Op, MVT::f16, Expand); 320 } 321 322 if (Subtarget.hasStdExtF()) { 323 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 324 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 325 for (auto CC : FPCCToExpand) 326 setCondCodeAction(CC, MVT::f32, Expand); 327 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 328 setOperationAction(ISD::SELECT, MVT::f32, Custom); 329 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 330 for (auto Op : FPOpToExpand) 331 setOperationAction(Op, MVT::f32, Expand); 332 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 333 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 334 } 335 336 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 337 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 338 339 if (Subtarget.hasStdExtD()) { 340 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 341 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 342 for (auto CC : FPCCToExpand) 343 setCondCodeAction(CC, MVT::f64, Expand); 344 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 345 setOperationAction(ISD::SELECT, MVT::f64, Custom); 346 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 347 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 348 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 349 for (auto Op : FPOpToExpand) 350 setOperationAction(Op, MVT::f64, Expand); 351 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 352 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 353 } 354 355 if (Subtarget.is64Bit()) { 356 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 357 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 358 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 359 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 360 } 361 362 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 363 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 364 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 365 setOperationAction(ISD::JumpTable, XLenVT, Custom); 366 367 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 368 369 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 370 // Unfortunately this can't be determined just from the ISA naming string. 371 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 372 Subtarget.is64Bit() ? Legal : Custom); 373 374 setOperationAction(ISD::TRAP, MVT::Other, Legal); 375 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 376 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 377 378 if (Subtarget.hasStdExtA()) { 379 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 380 setMinCmpXchgSizeInBits(32); 381 } else { 382 setMaxAtomicSizeInBitsSupported(0); 383 } 384 385 setBooleanContents(ZeroOrOneBooleanContent); 386 387 if (Subtarget.hasStdExtV()) { 388 setBooleanVectorContents(ZeroOrOneBooleanContent); 389 390 setOperationAction(ISD::VSCALE, XLenVT, Custom); 391 392 // RVV intrinsics may have illegal operands. 393 // We also need to custom legalize vmv.x.s. 394 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 395 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 396 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 397 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 398 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 399 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 400 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 401 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 402 403 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 404 405 if (!Subtarget.is64Bit()) { 406 // We must custom-lower certain vXi64 operations on RV32 due to the vector 407 // element type being illegal. 408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 409 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 410 411 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 412 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 413 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 414 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 415 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 416 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 417 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 418 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 419 } 420 421 for (MVT VT : BoolVecVTs) { 422 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 423 424 // Mask VTs are custom-expanded into a series of standard nodes 425 setOperationAction(ISD::TRUNCATE, VT, Custom); 426 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 427 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 428 429 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 430 } 431 432 for (MVT VT : IntVecVTs) { 433 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 434 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 435 436 setOperationAction(ISD::SMIN, VT, Legal); 437 setOperationAction(ISD::SMAX, VT, Legal); 438 setOperationAction(ISD::UMIN, VT, Legal); 439 setOperationAction(ISD::UMAX, VT, Legal); 440 441 setOperationAction(ISD::ROTL, VT, Expand); 442 setOperationAction(ISD::ROTR, VT, Expand); 443 444 // Custom-lower extensions and truncations from/to mask types. 445 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 446 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 447 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 448 449 // RVV has native int->float & float->int conversions where the 450 // element type sizes are within one power-of-two of each other. Any 451 // wider distances between type sizes have to be lowered as sequences 452 // which progressively narrow the gap in stages. 453 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 454 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 455 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 456 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 457 458 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 459 // nodes which truncate by one power of two at a time. 460 setOperationAction(ISD::TRUNCATE, VT, Custom); 461 462 // Custom-lower insert/extract operations to simplify patterns. 463 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 464 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 465 466 // Custom-lower reduction operations to set up the corresponding custom 467 // nodes' operands. 468 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 469 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 470 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 471 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 472 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 473 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 474 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 475 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 476 477 setOperationAction(ISD::MLOAD, VT, Custom); 478 setOperationAction(ISD::MSTORE, VT, Custom); 479 setOperationAction(ISD::MGATHER, VT, Custom); 480 setOperationAction(ISD::MSCATTER, VT, Custom); 481 482 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 483 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 484 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 485 486 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 487 } 488 489 // Expand various CCs to best match the RVV ISA, which natively supports UNE 490 // but no other unordered comparisons, and supports all ordered comparisons 491 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 492 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 493 // and we pattern-match those back to the "original", swapping operands once 494 // more. This way we catch both operations and both "vf" and "fv" forms with 495 // fewer patterns. 496 ISD::CondCode VFPCCToExpand[] = { 497 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 498 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 499 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 500 }; 501 502 // Sets common operation actions on RVV floating-point vector types. 503 const auto SetCommonVFPActions = [&](MVT VT) { 504 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 505 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 506 // sizes are within one power-of-two of each other. Therefore conversions 507 // between vXf16 and vXf64 must be lowered as sequences which convert via 508 // vXf32. 509 setOperationAction(ISD::FP_ROUND, VT, Custom); 510 setOperationAction(ISD::FP_EXTEND, VT, Custom); 511 // Custom-lower insert/extract operations to simplify patterns. 512 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 513 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 514 // Expand various condition codes (explained above). 515 for (auto CC : VFPCCToExpand) 516 setCondCodeAction(CC, VT, Expand); 517 518 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 519 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 520 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 521 522 setOperationAction(ISD::MLOAD, VT, Custom); 523 setOperationAction(ISD::MSTORE, VT, Custom); 524 setOperationAction(ISD::MGATHER, VT, Custom); 525 setOperationAction(ISD::MSCATTER, VT, Custom); 526 527 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 528 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 529 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 530 531 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 532 }; 533 534 if (Subtarget.hasStdExtZfh()) 535 for (MVT VT : F16VecVTs) 536 SetCommonVFPActions(VT); 537 538 if (Subtarget.hasStdExtF()) 539 for (MVT VT : F32VecVTs) 540 SetCommonVFPActions(VT); 541 542 if (Subtarget.hasStdExtD()) 543 for (MVT VT : F64VecVTs) 544 SetCommonVFPActions(VT); 545 546 if (Subtarget.useRVVForFixedLengthVectors()) { 547 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 548 if (!useRVVForFixedLengthVectorVT(VT)) 549 continue; 550 551 // By default everything must be expanded. 552 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 553 setOperationAction(Op, VT, Expand); 554 for (MVT OtherVT : MVT::fixedlen_vector_valuetypes()) 555 setTruncStoreAction(VT, OtherVT, Expand); 556 557 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 558 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 559 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 560 561 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 562 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 563 564 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 565 566 setOperationAction(ISD::LOAD, VT, Custom); 567 setOperationAction(ISD::STORE, VT, Custom); 568 569 setOperationAction(ISD::SETCC, VT, Custom); 570 571 setOperationAction(ISD::TRUNCATE, VT, Custom); 572 573 setOperationAction(ISD::BITCAST, VT, Custom); 574 575 // Operations below are different for between masks and other vectors. 576 if (VT.getVectorElementType() == MVT::i1) { 577 setOperationAction(ISD::AND, VT, Custom); 578 setOperationAction(ISD::OR, VT, Custom); 579 setOperationAction(ISD::XOR, VT, Custom); 580 continue; 581 } 582 583 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 584 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 585 586 setOperationAction(ISD::MLOAD, VT, Custom); 587 setOperationAction(ISD::MSTORE, VT, Custom); 588 setOperationAction(ISD::MGATHER, VT, Custom); 589 setOperationAction(ISD::MSCATTER, VT, Custom); 590 setOperationAction(ISD::ADD, VT, Custom); 591 setOperationAction(ISD::MUL, VT, Custom); 592 setOperationAction(ISD::SUB, VT, Custom); 593 setOperationAction(ISD::AND, VT, Custom); 594 setOperationAction(ISD::OR, VT, Custom); 595 setOperationAction(ISD::XOR, VT, Custom); 596 setOperationAction(ISD::SDIV, VT, Custom); 597 setOperationAction(ISD::SREM, VT, Custom); 598 setOperationAction(ISD::UDIV, VT, Custom); 599 setOperationAction(ISD::UREM, VT, Custom); 600 setOperationAction(ISD::SHL, VT, Custom); 601 setOperationAction(ISD::SRA, VT, Custom); 602 setOperationAction(ISD::SRL, VT, Custom); 603 604 setOperationAction(ISD::SMIN, VT, Custom); 605 setOperationAction(ISD::SMAX, VT, Custom); 606 setOperationAction(ISD::UMIN, VT, Custom); 607 setOperationAction(ISD::UMAX, VT, Custom); 608 setOperationAction(ISD::ABS, VT, Custom); 609 610 setOperationAction(ISD::MULHS, VT, Custom); 611 setOperationAction(ISD::MULHU, VT, Custom); 612 613 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 614 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 615 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 616 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 617 618 setOperationAction(ISD::VSELECT, VT, Custom); 619 620 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 621 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 622 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 623 624 // Custom-lower reduction operations to set up the corresponding custom 625 // nodes' operands. 626 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 627 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 628 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 629 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 630 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 631 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 632 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 633 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 634 } 635 636 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 637 if (!useRVVForFixedLengthVectorVT(VT)) 638 continue; 639 640 // By default everything must be expanded. 641 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 642 setOperationAction(Op, VT, Expand); 643 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 644 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 645 setTruncStoreAction(VT, OtherVT, Expand); 646 } 647 648 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 649 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 650 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 651 652 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 653 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 654 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 655 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 656 657 setOperationAction(ISD::LOAD, VT, Custom); 658 setOperationAction(ISD::STORE, VT, Custom); 659 setOperationAction(ISD::MLOAD, VT, Custom); 660 setOperationAction(ISD::MSTORE, VT, Custom); 661 setOperationAction(ISD::MGATHER, VT, Custom); 662 setOperationAction(ISD::MSCATTER, VT, Custom); 663 setOperationAction(ISD::FADD, VT, Custom); 664 setOperationAction(ISD::FSUB, VT, Custom); 665 setOperationAction(ISD::FMUL, VT, Custom); 666 setOperationAction(ISD::FDIV, VT, Custom); 667 setOperationAction(ISD::FNEG, VT, Custom); 668 setOperationAction(ISD::FABS, VT, Custom); 669 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 670 setOperationAction(ISD::FSQRT, VT, Custom); 671 setOperationAction(ISD::FMA, VT, Custom); 672 673 setOperationAction(ISD::FP_ROUND, VT, Custom); 674 setOperationAction(ISD::FP_EXTEND, VT, Custom); 675 676 for (auto CC : VFPCCToExpand) 677 setCondCodeAction(CC, VT, Expand); 678 679 setOperationAction(ISD::VSELECT, VT, Custom); 680 681 setOperationAction(ISD::BITCAST, VT, Custom); 682 683 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 684 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 685 } 686 } 687 } 688 689 // Function alignments. 690 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 691 setMinFunctionAlignment(FunctionAlignment); 692 setPrefFunctionAlignment(FunctionAlignment); 693 694 setMinimumJumpTableEntries(5); 695 696 // Jumps are expensive, compared to logic 697 setJumpIsExpensive(); 698 699 // We can use any register for comparisons 700 setHasMultipleConditionRegisters(); 701 702 if (Subtarget.hasStdExtZbp()) { 703 setTargetDAGCombine(ISD::OR); 704 } 705 if (Subtarget.hasStdExtV()) { 706 setTargetDAGCombine(ISD::FCOPYSIGN); 707 setTargetDAGCombine(ISD::MGATHER); 708 setTargetDAGCombine(ISD::MSCATTER); 709 } 710 } 711 712 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 713 LLVMContext &Context, 714 EVT VT) const { 715 if (!VT.isVector()) 716 return getPointerTy(DL); 717 if (Subtarget.hasStdExtV() && 718 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 719 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 720 return VT.changeVectorElementTypeToInteger(); 721 } 722 723 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 724 const CallInst &I, 725 MachineFunction &MF, 726 unsigned Intrinsic) const { 727 switch (Intrinsic) { 728 default: 729 return false; 730 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 731 case Intrinsic::riscv_masked_atomicrmw_add_i32: 732 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 733 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 734 case Intrinsic::riscv_masked_atomicrmw_max_i32: 735 case Intrinsic::riscv_masked_atomicrmw_min_i32: 736 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 737 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 738 case Intrinsic::riscv_masked_cmpxchg_i32: 739 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 740 Info.opc = ISD::INTRINSIC_W_CHAIN; 741 Info.memVT = MVT::getVT(PtrTy->getElementType()); 742 Info.ptrVal = I.getArgOperand(0); 743 Info.offset = 0; 744 Info.align = Align(4); 745 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 746 MachineMemOperand::MOVolatile; 747 return true; 748 } 749 } 750 751 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 752 const AddrMode &AM, Type *Ty, 753 unsigned AS, 754 Instruction *I) const { 755 // No global is ever allowed as a base. 756 if (AM.BaseGV) 757 return false; 758 759 // Require a 12-bit signed offset. 760 if (!isInt<12>(AM.BaseOffs)) 761 return false; 762 763 switch (AM.Scale) { 764 case 0: // "r+i" or just "i", depending on HasBaseReg. 765 break; 766 case 1: 767 if (!AM.HasBaseReg) // allow "r+i". 768 break; 769 return false; // disallow "r+r" or "r+r+i". 770 default: 771 return false; 772 } 773 774 return true; 775 } 776 777 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 778 return isInt<12>(Imm); 779 } 780 781 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 782 return isInt<12>(Imm); 783 } 784 785 // On RV32, 64-bit integers are split into their high and low parts and held 786 // in two different registers, so the trunc is free since the low register can 787 // just be used. 788 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 789 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 790 return false; 791 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 792 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 793 return (SrcBits == 64 && DestBits == 32); 794 } 795 796 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 797 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 798 !SrcVT.isInteger() || !DstVT.isInteger()) 799 return false; 800 unsigned SrcBits = SrcVT.getSizeInBits(); 801 unsigned DestBits = DstVT.getSizeInBits(); 802 return (SrcBits == 64 && DestBits == 32); 803 } 804 805 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 806 // Zexts are free if they can be combined with a load. 807 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 808 EVT MemVT = LD->getMemoryVT(); 809 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 810 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 811 (LD->getExtensionType() == ISD::NON_EXTLOAD || 812 LD->getExtensionType() == ISD::ZEXTLOAD)) 813 return true; 814 } 815 816 return TargetLowering::isZExtFree(Val, VT2); 817 } 818 819 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 820 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 821 } 822 823 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 824 return Subtarget.hasStdExtZbb(); 825 } 826 827 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 828 return Subtarget.hasStdExtZbb(); 829 } 830 831 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 832 bool ForCodeSize) const { 833 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 834 return false; 835 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 836 return false; 837 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 838 return false; 839 if (Imm.isNegZero()) 840 return false; 841 return Imm.isZero(); 842 } 843 844 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 845 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 846 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 847 (VT == MVT::f64 && Subtarget.hasStdExtD()); 848 } 849 850 // Changes the condition code and swaps operands if necessary, so the SetCC 851 // operation matches one of the comparisons supported directly by branches 852 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 853 // with 1/-1. 854 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 855 ISD::CondCode &CC, SelectionDAG &DAG) { 856 // Convert X > -1 to X >= 0. 857 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 858 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 859 CC = ISD::SETGE; 860 return; 861 } 862 // Convert X < 1 to 0 >= X. 863 if (CC == ISD::SETLT && isOneConstant(RHS)) { 864 RHS = LHS; 865 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 866 CC = ISD::SETGE; 867 return; 868 } 869 870 switch (CC) { 871 default: 872 break; 873 case ISD::SETGT: 874 case ISD::SETLE: 875 case ISD::SETUGT: 876 case ISD::SETULE: 877 CC = ISD::getSetCCSwappedOperands(CC); 878 std::swap(LHS, RHS); 879 break; 880 } 881 } 882 883 // Return the RISC-V branch opcode that matches the given DAG integer 884 // condition code. The CondCode must be one of those supported by the RISC-V 885 // ISA (see translateSetCCForBranch). 886 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) { 887 switch (CC) { 888 default: 889 llvm_unreachable("Unsupported CondCode"); 890 case ISD::SETEQ: 891 return RISCV::BEQ; 892 case ISD::SETNE: 893 return RISCV::BNE; 894 case ISD::SETLT: 895 return RISCV::BLT; 896 case ISD::SETGE: 897 return RISCV::BGE; 898 case ISD::SETULT: 899 return RISCV::BLTU; 900 case ISD::SETUGE: 901 return RISCV::BGEU; 902 } 903 } 904 905 RISCVVLMUL RISCVTargetLowering::getLMUL(MVT VT) { 906 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 907 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 908 if (VT.getVectorElementType() == MVT::i1) 909 KnownSize *= 8; 910 911 switch (KnownSize) { 912 default: 913 llvm_unreachable("Invalid LMUL."); 914 case 8: 915 return RISCVVLMUL::LMUL_F8; 916 case 16: 917 return RISCVVLMUL::LMUL_F4; 918 case 32: 919 return RISCVVLMUL::LMUL_F2; 920 case 64: 921 return RISCVVLMUL::LMUL_1; 922 case 128: 923 return RISCVVLMUL::LMUL_2; 924 case 256: 925 return RISCVVLMUL::LMUL_4; 926 case 512: 927 return RISCVVLMUL::LMUL_8; 928 } 929 } 930 931 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVVLMUL LMul) { 932 switch (LMul) { 933 default: 934 llvm_unreachable("Invalid LMUL."); 935 case RISCVVLMUL::LMUL_F8: 936 case RISCVVLMUL::LMUL_F4: 937 case RISCVVLMUL::LMUL_F2: 938 case RISCVVLMUL::LMUL_1: 939 return RISCV::VRRegClassID; 940 case RISCVVLMUL::LMUL_2: 941 return RISCV::VRM2RegClassID; 942 case RISCVVLMUL::LMUL_4: 943 return RISCV::VRM4RegClassID; 944 case RISCVVLMUL::LMUL_8: 945 return RISCV::VRM8RegClassID; 946 } 947 } 948 949 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 950 RISCVVLMUL LMUL = getLMUL(VT); 951 if (LMUL == RISCVVLMUL::LMUL_F8 || LMUL == RISCVVLMUL::LMUL_F4 || 952 LMUL == RISCVVLMUL::LMUL_F2 || LMUL == RISCVVLMUL::LMUL_1) { 953 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 954 "Unexpected subreg numbering"); 955 return RISCV::sub_vrm1_0 + Index; 956 } 957 if (LMUL == RISCVVLMUL::LMUL_2) { 958 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 959 "Unexpected subreg numbering"); 960 return RISCV::sub_vrm2_0 + Index; 961 } 962 if (LMUL == RISCVVLMUL::LMUL_4) { 963 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 964 "Unexpected subreg numbering"); 965 return RISCV::sub_vrm4_0 + Index; 966 } 967 llvm_unreachable("Invalid vector type."); 968 } 969 970 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 971 if (VT.getVectorElementType() == MVT::i1) 972 return RISCV::VRRegClassID; 973 return getRegClassIDForLMUL(getLMUL(VT)); 974 } 975 976 // Attempt to decompose a subvector insert/extract between VecVT and 977 // SubVecVT via subregister indices. Returns the subregister index that 978 // can perform the subvector insert/extract with the given element index, as 979 // well as the index corresponding to any leftover subvectors that must be 980 // further inserted/extracted within the register class for SubVecVT. 981 std::pair<unsigned, unsigned> 982 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 983 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 984 const RISCVRegisterInfo *TRI) { 985 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 986 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 987 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 988 "Register classes not ordered"); 989 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 990 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 991 // Try to compose a subregister index that takes us from the incoming 992 // LMUL>1 register class down to the outgoing one. At each step we half 993 // the LMUL: 994 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 995 // Note that this is not guaranteed to find a subregister index, such as 996 // when we are extracting from one VR type to another. 997 unsigned SubRegIdx = RISCV::NoSubRegister; 998 for (const unsigned RCID : 999 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1000 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1001 VecVT = VecVT.getHalfNumVectorElementsVT(); 1002 bool IsHi = 1003 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1004 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1005 getSubregIndexByMVT(VecVT, IsHi)); 1006 if (IsHi) 1007 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1008 } 1009 return {SubRegIdx, InsertExtractIdx}; 1010 } 1011 1012 // Return the largest legal scalable vector type that matches VT's element type. 1013 MVT RISCVTargetLowering::getContainerForFixedLengthVector( 1014 const TargetLowering &TLI, MVT VT, const RISCVSubtarget &Subtarget) { 1015 assert(VT.isFixedLengthVector() && TLI.isTypeLegal(VT) && 1016 "Expected legal fixed length vector!"); 1017 1018 unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT); 1019 assert(LMul <= 8 && isPowerOf2_32(LMul) && "Unexpected LMUL!"); 1020 1021 MVT EltVT = VT.getVectorElementType(); 1022 switch (EltVT.SimpleTy) { 1023 default: 1024 llvm_unreachable("unexpected element type for RVV container"); 1025 case MVT::i1: { 1026 // Masks are calculated assuming 8-bit elements since that's when we need 1027 // the most elements. 1028 unsigned EltsPerBlock = RISCV::RVVBitsPerBlock / 8; 1029 return MVT::getScalableVectorVT(MVT::i1, LMul * EltsPerBlock); 1030 } 1031 case MVT::i8: 1032 case MVT::i16: 1033 case MVT::i32: 1034 case MVT::i64: 1035 case MVT::f16: 1036 case MVT::f32: 1037 case MVT::f64: { 1038 unsigned EltsPerBlock = RISCV::RVVBitsPerBlock / EltVT.getSizeInBits(); 1039 return MVT::getScalableVectorVT(EltVT, LMul * EltsPerBlock); 1040 } 1041 } 1042 } 1043 1044 MVT RISCVTargetLowering::getContainerForFixedLengthVector( 1045 SelectionDAG &DAG, MVT VT, const RISCVSubtarget &Subtarget) { 1046 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1047 Subtarget); 1048 } 1049 1050 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1051 return getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1052 } 1053 1054 // Grow V to consume an entire RVV register. 1055 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1056 const RISCVSubtarget &Subtarget) { 1057 assert(VT.isScalableVector() && 1058 "Expected to convert into a scalable vector!"); 1059 assert(V.getValueType().isFixedLengthVector() && 1060 "Expected a fixed length vector operand!"); 1061 SDLoc DL(V); 1062 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1063 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1064 } 1065 1066 // Shrink V so it's just big enough to maintain a VT's worth of data. 1067 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1068 const RISCVSubtarget &Subtarget) { 1069 assert(VT.isFixedLengthVector() && 1070 "Expected to convert into a fixed length vector!"); 1071 assert(V.getValueType().isScalableVector() && 1072 "Expected a scalable vector operand!"); 1073 SDLoc DL(V); 1074 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1075 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1076 } 1077 1078 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1079 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1080 // the vector type that it is contained in. 1081 static std::pair<SDValue, SDValue> 1082 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1083 const RISCVSubtarget &Subtarget) { 1084 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1085 MVT XLenVT = Subtarget.getXLenVT(); 1086 SDValue VL = VecVT.isFixedLengthVector() 1087 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1088 : DAG.getRegister(RISCV::X0, XLenVT); 1089 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 1090 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1091 return {Mask, VL}; 1092 } 1093 1094 // As above but assuming the given type is a scalable vector type. 1095 static std::pair<SDValue, SDValue> 1096 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1097 const RISCVSubtarget &Subtarget) { 1098 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1099 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1100 } 1101 1102 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1103 // of either is (currently) supported. This can get us into an infinite loop 1104 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1105 // as a ..., etc. 1106 // Until either (or both) of these can reliably lower any node, reporting that 1107 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1108 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1109 // which is not desirable. 1110 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1111 EVT VT, unsigned DefinedValues) const { 1112 return false; 1113 } 1114 1115 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 1116 // Only splats are currently supported. 1117 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 1118 return true; 1119 1120 return false; 1121 } 1122 1123 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1124 const RISCVSubtarget &Subtarget) { 1125 MVT VT = Op.getSimpleValueType(); 1126 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1127 1128 MVT ContainerVT = 1129 RISCVTargetLowering::getContainerForFixedLengthVector(DAG, VT, Subtarget); 1130 1131 SDLoc DL(Op); 1132 SDValue Mask, VL; 1133 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1134 1135 unsigned NumElts = Op.getNumOperands(); 1136 1137 if (VT.getVectorElementType() == MVT::i1) { 1138 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1139 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1140 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1141 } 1142 1143 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1144 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1145 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1146 } 1147 1148 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1149 // scalar integer chunks whose bit-width depends on the number of mask 1150 // bits and XLEN. 1151 // First, determine the most appropriate scalar integer type to use. This 1152 // is at most XLenVT, but may be shrunk to a smaller vector element type 1153 // according to the size of the final vector - use i8 chunks rather than 1154 // XLenVT if we're producing a v8i1. This results in more consistent 1155 // codegen across RV32 and RV64. 1156 // If we have to use more than one INSERT_VECTOR_ELT then this optimization 1157 // is likely to increase code size; avoid peforming it in such a case. 1158 unsigned NumViaIntegerBits = 1159 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1160 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 1161 (!DAG.shouldOptForSize() || NumElts <= NumViaIntegerBits)) { 1162 // Now we can create our integer vector type. Note that it may be larger 1163 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1164 MVT IntegerViaVecVT = 1165 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1166 divideCeil(NumElts, NumViaIntegerBits)); 1167 1168 uint64_t Bits = 0; 1169 unsigned BitPos = 0, IntegerEltIdx = 0; 1170 MVT XLenVT = Subtarget.getXLenVT(); 1171 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1172 1173 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1174 // Once we accumulate enough bits to fill our scalar type, insert into 1175 // our vector and clear our accumulated data. 1176 if (I != 0 && I % NumViaIntegerBits == 0) { 1177 if (NumViaIntegerBits <= 32) 1178 Bits = SignExtend64(Bits, 32); 1179 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1180 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1181 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1182 Bits = 0; 1183 BitPos = 0; 1184 IntegerEltIdx++; 1185 } 1186 SDValue V = Op.getOperand(I); 1187 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1188 Bits |= ((uint64_t)BitValue << BitPos); 1189 } 1190 1191 // Insert the (remaining) scalar value into position in our integer 1192 // vector type. 1193 if (NumViaIntegerBits <= 32) 1194 Bits = SignExtend64(Bits, 32); 1195 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1196 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1197 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1198 1199 if (NumElts < NumViaIntegerBits) { 1200 // If we're producing a smaller vector than our minimum legal integer 1201 // type, bitcast to the equivalent (known-legal) mask type, and extract 1202 // our final mask. 1203 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1204 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1205 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1206 DAG.getConstant(0, DL, XLenVT)); 1207 } else { 1208 // Else we must have produced an integer type with the same size as the 1209 // mask type; bitcast for the final result. 1210 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1211 Vec = DAG.getBitcast(VT, Vec); 1212 } 1213 1214 return Vec; 1215 } 1216 1217 return SDValue(); 1218 } 1219 1220 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 1221 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 1222 : RISCVISD::VMV_V_X_VL; 1223 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 1224 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 1225 } 1226 1227 // Try and match an index sequence, which we can lower directly to the vid 1228 // instruction. An all-undef vector is matched by getSplatValue, above. 1229 if (VT.isInteger()) { 1230 bool IsVID = true; 1231 for (unsigned I = 0; I < NumElts && IsVID; I++) 1232 IsVID &= Op.getOperand(I).isUndef() || 1233 (isa<ConstantSDNode>(Op.getOperand(I)) && 1234 Op.getConstantOperandVal(I) == I); 1235 1236 if (IsVID) { 1237 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 1238 return convertFromScalableVector(VT, VID, DAG, Subtarget); 1239 } 1240 } 1241 1242 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 1243 // which constitute a large proportion of the elements. In such cases we can 1244 // splat a vector with the dominant element and make up the shortfall with 1245 // INSERT_VECTOR_ELTs. 1246 // Note that this includes vectors of 2 elements by association. The 1247 // upper-most element is the "dominant" one, allowing us to use a splat to 1248 // "insert" the upper element, and an insert of the lower element at position 1249 // 0, which improves codegen. 1250 SDValue DominantValue; 1251 unsigned MostCommonCount = 0; 1252 DenseMap<SDValue, unsigned> ValueCounts; 1253 unsigned NumUndefElts = 1254 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 1255 1256 for (SDValue V : Op->op_values()) { 1257 if (V.isUndef()) 1258 continue; 1259 1260 ValueCounts.insert(std::make_pair(V, 0)); 1261 unsigned &Count = ValueCounts[V]; 1262 1263 // Is this value dominant? In case of a tie, prefer the highest element as 1264 // it's cheaper to insert near the beginning of a vector than it is at the 1265 // end. 1266 if (++Count >= MostCommonCount) { 1267 DominantValue = V; 1268 MostCommonCount = Count; 1269 } 1270 } 1271 1272 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 1273 MVT XLenVT = Subtarget.getXLenVT(); 1274 unsigned NumDefElts = NumElts - NumUndefElts; 1275 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 1276 1277 // Don't perform this optimization when optimizing for size, since 1278 // materializing elements and inserting them tends to cause code bloat. 1279 if (!DAG.shouldOptForSize() && 1280 ((MostCommonCount > DominantValueCountThreshold) || 1281 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 1282 // Start by splatting the most common element. 1283 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 1284 1285 DenseSet<SDValue> Processed{DominantValue}; 1286 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 1287 for (const auto &OpIdx : enumerate(Op->ops())) { 1288 const SDValue &V = OpIdx.value(); 1289 if (V.isUndef() || !Processed.insert(V).second) 1290 continue; 1291 if (ValueCounts[V] == 1) { 1292 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 1293 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 1294 } else { 1295 // Blend in all instances of this value using a VSELECT, using a 1296 // mask where each bit signals whether that element is the one 1297 // we're after. 1298 SmallVector<SDValue> Ops; 1299 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 1300 return DAG.getConstant(V == V1, DL, XLenVT); 1301 }); 1302 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 1303 DAG.getBuildVector(SelMaskTy, DL, Ops), 1304 DAG.getSplatBuildVector(VT, DL, V), Vec); 1305 } 1306 } 1307 1308 return Vec; 1309 } 1310 1311 return SDValue(); 1312 } 1313 1314 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 1315 const RISCVSubtarget &Subtarget) { 1316 SDValue V1 = Op.getOperand(0); 1317 SDLoc DL(Op); 1318 MVT VT = Op.getSimpleValueType(); 1319 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 1320 1321 if (SVN->isSplat()) { 1322 int Lane = SVN->getSplatIndex(); 1323 if (Lane >= 0) { 1324 MVT ContainerVT = RISCVTargetLowering::getContainerForFixedLengthVector( 1325 DAG, VT, Subtarget); 1326 1327 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 1328 assert(Lane < (int)VT.getVectorNumElements() && "Unexpected lane!"); 1329 1330 SDValue Mask, VL; 1331 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1332 MVT XLenVT = Subtarget.getXLenVT(); 1333 SDValue Gather = 1334 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 1335 DAG.getConstant(Lane, DL, XLenVT), Mask, VL); 1336 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1337 } 1338 } 1339 1340 return SDValue(); 1341 } 1342 1343 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 1344 SDLoc DL, SelectionDAG &DAG, 1345 const RISCVSubtarget &Subtarget) { 1346 if (VT.isScalableVector()) 1347 return DAG.getFPExtendOrRound(Op, DL, VT); 1348 assert(VT.isFixedLengthVector() && 1349 "Unexpected value type for RVV FP extend/round lowering"); 1350 SDValue Mask, VL; 1351 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1352 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 1353 ? RISCVISD::FP_EXTEND_VL 1354 : RISCVISD::FP_ROUND_VL; 1355 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 1356 } 1357 1358 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 1359 SelectionDAG &DAG) const { 1360 switch (Op.getOpcode()) { 1361 default: 1362 report_fatal_error("unimplemented operand"); 1363 case ISD::GlobalAddress: 1364 return lowerGlobalAddress(Op, DAG); 1365 case ISD::BlockAddress: 1366 return lowerBlockAddress(Op, DAG); 1367 case ISD::ConstantPool: 1368 return lowerConstantPool(Op, DAG); 1369 case ISD::JumpTable: 1370 return lowerJumpTable(Op, DAG); 1371 case ISD::GlobalTLSAddress: 1372 return lowerGlobalTLSAddress(Op, DAG); 1373 case ISD::SELECT: 1374 return lowerSELECT(Op, DAG); 1375 case ISD::BRCOND: 1376 return lowerBRCOND(Op, DAG); 1377 case ISD::VASTART: 1378 return lowerVASTART(Op, DAG); 1379 case ISD::FRAMEADDR: 1380 return lowerFRAMEADDR(Op, DAG); 1381 case ISD::RETURNADDR: 1382 return lowerRETURNADDR(Op, DAG); 1383 case ISD::SHL_PARTS: 1384 return lowerShiftLeftParts(Op, DAG); 1385 case ISD::SRA_PARTS: 1386 return lowerShiftRightParts(Op, DAG, true); 1387 case ISD::SRL_PARTS: 1388 return lowerShiftRightParts(Op, DAG, false); 1389 case ISD::BITCAST: { 1390 SDValue Op0 = Op.getOperand(0); 1391 // We can handle fixed length vector bitcasts with a simple replacement 1392 // in isel. 1393 if (Op.getValueType().isFixedLengthVector()) { 1394 if (Op0.getValueType().isFixedLengthVector()) 1395 return Op; 1396 return SDValue(); 1397 } 1398 assert(((Subtarget.is64Bit() && Subtarget.hasStdExtF()) || 1399 Subtarget.hasStdExtZfh()) && 1400 "Unexpected custom legalisation"); 1401 SDLoc DL(Op); 1402 if (Op.getValueType() == MVT::f16 && Subtarget.hasStdExtZfh()) { 1403 if (Op0.getValueType() != MVT::i16) 1404 return SDValue(); 1405 SDValue NewOp0 = 1406 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), Op0); 1407 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 1408 return FPConv; 1409 } else if (Op.getValueType() == MVT::f32 && Subtarget.is64Bit() && 1410 Subtarget.hasStdExtF()) { 1411 if (Op0.getValueType() != MVT::i32) 1412 return SDValue(); 1413 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 1414 SDValue FPConv = 1415 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 1416 return FPConv; 1417 } 1418 return SDValue(); 1419 } 1420 case ISD::INTRINSIC_WO_CHAIN: 1421 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 1422 case ISD::INTRINSIC_W_CHAIN: 1423 return LowerINTRINSIC_W_CHAIN(Op, DAG); 1424 case ISD::BSWAP: 1425 case ISD::BITREVERSE: { 1426 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 1427 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 1428 MVT VT = Op.getSimpleValueType(); 1429 SDLoc DL(Op); 1430 // Start with the maximum immediate value which is the bitwidth - 1. 1431 unsigned Imm = VT.getSizeInBits() - 1; 1432 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 1433 if (Op.getOpcode() == ISD::BSWAP) 1434 Imm &= ~0x7U; 1435 return DAG.getNode(RISCVISD::GREVI, DL, VT, Op.getOperand(0), 1436 DAG.getTargetConstant(Imm, DL, Subtarget.getXLenVT())); 1437 } 1438 case ISD::FSHL: 1439 case ISD::FSHR: { 1440 MVT VT = Op.getSimpleValueType(); 1441 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 1442 SDLoc DL(Op); 1443 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 1444 // use log(XLen) bits. Mask the shift amount accordingly. 1445 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 1446 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 1447 DAG.getConstant(ShAmtWidth, DL, VT)); 1448 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 1449 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 1450 } 1451 case ISD::TRUNCATE: { 1452 SDLoc DL(Op); 1453 MVT VT = Op.getSimpleValueType(); 1454 // Only custom-lower vector truncates 1455 if (!VT.isVector()) 1456 return Op; 1457 1458 // Truncates to mask types are handled differently 1459 if (VT.getVectorElementType() == MVT::i1) 1460 return lowerVectorMaskTrunc(Op, DAG); 1461 1462 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 1463 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 1464 // truncate by one power of two at a time. 1465 MVT DstEltVT = VT.getVectorElementType(); 1466 1467 SDValue Src = Op.getOperand(0); 1468 MVT SrcVT = Src.getSimpleValueType(); 1469 MVT SrcEltVT = SrcVT.getVectorElementType(); 1470 1471 assert(DstEltVT.bitsLT(SrcEltVT) && 1472 isPowerOf2_64(DstEltVT.getSizeInBits()) && 1473 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 1474 "Unexpected vector truncate lowering"); 1475 1476 MVT ContainerVT = SrcVT; 1477 if (SrcVT.isFixedLengthVector()) { 1478 ContainerVT = getContainerForFixedLengthVector(SrcVT); 1479 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 1480 } 1481 1482 SDValue Result = Src; 1483 SDValue Mask, VL; 1484 std::tie(Mask, VL) = 1485 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 1486 LLVMContext &Context = *DAG.getContext(); 1487 const ElementCount Count = ContainerVT.getVectorElementCount(); 1488 do { 1489 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 1490 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 1491 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 1492 Mask, VL); 1493 } while (SrcEltVT != DstEltVT); 1494 1495 if (SrcVT.isFixedLengthVector()) 1496 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 1497 1498 return Result; 1499 } 1500 case ISD::ANY_EXTEND: 1501 case ISD::ZERO_EXTEND: 1502 if (Op.getOperand(0).getValueType().isVector() && 1503 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 1504 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 1505 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 1506 case ISD::SIGN_EXTEND: 1507 if (Op.getOperand(0).getValueType().isVector() && 1508 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 1509 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 1510 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 1511 case ISD::SPLAT_VECTOR_PARTS: 1512 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 1513 case ISD::INSERT_VECTOR_ELT: 1514 return lowerINSERT_VECTOR_ELT(Op, DAG); 1515 case ISD::EXTRACT_VECTOR_ELT: 1516 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 1517 case ISD::VSCALE: { 1518 MVT VT = Op.getSimpleValueType(); 1519 SDLoc DL(Op); 1520 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 1521 // We define our scalable vector types for lmul=1 to use a 64 bit known 1522 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 1523 // vscale as VLENB / 8. 1524 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 1525 DAG.getConstant(3, DL, VT)); 1526 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 1527 } 1528 case ISD::FP_EXTEND: { 1529 // RVV can only do fp_extend to types double the size as the source. We 1530 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 1531 // via f32. 1532 SDLoc DL(Op); 1533 MVT VT = Op.getSimpleValueType(); 1534 SDValue Src = Op.getOperand(0); 1535 MVT SrcVT = Src.getSimpleValueType(); 1536 1537 // Prepare any fixed-length vector operands. 1538 MVT ContainerVT = VT; 1539 if (SrcVT.isFixedLengthVector()) { 1540 ContainerVT = getContainerForFixedLengthVector(VT); 1541 MVT SrcContainerVT = 1542 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 1543 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 1544 } 1545 1546 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 1547 SrcVT.getVectorElementType() != MVT::f16) { 1548 // For scalable vectors, we only need to close the gap between 1549 // vXf16->vXf64. 1550 if (!VT.isFixedLengthVector()) 1551 return Op; 1552 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 1553 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 1554 return convertFromScalableVector(VT, Src, DAG, Subtarget); 1555 } 1556 1557 MVT InterVT = VT.changeVectorElementType(MVT::f32); 1558 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 1559 SDValue IntermediateExtend = getRVVFPExtendOrRound( 1560 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 1561 1562 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 1563 DL, DAG, Subtarget); 1564 if (VT.isFixedLengthVector()) 1565 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 1566 return Extend; 1567 } 1568 case ISD::FP_ROUND: { 1569 // RVV can only do fp_round to types half the size as the source. We 1570 // custom-lower f64->f16 rounds via RVV's round-to-odd float 1571 // conversion instruction. 1572 SDLoc DL(Op); 1573 MVT VT = Op.getSimpleValueType(); 1574 SDValue Src = Op.getOperand(0); 1575 MVT SrcVT = Src.getSimpleValueType(); 1576 1577 // Prepare any fixed-length vector operands. 1578 MVT ContainerVT = VT; 1579 if (VT.isFixedLengthVector()) { 1580 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 1581 ContainerVT = 1582 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 1583 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 1584 } 1585 1586 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 1587 SrcVT.getVectorElementType() != MVT::f64) { 1588 // For scalable vectors, we only need to close the gap between 1589 // vXf64<->vXf16. 1590 if (!VT.isFixedLengthVector()) 1591 return Op; 1592 // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version. 1593 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 1594 return convertFromScalableVector(VT, Src, DAG, Subtarget); 1595 } 1596 1597 SDValue Mask, VL; 1598 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1599 1600 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 1601 SDValue IntermediateRound = 1602 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 1603 SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT, 1604 DL, DAG, Subtarget); 1605 1606 if (VT.isFixedLengthVector()) 1607 return convertFromScalableVector(VT, Round, DAG, Subtarget); 1608 return Round; 1609 } 1610 case ISD::FP_TO_SINT: 1611 case ISD::FP_TO_UINT: 1612 case ISD::SINT_TO_FP: 1613 case ISD::UINT_TO_FP: { 1614 // RVV can only do fp<->int conversions to types half/double the size as 1615 // the source. We custom-lower any conversions that do two hops into 1616 // sequences. 1617 MVT VT = Op.getSimpleValueType(); 1618 if (!VT.isVector()) 1619 return Op; 1620 SDLoc DL(Op); 1621 SDValue Src = Op.getOperand(0); 1622 MVT EltVT = VT.getVectorElementType(); 1623 MVT SrcVT = Src.getSimpleValueType(); 1624 MVT SrcEltVT = SrcVT.getVectorElementType(); 1625 unsigned EltSize = EltVT.getSizeInBits(); 1626 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 1627 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 1628 "Unexpected vector element types"); 1629 1630 bool IsInt2FP = SrcEltVT.isInteger(); 1631 // Widening conversions 1632 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 1633 if (IsInt2FP) { 1634 // Do a regular integer sign/zero extension then convert to float. 1635 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 1636 VT.getVectorElementCount()); 1637 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 1638 ? ISD::ZERO_EXTEND 1639 : ISD::SIGN_EXTEND; 1640 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 1641 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 1642 } 1643 // FP2Int 1644 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 1645 // Do one doubling fp_extend then complete the operation by converting 1646 // to int. 1647 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 1648 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 1649 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 1650 } 1651 1652 // Narrowing conversions 1653 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 1654 if (IsInt2FP) { 1655 // One narrowing int_to_fp, then an fp_round. 1656 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 1657 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 1658 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 1659 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 1660 } 1661 // FP2Int 1662 // One narrowing fp_to_int, then truncate the integer. If the float isn't 1663 // representable by the integer, the result is poison. 1664 MVT IVecVT = 1665 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 1666 VT.getVectorElementCount()); 1667 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 1668 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 1669 } 1670 1671 // Scalable vectors can exit here. Patterns will handle equally-sized 1672 // conversions halving/doubling ones. 1673 if (!VT.isFixedLengthVector()) 1674 return Op; 1675 1676 // For fixed-length vectors we lower to a custom "VL" node. 1677 unsigned RVVOpc = 0; 1678 switch (Op.getOpcode()) { 1679 default: 1680 llvm_unreachable("Impossible opcode"); 1681 case ISD::FP_TO_SINT: 1682 RVVOpc = RISCVISD::FP_TO_SINT_VL; 1683 break; 1684 case ISD::FP_TO_UINT: 1685 RVVOpc = RISCVISD::FP_TO_UINT_VL; 1686 break; 1687 case ISD::SINT_TO_FP: 1688 RVVOpc = RISCVISD::SINT_TO_FP_VL; 1689 break; 1690 case ISD::UINT_TO_FP: 1691 RVVOpc = RISCVISD::UINT_TO_FP_VL; 1692 break; 1693 } 1694 1695 MVT ContainerVT, SrcContainerVT; 1696 // Derive the reference container type from the larger vector type. 1697 if (SrcEltSize > EltSize) { 1698 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 1699 ContainerVT = 1700 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 1701 } else { 1702 ContainerVT = getContainerForFixedLengthVector(VT); 1703 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 1704 } 1705 1706 SDValue Mask, VL; 1707 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1708 1709 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 1710 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 1711 return convertFromScalableVector(VT, Src, DAG, Subtarget); 1712 } 1713 case ISD::VECREDUCE_ADD: 1714 case ISD::VECREDUCE_UMAX: 1715 case ISD::VECREDUCE_SMAX: 1716 case ISD::VECREDUCE_UMIN: 1717 case ISD::VECREDUCE_SMIN: 1718 case ISD::VECREDUCE_AND: 1719 case ISD::VECREDUCE_OR: 1720 case ISD::VECREDUCE_XOR: 1721 return lowerVECREDUCE(Op, DAG); 1722 case ISD::VECREDUCE_FADD: 1723 case ISD::VECREDUCE_SEQ_FADD: 1724 return lowerFPVECREDUCE(Op, DAG); 1725 case ISD::INSERT_SUBVECTOR: 1726 return lowerINSERT_SUBVECTOR(Op, DAG); 1727 case ISD::EXTRACT_SUBVECTOR: 1728 return lowerEXTRACT_SUBVECTOR(Op, DAG); 1729 case ISD::VECTOR_REVERSE: 1730 return lowerVECTOR_REVERSE(Op, DAG); 1731 case ISD::BUILD_VECTOR: 1732 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 1733 case ISD::VECTOR_SHUFFLE: 1734 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 1735 case ISD::CONCAT_VECTORS: { 1736 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 1737 // better than going through the stack, as the default expansion does. 1738 SDLoc DL(Op); 1739 MVT VT = Op.getSimpleValueType(); 1740 unsigned NumOpElts = 1741 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 1742 SDValue Vec = DAG.getUNDEF(VT); 1743 for (const auto &OpIdx : enumerate(Op->ops())) 1744 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(), 1745 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 1746 return Vec; 1747 } 1748 case ISD::LOAD: 1749 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 1750 case ISD::STORE: 1751 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 1752 case ISD::MLOAD: 1753 return lowerMLOAD(Op, DAG); 1754 case ISD::MSTORE: 1755 return lowerMSTORE(Op, DAG); 1756 case ISD::SETCC: 1757 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 1758 case ISD::ADD: 1759 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 1760 case ISD::SUB: 1761 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 1762 case ISD::MUL: 1763 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 1764 case ISD::MULHS: 1765 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 1766 case ISD::MULHU: 1767 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 1768 case ISD::AND: 1769 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 1770 RISCVISD::AND_VL); 1771 case ISD::OR: 1772 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 1773 RISCVISD::OR_VL); 1774 case ISD::XOR: 1775 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 1776 RISCVISD::XOR_VL); 1777 case ISD::SDIV: 1778 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 1779 case ISD::SREM: 1780 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 1781 case ISD::UDIV: 1782 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 1783 case ISD::UREM: 1784 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 1785 case ISD::SHL: 1786 return lowerToScalableOp(Op, DAG, RISCVISD::SHL_VL); 1787 case ISD::SRA: 1788 return lowerToScalableOp(Op, DAG, RISCVISD::SRA_VL); 1789 case ISD::SRL: 1790 return lowerToScalableOp(Op, DAG, RISCVISD::SRL_VL); 1791 case ISD::FADD: 1792 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 1793 case ISD::FSUB: 1794 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 1795 case ISD::FMUL: 1796 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 1797 case ISD::FDIV: 1798 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 1799 case ISD::FNEG: 1800 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 1801 case ISD::FABS: 1802 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 1803 case ISD::FSQRT: 1804 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 1805 case ISD::FMA: 1806 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 1807 case ISD::SMIN: 1808 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 1809 case ISD::SMAX: 1810 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 1811 case ISD::UMIN: 1812 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 1813 case ISD::UMAX: 1814 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 1815 case ISD::ABS: 1816 return lowerABS(Op, DAG); 1817 case ISD::VSELECT: 1818 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 1819 case ISD::FCOPYSIGN: 1820 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 1821 case ISD::MGATHER: 1822 return lowerMGATHER(Op, DAG); 1823 case ISD::MSCATTER: 1824 return lowerMSCATTER(Op, DAG); 1825 } 1826 } 1827 1828 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 1829 SelectionDAG &DAG, unsigned Flags) { 1830 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 1831 } 1832 1833 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 1834 SelectionDAG &DAG, unsigned Flags) { 1835 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 1836 Flags); 1837 } 1838 1839 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 1840 SelectionDAG &DAG, unsigned Flags) { 1841 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 1842 N->getOffset(), Flags); 1843 } 1844 1845 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 1846 SelectionDAG &DAG, unsigned Flags) { 1847 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 1848 } 1849 1850 template <class NodeTy> 1851 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 1852 bool IsLocal) const { 1853 SDLoc DL(N); 1854 EVT Ty = getPointerTy(DAG.getDataLayout()); 1855 1856 if (isPositionIndependent()) { 1857 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 1858 if (IsLocal) 1859 // Use PC-relative addressing to access the symbol. This generates the 1860 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 1861 // %pcrel_lo(auipc)). 1862 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 1863 1864 // Use PC-relative addressing to access the GOT for this symbol, then load 1865 // the address from the GOT. This generates the pattern (PseudoLA sym), 1866 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 1867 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 1868 } 1869 1870 switch (getTargetMachine().getCodeModel()) { 1871 default: 1872 report_fatal_error("Unsupported code model for lowering"); 1873 case CodeModel::Small: { 1874 // Generate a sequence for accessing addresses within the first 2 GiB of 1875 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 1876 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 1877 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 1878 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 1879 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 1880 } 1881 case CodeModel::Medium: { 1882 // Generate a sequence for accessing addresses within any 2GiB range within 1883 // the address space. This generates the pattern (PseudoLLA sym), which 1884 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 1885 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 1886 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 1887 } 1888 } 1889 } 1890 1891 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 1892 SelectionDAG &DAG) const { 1893 SDLoc DL(Op); 1894 EVT Ty = Op.getValueType(); 1895 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 1896 int64_t Offset = N->getOffset(); 1897 MVT XLenVT = Subtarget.getXLenVT(); 1898 1899 const GlobalValue *GV = N->getGlobal(); 1900 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 1901 SDValue Addr = getAddr(N, DAG, IsLocal); 1902 1903 // In order to maximise the opportunity for common subexpression elimination, 1904 // emit a separate ADD node for the global address offset instead of folding 1905 // it in the global address node. Later peephole optimisations may choose to 1906 // fold it back in when profitable. 1907 if (Offset != 0) 1908 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 1909 DAG.getConstant(Offset, DL, XLenVT)); 1910 return Addr; 1911 } 1912 1913 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 1914 SelectionDAG &DAG) const { 1915 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 1916 1917 return getAddr(N, DAG); 1918 } 1919 1920 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 1921 SelectionDAG &DAG) const { 1922 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 1923 1924 return getAddr(N, DAG); 1925 } 1926 1927 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 1928 SelectionDAG &DAG) const { 1929 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 1930 1931 return getAddr(N, DAG); 1932 } 1933 1934 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 1935 SelectionDAG &DAG, 1936 bool UseGOT) const { 1937 SDLoc DL(N); 1938 EVT Ty = getPointerTy(DAG.getDataLayout()); 1939 const GlobalValue *GV = N->getGlobal(); 1940 MVT XLenVT = Subtarget.getXLenVT(); 1941 1942 if (UseGOT) { 1943 // Use PC-relative addressing to access the GOT for this TLS symbol, then 1944 // load the address from the GOT and add the thread pointer. This generates 1945 // the pattern (PseudoLA_TLS_IE sym), which expands to 1946 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 1947 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 1948 SDValue Load = 1949 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 1950 1951 // Add the thread pointer. 1952 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 1953 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 1954 } 1955 1956 // Generate a sequence for accessing the address relative to the thread 1957 // pointer, with the appropriate adjustment for the thread pointer offset. 1958 // This generates the pattern 1959 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 1960 SDValue AddrHi = 1961 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 1962 SDValue AddrAdd = 1963 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 1964 SDValue AddrLo = 1965 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 1966 1967 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 1968 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 1969 SDValue MNAdd = SDValue( 1970 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 1971 0); 1972 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 1973 } 1974 1975 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 1976 SelectionDAG &DAG) const { 1977 SDLoc DL(N); 1978 EVT Ty = getPointerTy(DAG.getDataLayout()); 1979 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 1980 const GlobalValue *GV = N->getGlobal(); 1981 1982 // Use a PC-relative addressing mode to access the global dynamic GOT address. 1983 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 1984 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 1985 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 1986 SDValue Load = 1987 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 1988 1989 // Prepare argument list to generate call. 1990 ArgListTy Args; 1991 ArgListEntry Entry; 1992 Entry.Node = Load; 1993 Entry.Ty = CallTy; 1994 Args.push_back(Entry); 1995 1996 // Setup call to __tls_get_addr. 1997 TargetLowering::CallLoweringInfo CLI(DAG); 1998 CLI.setDebugLoc(DL) 1999 .setChain(DAG.getEntryNode()) 2000 .setLibCallee(CallingConv::C, CallTy, 2001 DAG.getExternalSymbol("__tls_get_addr", Ty), 2002 std::move(Args)); 2003 2004 return LowerCallTo(CLI).first; 2005 } 2006 2007 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 2008 SelectionDAG &DAG) const { 2009 SDLoc DL(Op); 2010 EVT Ty = Op.getValueType(); 2011 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 2012 int64_t Offset = N->getOffset(); 2013 MVT XLenVT = Subtarget.getXLenVT(); 2014 2015 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 2016 2017 if (DAG.getMachineFunction().getFunction().getCallingConv() == 2018 CallingConv::GHC) 2019 report_fatal_error("In GHC calling convention TLS is not supported"); 2020 2021 SDValue Addr; 2022 switch (Model) { 2023 case TLSModel::LocalExec: 2024 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 2025 break; 2026 case TLSModel::InitialExec: 2027 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 2028 break; 2029 case TLSModel::LocalDynamic: 2030 case TLSModel::GeneralDynamic: 2031 Addr = getDynamicTLSAddr(N, DAG); 2032 break; 2033 } 2034 2035 // In order to maximise the opportunity for common subexpression elimination, 2036 // emit a separate ADD node for the global address offset instead of folding 2037 // it in the global address node. Later peephole optimisations may choose to 2038 // fold it back in when profitable. 2039 if (Offset != 0) 2040 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 2041 DAG.getConstant(Offset, DL, XLenVT)); 2042 return Addr; 2043 } 2044 2045 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 2046 SDValue CondV = Op.getOperand(0); 2047 SDValue TrueV = Op.getOperand(1); 2048 SDValue FalseV = Op.getOperand(2); 2049 SDLoc DL(Op); 2050 MVT XLenVT = Subtarget.getXLenVT(); 2051 2052 // If the result type is XLenVT and CondV is the output of a SETCC node 2053 // which also operated on XLenVT inputs, then merge the SETCC node into the 2054 // lowered RISCVISD::SELECT_CC to take advantage of the integer 2055 // compare+branch instructions. i.e.: 2056 // (select (setcc lhs, rhs, cc), truev, falsev) 2057 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 2058 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC && 2059 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 2060 SDValue LHS = CondV.getOperand(0); 2061 SDValue RHS = CondV.getOperand(1); 2062 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 2063 ISD::CondCode CCVal = CC->get(); 2064 2065 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 2066 2067 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT); 2068 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 2069 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 2070 } 2071 2072 // Otherwise: 2073 // (select condv, truev, falsev) 2074 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 2075 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 2076 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT); 2077 2078 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 2079 2080 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 2081 } 2082 2083 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 2084 SDValue CondV = Op.getOperand(1); 2085 SDLoc DL(Op); 2086 MVT XLenVT = Subtarget.getXLenVT(); 2087 2088 if (CondV.getOpcode() == ISD::SETCC && 2089 CondV.getOperand(0).getValueType() == XLenVT) { 2090 SDValue LHS = CondV.getOperand(0); 2091 SDValue RHS = CondV.getOperand(1); 2092 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 2093 2094 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 2095 2096 SDValue TargetCC = DAG.getCondCode(CCVal); 2097 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 2098 LHS, RHS, TargetCC, Op.getOperand(2)); 2099 } 2100 2101 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 2102 CondV, DAG.getConstant(0, DL, XLenVT), 2103 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 2104 } 2105 2106 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2107 MachineFunction &MF = DAG.getMachineFunction(); 2108 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 2109 2110 SDLoc DL(Op); 2111 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2112 getPointerTy(MF.getDataLayout())); 2113 2114 // vastart just stores the address of the VarArgsFrameIndex slot into the 2115 // memory location argument. 2116 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2117 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 2118 MachinePointerInfo(SV)); 2119 } 2120 2121 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 2122 SelectionDAG &DAG) const { 2123 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 2124 MachineFunction &MF = DAG.getMachineFunction(); 2125 MachineFrameInfo &MFI = MF.getFrameInfo(); 2126 MFI.setFrameAddressIsTaken(true); 2127 Register FrameReg = RI.getFrameRegister(MF); 2128 int XLenInBytes = Subtarget.getXLen() / 8; 2129 2130 EVT VT = Op.getValueType(); 2131 SDLoc DL(Op); 2132 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 2133 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2134 while (Depth--) { 2135 int Offset = -(XLenInBytes * 2); 2136 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 2137 DAG.getIntPtrConstant(Offset, DL)); 2138 FrameAddr = 2139 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2140 } 2141 return FrameAddr; 2142 } 2143 2144 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 2145 SelectionDAG &DAG) const { 2146 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 2147 MachineFunction &MF = DAG.getMachineFunction(); 2148 MachineFrameInfo &MFI = MF.getFrameInfo(); 2149 MFI.setReturnAddressIsTaken(true); 2150 MVT XLenVT = Subtarget.getXLenVT(); 2151 int XLenInBytes = Subtarget.getXLen() / 8; 2152 2153 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 2154 return SDValue(); 2155 2156 EVT VT = Op.getValueType(); 2157 SDLoc DL(Op); 2158 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2159 if (Depth) { 2160 int Off = -XLenInBytes; 2161 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 2162 SDValue Offset = DAG.getConstant(Off, DL, VT); 2163 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 2164 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 2165 MachinePointerInfo()); 2166 } 2167 2168 // Return the value of the return address register, marking it an implicit 2169 // live-in. 2170 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 2171 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 2172 } 2173 2174 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 2175 SelectionDAG &DAG) const { 2176 SDLoc DL(Op); 2177 SDValue Lo = Op.getOperand(0); 2178 SDValue Hi = Op.getOperand(1); 2179 SDValue Shamt = Op.getOperand(2); 2180 EVT VT = Lo.getValueType(); 2181 2182 // if Shamt-XLEN < 0: // Shamt < XLEN 2183 // Lo = Lo << Shamt 2184 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 2185 // else: 2186 // Lo = 0 2187 // Hi = Lo << (Shamt-XLEN) 2188 2189 SDValue Zero = DAG.getConstant(0, DL, VT); 2190 SDValue One = DAG.getConstant(1, DL, VT); 2191 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 2192 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 2193 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 2194 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 2195 2196 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 2197 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 2198 SDValue ShiftRightLo = 2199 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 2200 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 2201 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 2202 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 2203 2204 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 2205 2206 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 2207 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 2208 2209 SDValue Parts[2] = {Lo, Hi}; 2210 return DAG.getMergeValues(Parts, DL); 2211 } 2212 2213 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 2214 bool IsSRA) const { 2215 SDLoc DL(Op); 2216 SDValue Lo = Op.getOperand(0); 2217 SDValue Hi = Op.getOperand(1); 2218 SDValue Shamt = Op.getOperand(2); 2219 EVT VT = Lo.getValueType(); 2220 2221 // SRA expansion: 2222 // if Shamt-XLEN < 0: // Shamt < XLEN 2223 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 2224 // Hi = Hi >>s Shamt 2225 // else: 2226 // Lo = Hi >>s (Shamt-XLEN); 2227 // Hi = Hi >>s (XLEN-1) 2228 // 2229 // SRL expansion: 2230 // if Shamt-XLEN < 0: // Shamt < XLEN 2231 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 2232 // Hi = Hi >>u Shamt 2233 // else: 2234 // Lo = Hi >>u (Shamt-XLEN); 2235 // Hi = 0; 2236 2237 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 2238 2239 SDValue Zero = DAG.getConstant(0, DL, VT); 2240 SDValue One = DAG.getConstant(1, DL, VT); 2241 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 2242 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 2243 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 2244 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 2245 2246 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 2247 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 2248 SDValue ShiftLeftHi = 2249 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 2250 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 2251 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 2252 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 2253 SDValue HiFalse = 2254 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 2255 2256 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 2257 2258 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 2259 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 2260 2261 SDValue Parts[2] = {Lo, Hi}; 2262 return DAG.getMergeValues(Parts, DL); 2263 } 2264 2265 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 2266 // illegal (currently only vXi64 RV32). 2267 // FIXME: We could also catch non-constant sign-extended i32 values and lower 2268 // them to SPLAT_VECTOR_I64 2269 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 2270 SelectionDAG &DAG) const { 2271 SDLoc DL(Op); 2272 EVT VecVT = Op.getValueType(); 2273 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 2274 "Unexpected SPLAT_VECTOR_PARTS lowering"); 2275 2276 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 2277 SDValue Lo = Op.getOperand(0); 2278 SDValue Hi = Op.getOperand(1); 2279 2280 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2281 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2282 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2283 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2284 // node in order to try and match RVV vector/scalar instructions. 2285 if ((LoC >> 31) == HiC) 2286 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 2287 } 2288 2289 // Else, on RV32 we lower an i64-element SPLAT_VECTOR thus, being careful not 2290 // to accidentally sign-extend the 32-bit halves to the e64 SEW: 2291 // vmv.v.x vX, hi 2292 // vsll.vx vX, vX, /*32*/ 2293 // vmv.v.x vY, lo 2294 // vsll.vx vY, vY, /*32*/ 2295 // vsrl.vx vY, vY, /*32*/ 2296 // vor.vv vX, vX, vY 2297 SDValue ThirtyTwoV = DAG.getConstant(32, DL, VecVT); 2298 2299 Lo = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 2300 Lo = DAG.getNode(ISD::SHL, DL, VecVT, Lo, ThirtyTwoV); 2301 Lo = DAG.getNode(ISD::SRL, DL, VecVT, Lo, ThirtyTwoV); 2302 2303 if (isNullConstant(Hi)) 2304 return Lo; 2305 2306 Hi = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Hi); 2307 Hi = DAG.getNode(ISD::SHL, DL, VecVT, Hi, ThirtyTwoV); 2308 2309 return DAG.getNode(ISD::OR, DL, VecVT, Lo, Hi); 2310 } 2311 2312 // Custom-lower extensions from mask vectors by using a vselect either with 1 2313 // for zero/any-extension or -1 for sign-extension: 2314 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 2315 // Note that any-extension is lowered identically to zero-extension. 2316 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 2317 int64_t ExtTrueVal) const { 2318 SDLoc DL(Op); 2319 MVT VecVT = Op.getSimpleValueType(); 2320 SDValue Src = Op.getOperand(0); 2321 // Only custom-lower extensions from mask types 2322 assert(Src.getValueType().isVector() && 2323 Src.getValueType().getVectorElementType() == MVT::i1); 2324 2325 MVT XLenVT = Subtarget.getXLenVT(); 2326 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 2327 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 2328 2329 if (VecVT.isScalableVector()) { 2330 // Be careful not to introduce illegal scalar types at this stage, and be 2331 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 2332 // illegal and must be expanded. Since we know that the constants are 2333 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 2334 bool IsRV32E64 = 2335 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 2336 2337 if (!IsRV32E64) { 2338 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 2339 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 2340 } else { 2341 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 2342 SplatTrueVal = 2343 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 2344 } 2345 2346 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 2347 } 2348 2349 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 2350 MVT I1ContainerVT = 2351 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 2352 2353 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 2354 2355 SDValue Mask, VL; 2356 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 2357 2358 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL); 2359 SplatTrueVal = 2360 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL); 2361 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 2362 SplatTrueVal, SplatZero, VL); 2363 2364 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 2365 } 2366 2367 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 2368 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 2369 MVT ExtVT = Op.getSimpleValueType(); 2370 // Only custom-lower extensions from fixed-length vector types. 2371 if (!ExtVT.isFixedLengthVector()) 2372 return Op; 2373 MVT VT = Op.getOperand(0).getSimpleValueType(); 2374 // Grab the canonical container type for the extended type. Infer the smaller 2375 // type from that to ensure the same number of vector elements, as we know 2376 // the LMUL will be sufficient to hold the smaller type. 2377 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 2378 // Get the extended container type manually to ensure the same number of 2379 // vector elements between source and dest. 2380 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 2381 ContainerExtVT.getVectorElementCount()); 2382 2383 SDValue Op1 = 2384 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 2385 2386 SDLoc DL(Op); 2387 SDValue Mask, VL; 2388 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2389 2390 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 2391 2392 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 2393 } 2394 2395 // Custom-lower truncations from vectors to mask vectors by using a mask and a 2396 // setcc operation: 2397 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 2398 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 2399 SelectionDAG &DAG) const { 2400 SDLoc DL(Op); 2401 EVT MaskVT = Op.getValueType(); 2402 // Only expect to custom-lower truncations to mask types 2403 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 2404 "Unexpected type for vector mask lowering"); 2405 SDValue Src = Op.getOperand(0); 2406 MVT VecVT = Src.getSimpleValueType(); 2407 2408 // If this is a fixed vector, we need to convert it to a scalable vector. 2409 MVT ContainerVT = VecVT; 2410 if (VecVT.isFixedLengthVector()) { 2411 ContainerVT = getContainerForFixedLengthVector(VecVT); 2412 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 2413 } 2414 2415 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 2416 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 2417 2418 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne); 2419 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero); 2420 2421 if (VecVT.isScalableVector()) { 2422 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 2423 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 2424 } 2425 2426 SDValue Mask, VL; 2427 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 2428 2429 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2430 SDValue Trunc = 2431 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 2432 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 2433 DAG.getCondCode(ISD::SETNE), Mask, VL); 2434 return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 2435 } 2436 2437 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 2438 // first position of a vector, and that vector is slid up to the insert index. 2439 // By limiting the active vector length to index+1 and merging with the 2440 // original vector (with an undisturbed tail policy for elements >= VL), we 2441 // achieve the desired result of leaving all elements untouched except the one 2442 // at VL-1, which is replaced with the desired value. 2443 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 2444 SelectionDAG &DAG) const { 2445 SDLoc DL(Op); 2446 MVT VecVT = Op.getSimpleValueType(); 2447 SDValue Vec = Op.getOperand(0); 2448 SDValue Val = Op.getOperand(1); 2449 SDValue Idx = Op.getOperand(2); 2450 2451 MVT ContainerVT = VecVT; 2452 // If the operand is a fixed-length vector, convert to a scalable one. 2453 if (VecVT.isFixedLengthVector()) { 2454 ContainerVT = getContainerForFixedLengthVector(VecVT); 2455 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2456 } 2457 2458 MVT XLenVT = Subtarget.getXLenVT(); 2459 2460 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 2461 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 2462 // Even i64-element vectors on RV32 can be lowered without scalar 2463 // legalization if the most-significant 32 bits of the value are not affected 2464 // by the sign-extension of the lower 32 bits. 2465 // TODO: We could also catch sign extensions of a 32-bit value. 2466 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 2467 const auto *CVal = cast<ConstantSDNode>(Val); 2468 if (isInt<32>(CVal->getSExtValue())) { 2469 IsLegalInsert = true; 2470 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 2471 } 2472 } 2473 2474 SDValue Mask, VL; 2475 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 2476 2477 SDValue ValInVec; 2478 2479 if (IsLegalInsert) { 2480 if (isNullConstant(Idx)) { 2481 Vec = DAG.getNode(RISCVISD::VMV_S_XF_VL, DL, ContainerVT, Vec, Val, VL); 2482 if (!VecVT.isFixedLengthVector()) 2483 return Vec; 2484 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 2485 } 2486 ValInVec = DAG.getNode(RISCVISD::VMV_S_XF_VL, DL, ContainerVT, 2487 DAG.getUNDEF(ContainerVT), Val, VL); 2488 } else { 2489 // On RV32, i64-element vectors must be specially handled to place the 2490 // value at element 0, by using two vslide1up instructions in sequence on 2491 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 2492 // this. 2493 SDValue One = DAG.getConstant(1, DL, XLenVT); 2494 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 2495 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 2496 MVT I32ContainerVT = 2497 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 2498 SDValue I32Mask = 2499 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 2500 // Limit the active VL to two. 2501 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 2502 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 2503 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 2504 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero, 2505 InsertI64VL); 2506 // First slide in the hi value, then the lo in underneath it. 2507 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 2508 ValHi, I32Mask, InsertI64VL); 2509 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec, 2510 ValLo, I32Mask, InsertI64VL); 2511 // Bitcast back to the right container type. 2512 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 2513 } 2514 2515 // Now that the value is in a vector, slide it into position. 2516 SDValue InsertVL = 2517 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 2518 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 2519 ValInVec, Idx, Mask, InsertVL); 2520 if (!VecVT.isFixedLengthVector()) 2521 return Slideup; 2522 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 2523 } 2524 2525 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 2526 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 2527 // types this is done using VMV_X_S to allow us to glean information about the 2528 // sign bits of the result. 2529 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 2530 SelectionDAG &DAG) const { 2531 SDLoc DL(Op); 2532 SDValue Idx = Op.getOperand(1); 2533 SDValue Vec = Op.getOperand(0); 2534 EVT EltVT = Op.getValueType(); 2535 MVT VecVT = Vec.getSimpleValueType(); 2536 MVT XLenVT = Subtarget.getXLenVT(); 2537 2538 if (VecVT.getVectorElementType() == MVT::i1) { 2539 // FIXME: For now we just promote to an i8 vector and extract from that, 2540 // but this is probably not optimal. 2541 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 2542 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 2543 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 2544 } 2545 2546 // If this is a fixed vector, we need to convert it to a scalable vector. 2547 MVT ContainerVT = VecVT; 2548 if (VecVT.isFixedLengthVector()) { 2549 ContainerVT = getContainerForFixedLengthVector(VecVT); 2550 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2551 } 2552 2553 // If the index is 0, the vector is already in the right position. 2554 if (!isNullConstant(Idx)) { 2555 // Use a VL of 1 to avoid processing more elements than we need. 2556 SDValue VL = DAG.getConstant(1, DL, XLenVT); 2557 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 2558 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2559 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 2560 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 2561 } 2562 2563 if (!EltVT.isInteger()) { 2564 // Floating-point extracts are handled in TableGen. 2565 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 2566 DAG.getConstant(0, DL, XLenVT)); 2567 } 2568 2569 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 2570 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 2571 } 2572 2573 // Called by type legalization to handle splat of i64 on RV32. 2574 // FIXME: We can optimize this when the type has sign or zero bits in one 2575 // of the halves. 2576 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar, 2577 SDValue VL, SelectionDAG &DAG) { 2578 SDValue ThirtyTwoV = DAG.getConstant(32, DL, VT); 2579 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2580 DAG.getConstant(0, DL, MVT::i32)); 2581 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2582 DAG.getConstant(1, DL, MVT::i32)); 2583 2584 // vmv.v.x vX, hi 2585 // vsll.vx vX, vX, /*32*/ 2586 // vmv.v.x vY, lo 2587 // vsll.vx vY, vY, /*32*/ 2588 // vsrl.vx vY, vY, /*32*/ 2589 // vor.vv vX, vX, vY 2590 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 2591 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2592 Lo = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL); 2593 Lo = DAG.getNode(RISCVISD::SHL_VL, DL, VT, Lo, ThirtyTwoV, Mask, VL); 2594 Lo = DAG.getNode(RISCVISD::SRL_VL, DL, VT, Lo, ThirtyTwoV, Mask, VL); 2595 2596 Hi = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Hi, VL); 2597 Hi = DAG.getNode(RISCVISD::SHL_VL, DL, VT, Hi, ThirtyTwoV, Mask, VL); 2598 2599 return DAG.getNode(RISCVISD::OR_VL, DL, VT, Lo, Hi, Mask, VL); 2600 } 2601 2602 // Some RVV intrinsics may claim that they want an integer operand to be 2603 // promoted or expanded. 2604 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG, 2605 const RISCVSubtarget &Subtarget) { 2606 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2607 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 2608 "Unexpected opcode"); 2609 2610 if (!Subtarget.hasStdExtV()) 2611 return SDValue(); 2612 2613 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 2614 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 2615 SDLoc DL(Op); 2616 2617 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 2618 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 2619 if (!II || !II->SplatOperand) 2620 return SDValue(); 2621 2622 unsigned SplatOp = II->SplatOperand + HasChain; 2623 assert(SplatOp < Op.getNumOperands()); 2624 2625 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 2626 SDValue &ScalarOp = Operands[SplatOp]; 2627 MVT OpVT = ScalarOp.getSimpleValueType(); 2628 MVT VT = Op.getSimpleValueType(); 2629 MVT XLenVT = Subtarget.getXLenVT(); 2630 2631 // If this isn't a scalar, or its type is XLenVT we're done. 2632 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 2633 return SDValue(); 2634 2635 // Simplest case is that the operand needs to be promoted to XLenVT. 2636 if (OpVT.bitsLT(XLenVT)) { 2637 // If the operand is a constant, sign extend to increase our chances 2638 // of being able to use a .vi instruction. ANY_EXTEND would become a 2639 // a zero extend and the simm5 check in isel would fail. 2640 // FIXME: Should we ignore the upper bits in isel instead? 2641 unsigned ExtOpc = 2642 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2643 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 2644 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 2645 } 2646 2647 // The more complex case is when the scalar is larger than XLenVT. 2648 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 2649 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 2650 2651 // If this is a sign-extended 32-bit constant, we can truncate it and rely 2652 // on the instruction to sign-extend since SEW>XLEN. 2653 if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) { 2654 if (isInt<32>(CVal->getSExtValue())) { 2655 ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 2656 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 2657 } 2658 } 2659 2660 // We need to convert the scalar to a splat vector. 2661 // FIXME: Can we implicitly truncate the scalar if it is known to 2662 // be sign extended? 2663 // VL should be the last operand. 2664 SDValue VL = Op.getOperand(Op.getNumOperands() - 1); 2665 assert(VL.getValueType() == XLenVT); 2666 ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG); 2667 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 2668 } 2669 2670 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2671 SelectionDAG &DAG) const { 2672 unsigned IntNo = Op.getConstantOperandVal(0); 2673 SDLoc DL(Op); 2674 MVT XLenVT = Subtarget.getXLenVT(); 2675 2676 switch (IntNo) { 2677 default: 2678 break; // Don't custom lower most intrinsics. 2679 case Intrinsic::thread_pointer: { 2680 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2681 return DAG.getRegister(RISCV::X4, PtrVT); 2682 } 2683 case Intrinsic::riscv_vmv_x_s: 2684 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 2685 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 2686 Op.getOperand(1)); 2687 case Intrinsic::riscv_vmv_v_x: { 2688 SDValue Scalar = Op.getOperand(1); 2689 if (Scalar.getValueType().bitsLE(XLenVT)) { 2690 unsigned ExtOpc = 2691 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2692 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2693 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, Op.getValueType(), Scalar, 2694 Op.getOperand(2)); 2695 } 2696 2697 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 2698 2699 // If this is a sign-extended 32-bit constant, we can truncate it and rely 2700 // on the instruction to sign-extend since SEW>XLEN. 2701 if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar)) { 2702 if (isInt<32>(CVal->getSExtValue())) 2703 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, Op.getValueType(), 2704 DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32), 2705 Op.getOperand(2)); 2706 } 2707 2708 // Otherwise use the more complicated splatting algorithm. 2709 return splatSplitI64WithVL(DL, Op.getSimpleValueType(), Scalar, 2710 Op.getOperand(2), DAG); 2711 } 2712 case Intrinsic::riscv_vfmv_v_f: 2713 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 2714 Op.getOperand(1), Op.getOperand(2)); 2715 case Intrinsic::riscv_vmv_s_x: { 2716 SDValue Scalar = Op.getOperand(2); 2717 2718 if (Scalar.getValueType().bitsLE(XLenVT)) { 2719 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 2720 return DAG.getNode(RISCVISD::VMV_S_XF_VL, DL, Op.getValueType(), 2721 Op.getOperand(1), Scalar, Op.getOperand(3)); 2722 } 2723 2724 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 2725 2726 // This is an i64 value that lives in two scalar registers. We have to 2727 // insert this in a convoluted way. First we build vXi64 splat containing 2728 // the/ two values that we assemble using some bit math. Next we'll use 2729 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 2730 // to merge element 0 from our splat into the source vector. 2731 // FIXME: This is probably not the best way to do this, but it is 2732 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 2733 // point. 2734 // vmv.v.x vX, hi 2735 // vsll.vx vX, vX, /*32*/ 2736 // vmv.v.x vY, lo 2737 // vsll.vx vY, vY, /*32*/ 2738 // vsrl.vx vY, vY, /*32*/ 2739 // vor.vv vX, vX, vY 2740 // 2741 // vid.v vVid 2742 // vmseq.vx mMask, vVid, 0 2743 // vmerge.vvm vDest, vSrc, vVal, mMask 2744 MVT VT = Op.getSimpleValueType(); 2745 SDValue Vec = Op.getOperand(1); 2746 SDValue VL = Op.getOperand(3); 2747 2748 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG); 2749 SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, 2750 DAG.getConstant(0, DL, MVT::i32), VL); 2751 2752 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 2753 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2754 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 2755 SDValue SelectCond = 2756 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 2757 DAG.getCondCode(ISD::SETEQ), Mask, VL); 2758 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 2759 Vec, VL); 2760 } 2761 } 2762 2763 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 2764 } 2765 2766 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 2767 SelectionDAG &DAG) const { 2768 return lowerVectorIntrinsicSplats(Op, DAG, Subtarget); 2769 } 2770 2771 static MVT getLMUL1VT(MVT VT) { 2772 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 2773 "Unexpected vector MVT"); 2774 return MVT::getScalableVectorVT( 2775 VT.getVectorElementType(), 2776 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 2777 } 2778 2779 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 2780 switch (ISDOpcode) { 2781 default: 2782 llvm_unreachable("Unhandled reduction"); 2783 case ISD::VECREDUCE_ADD: 2784 return RISCVISD::VECREDUCE_ADD_VL; 2785 case ISD::VECREDUCE_UMAX: 2786 return RISCVISD::VECREDUCE_UMAX_VL; 2787 case ISD::VECREDUCE_SMAX: 2788 return RISCVISD::VECREDUCE_SMAX_VL; 2789 case ISD::VECREDUCE_UMIN: 2790 return RISCVISD::VECREDUCE_UMIN_VL; 2791 case ISD::VECREDUCE_SMIN: 2792 return RISCVISD::VECREDUCE_SMIN_VL; 2793 case ISD::VECREDUCE_AND: 2794 return RISCVISD::VECREDUCE_AND_VL; 2795 case ISD::VECREDUCE_OR: 2796 return RISCVISD::VECREDUCE_OR_VL; 2797 case ISD::VECREDUCE_XOR: 2798 return RISCVISD::VECREDUCE_XOR_VL; 2799 } 2800 } 2801 2802 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 2803 SelectionDAG &DAG) const { 2804 SDLoc DL(Op); 2805 SDValue Vec = Op.getOperand(0); 2806 EVT VecEVT = Vec.getValueType(); 2807 2808 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 2809 2810 // Due to ordering in legalize types we may have a vector type that needs to 2811 // be split. Do that manually so we can get down to a legal type. 2812 while (getTypeAction(*DAG.getContext(), VecEVT) == 2813 TargetLowering::TypeSplitVector) { 2814 SDValue Lo, Hi; 2815 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 2816 VecEVT = Lo.getValueType(); 2817 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 2818 } 2819 2820 // TODO: The type may need to be widened rather than split. Or widened before 2821 // it can be split. 2822 if (!isTypeLegal(VecEVT)) 2823 return SDValue(); 2824 2825 MVT VecVT = VecEVT.getSimpleVT(); 2826 MVT VecEltVT = VecVT.getVectorElementType(); 2827 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 2828 2829 MVT ContainerVT = VecVT; 2830 if (VecVT.isFixedLengthVector()) { 2831 ContainerVT = getContainerForFixedLengthVector(VecVT); 2832 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2833 } 2834 2835 MVT M1VT = getLMUL1VT(ContainerVT); 2836 2837 SDValue Mask, VL; 2838 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 2839 2840 // FIXME: This is a VLMAX splat which might be too large and can prevent 2841 // vsetvli removal. 2842 SDValue NeutralElem = 2843 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 2844 SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem); 2845 SDValue Reduction = 2846 DAG.getNode(RVVOpcode, DL, M1VT, Vec, IdentitySplat, Mask, VL); 2847 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 2848 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 2849 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 2850 } 2851 2852 // Given a reduction op, this function returns the matching reduction opcode, 2853 // the vector SDValue and the scalar SDValue required to lower this to a 2854 // RISCVISD node. 2855 static std::tuple<unsigned, SDValue, SDValue> 2856 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 2857 SDLoc DL(Op); 2858 switch (Op.getOpcode()) { 2859 default: 2860 llvm_unreachable("Unhandled reduction"); 2861 case ISD::VECREDUCE_FADD: 2862 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), 2863 DAG.getConstantFP(0.0, DL, EltVT)); 2864 case ISD::VECREDUCE_SEQ_FADD: 2865 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 2866 Op.getOperand(0)); 2867 } 2868 } 2869 2870 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 2871 SelectionDAG &DAG) const { 2872 SDLoc DL(Op); 2873 MVT VecEltVT = Op.getSimpleValueType(); 2874 2875 unsigned RVVOpcode; 2876 SDValue VectorVal, ScalarVal; 2877 std::tie(RVVOpcode, VectorVal, ScalarVal) = 2878 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 2879 MVT VecVT = VectorVal.getSimpleValueType(); 2880 2881 MVT ContainerVT = VecVT; 2882 if (VecVT.isFixedLengthVector()) { 2883 ContainerVT = getContainerForFixedLengthVector(VecVT); 2884 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 2885 } 2886 2887 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 2888 2889 SDValue Mask, VL; 2890 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 2891 2892 // FIXME: This is a VLMAX splat which might be too large and can prevent 2893 // vsetvli removal. 2894 SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal); 2895 SDValue Reduction = 2896 DAG.getNode(RVVOpcode, DL, M1VT, VectorVal, ScalarSplat, Mask, VL); 2897 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 2898 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 2899 } 2900 2901 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 2902 SelectionDAG &DAG) const { 2903 SDValue Vec = Op.getOperand(0); 2904 SDValue SubVec = Op.getOperand(1); 2905 MVT VecVT = Vec.getSimpleValueType(); 2906 MVT SubVecVT = SubVec.getSimpleValueType(); 2907 2908 SDLoc DL(Op); 2909 MVT XLenVT = Subtarget.getXLenVT(); 2910 unsigned OrigIdx = Op.getConstantOperandVal(2); 2911 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 2912 2913 // We don't have the ability to slide mask vectors up indexed by their i1 2914 // elements; the smallest we can do is i8. Often we are able to bitcast to 2915 // equivalent i8 vectors. Note that when inserting a fixed-length vector 2916 // into a scalable one, we might not necessarily have enough scalable 2917 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 2918 if (SubVecVT.getVectorElementType() == MVT::i1 && 2919 (OrigIdx != 0 || !Vec.isUndef())) { 2920 if (VecVT.getVectorMinNumElements() >= 8 && 2921 SubVecVT.getVectorMinNumElements() >= 8) { 2922 assert(OrigIdx % 8 == 0 && "Invalid index"); 2923 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 2924 SubVecVT.getVectorMinNumElements() % 8 == 0 && 2925 "Unexpected mask vector lowering"); 2926 OrigIdx /= 8; 2927 SubVecVT = 2928 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 2929 SubVecVT.isScalableVector()); 2930 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 2931 VecVT.isScalableVector()); 2932 Vec = DAG.getBitcast(VecVT, Vec); 2933 SubVec = DAG.getBitcast(SubVecVT, SubVec); 2934 } else { 2935 // We can't slide this mask vector up indexed by its i1 elements. 2936 // This poses a problem when we wish to insert a scalable vector which 2937 // can't be re-expressed as a larger type. Just choose the slow path and 2938 // extend to a larger type, then truncate back down. 2939 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 2940 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 2941 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 2942 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 2943 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 2944 Op.getOperand(2)); 2945 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 2946 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 2947 } 2948 } 2949 2950 // If the subvector vector is a fixed-length type, we cannot use subregister 2951 // manipulation to simplify the codegen; we don't know which register of a 2952 // LMUL group contains the specific subvector as we only know the minimum 2953 // register size. Therefore we must slide the vector group up the full 2954 // amount. 2955 if (SubVecVT.isFixedLengthVector()) { 2956 if (OrigIdx == 0 && Vec.isUndef()) 2957 return Op; 2958 MVT ContainerVT = VecVT; 2959 if (VecVT.isFixedLengthVector()) { 2960 ContainerVT = getContainerForFixedLengthVector(VecVT); 2961 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2962 } 2963 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 2964 DAG.getUNDEF(ContainerVT), SubVec, 2965 DAG.getConstant(0, DL, XLenVT)); 2966 SDValue Mask = 2967 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 2968 // Set the vector length to only the number of elements we care about. Note 2969 // that for slideup this includes the offset. 2970 SDValue VL = 2971 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 2972 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 2973 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 2974 SubVec, SlideupAmt, Mask, VL); 2975 if (VecVT.isFixedLengthVector()) 2976 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 2977 return DAG.getBitcast(Op.getValueType(), Slideup); 2978 } 2979 2980 unsigned SubRegIdx, RemIdx; 2981 std::tie(SubRegIdx, RemIdx) = 2982 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 2983 VecVT, SubVecVT, OrigIdx, TRI); 2984 2985 RISCVVLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 2986 bool IsSubVecPartReg = SubVecLMUL == RISCVVLMUL::LMUL_F2 || 2987 SubVecLMUL == RISCVVLMUL::LMUL_F4 || 2988 SubVecLMUL == RISCVVLMUL::LMUL_F8; 2989 2990 // 1. If the Idx has been completely eliminated and this subvector's size is 2991 // a vector register or a multiple thereof, or the surrounding elements are 2992 // undef, then this is a subvector insert which naturally aligns to a vector 2993 // register. These can easily be handled using subregister manipulation. 2994 // 2. If the subvector is smaller than a vector register, then the insertion 2995 // must preserve the undisturbed elements of the register. We do this by 2996 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 2997 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 2998 // subvector within the vector register, and an INSERT_SUBVECTOR of that 2999 // LMUL=1 type back into the larger vector (resolving to another subregister 3000 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 3001 // to avoid allocating a large register group to hold our subvector. 3002 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 3003 return Op; 3004 3005 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 3006 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 3007 // (in our case undisturbed). This means we can set up a subvector insertion 3008 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 3009 // size of the subvector. 3010 MVT InterSubVT = VecVT; 3011 SDValue AlignedExtract = Vec; 3012 unsigned AlignedIdx = OrigIdx - RemIdx; 3013 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 3014 InterSubVT = getLMUL1VT(VecVT); 3015 // Extract a subvector equal to the nearest full vector register type. This 3016 // should resolve to a EXTRACT_SUBREG instruction. 3017 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 3018 DAG.getConstant(AlignedIdx, DL, XLenVT)); 3019 } 3020 3021 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 3022 // For scalable vectors this must be further multiplied by vscale. 3023 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 3024 3025 SDValue Mask, VL; 3026 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 3027 3028 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 3029 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 3030 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 3031 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 3032 3033 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 3034 DAG.getUNDEF(InterSubVT), SubVec, 3035 DAG.getConstant(0, DL, XLenVT)); 3036 3037 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 3038 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 3039 3040 // If required, insert this subvector back into the correct vector register. 3041 // This should resolve to an INSERT_SUBREG instruction. 3042 if (VecVT.bitsGT(InterSubVT)) 3043 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 3044 DAG.getConstant(AlignedIdx, DL, XLenVT)); 3045 3046 // We might have bitcast from a mask type: cast back to the original type if 3047 // required. 3048 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 3049 } 3050 3051 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 3052 SelectionDAG &DAG) const { 3053 SDValue Vec = Op.getOperand(0); 3054 MVT SubVecVT = Op.getSimpleValueType(); 3055 MVT VecVT = Vec.getSimpleValueType(); 3056 3057 SDLoc DL(Op); 3058 MVT XLenVT = Subtarget.getXLenVT(); 3059 unsigned OrigIdx = Op.getConstantOperandVal(1); 3060 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 3061 3062 // We don't have the ability to slide mask vectors down indexed by their i1 3063 // elements; the smallest we can do is i8. Often we are able to bitcast to 3064 // equivalent i8 vectors. Note that when extracting a fixed-length vector 3065 // from a scalable one, we might not necessarily have enough scalable 3066 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 3067 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 3068 if (VecVT.getVectorMinNumElements() >= 8 && 3069 SubVecVT.getVectorMinNumElements() >= 8) { 3070 assert(OrigIdx % 8 == 0 && "Invalid index"); 3071 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 3072 SubVecVT.getVectorMinNumElements() % 8 == 0 && 3073 "Unexpected mask vector lowering"); 3074 OrigIdx /= 8; 3075 SubVecVT = 3076 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 3077 SubVecVT.isScalableVector()); 3078 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 3079 VecVT.isScalableVector()); 3080 Vec = DAG.getBitcast(VecVT, Vec); 3081 } else { 3082 // We can't slide this mask vector down, indexed by its i1 elements. 3083 // This poses a problem when we wish to extract a scalable vector which 3084 // can't be re-expressed as a larger type. Just choose the slow path and 3085 // extend to a larger type, then truncate back down. 3086 // TODO: We could probably improve this when extracting certain fixed 3087 // from fixed, where we can extract as i8 and shift the correct element 3088 // right to reach the desired subvector? 3089 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 3090 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 3091 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 3092 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 3093 Op.getOperand(1)); 3094 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 3095 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 3096 } 3097 } 3098 3099 // If the subvector vector is a fixed-length type, we cannot use subregister 3100 // manipulation to simplify the codegen; we don't know which register of a 3101 // LMUL group contains the specific subvector as we only know the minimum 3102 // register size. Therefore we must slide the vector group down the full 3103 // amount. 3104 if (SubVecVT.isFixedLengthVector()) { 3105 // With an index of 0 this is a cast-like subvector, which can be performed 3106 // with subregister operations. 3107 if (OrigIdx == 0) 3108 return Op; 3109 MVT ContainerVT = VecVT; 3110 if (VecVT.isFixedLengthVector()) { 3111 ContainerVT = getContainerForFixedLengthVector(VecVT); 3112 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 3113 } 3114 SDValue Mask = 3115 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 3116 // Set the vector length to only the number of elements we care about. This 3117 // avoids sliding down elements we're going to discard straight away. 3118 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 3119 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 3120 SDValue Slidedown = 3121 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 3122 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 3123 // Now we can use a cast-like subvector extract to get the result. 3124 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 3125 DAG.getConstant(0, DL, XLenVT)); 3126 return DAG.getBitcast(Op.getValueType(), Slidedown); 3127 } 3128 3129 unsigned SubRegIdx, RemIdx; 3130 std::tie(SubRegIdx, RemIdx) = 3131 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 3132 VecVT, SubVecVT, OrigIdx, TRI); 3133 3134 // If the Idx has been completely eliminated then this is a subvector extract 3135 // which naturally aligns to a vector register. These can easily be handled 3136 // using subregister manipulation. 3137 if (RemIdx == 0) 3138 return Op; 3139 3140 // Else we must shift our vector register directly to extract the subvector. 3141 // Do this using VSLIDEDOWN. 3142 3143 // If the vector type is an LMUL-group type, extract a subvector equal to the 3144 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 3145 // instruction. 3146 MVT InterSubVT = VecVT; 3147 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 3148 InterSubVT = getLMUL1VT(VecVT); 3149 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 3150 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 3151 } 3152 3153 // Slide this vector register down by the desired number of elements in order 3154 // to place the desired subvector starting at element 0. 3155 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 3156 // For scalable vectors this must be further multiplied by vscale. 3157 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 3158 3159 SDValue Mask, VL; 3160 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 3161 SDValue Slidedown = 3162 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 3163 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 3164 3165 // Now the vector is in the right position, extract our final subvector. This 3166 // should resolve to a COPY. 3167 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 3168 DAG.getConstant(0, DL, XLenVT)); 3169 3170 // We might have bitcast from a mask type: cast back to the original type if 3171 // required. 3172 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 3173 } 3174 3175 // Implement vector_reverse using vrgather.vv with indices determined by 3176 // subtracting the id of each element from (VLMAX-1). This will convert 3177 // the indices like so: 3178 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 3179 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 3180 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 3181 SelectionDAG &DAG) const { 3182 SDLoc DL(Op); 3183 MVT VecVT = Op.getSimpleValueType(); 3184 unsigned EltSize = VecVT.getScalarSizeInBits(); 3185 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 3186 3187 unsigned MaxVLMAX = 0; 3188 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 3189 if (VectorBitsMax != 0) 3190 MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock; 3191 3192 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 3193 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 3194 3195 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 3196 // to use vrgatherei16.vv. 3197 // TODO: It's also possible to use vrgatherei16.vv for other types to 3198 // decrease register width for the index calculation. 3199 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 3200 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 3201 // Reverse each half, then reassemble them in reverse order. 3202 // NOTE: It's also possible that after splitting that VLMAX no longer 3203 // requires vrgatherei16.vv. 3204 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 3205 SDValue Lo, Hi; 3206 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3207 EVT LoVT, HiVT; 3208 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 3209 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 3210 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 3211 // Reassemble the low and high pieces reversed. 3212 // FIXME: This is a CONCAT_VECTORS. 3213 SDValue Res = 3214 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 3215 DAG.getIntPtrConstant(0, DL)); 3216 return DAG.getNode( 3217 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 3218 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 3219 } 3220 3221 // Just promote the int type to i16 which will double the LMUL. 3222 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 3223 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 3224 } 3225 3226 MVT XLenVT = Subtarget.getXLenVT(); 3227 SDValue Mask, VL; 3228 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 3229 3230 // Calculate VLMAX-1 for the desired SEW. 3231 unsigned MinElts = VecVT.getVectorMinNumElements(); 3232 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 3233 DAG.getConstant(MinElts, DL, XLenVT)); 3234 SDValue VLMinus1 = 3235 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 3236 3237 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 3238 bool IsRV32E64 = 3239 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 3240 SDValue SplatVL; 3241 if (!IsRV32E64) 3242 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 3243 else 3244 SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1); 3245 3246 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 3247 SDValue Indices = 3248 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 3249 3250 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 3251 } 3252 3253 SDValue 3254 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 3255 SelectionDAG &DAG) const { 3256 auto *Load = cast<LoadSDNode>(Op); 3257 3258 SDLoc DL(Op); 3259 MVT VT = Op.getSimpleValueType(); 3260 MVT ContainerVT = getContainerForFixedLengthVector(VT); 3261 3262 SDValue VL = 3263 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 3264 3265 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 3266 SDValue NewLoad = DAG.getMemIntrinsicNode( 3267 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 3268 Load->getMemoryVT(), Load->getMemOperand()); 3269 3270 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 3271 return DAG.getMergeValues({Result, Load->getChain()}, DL); 3272 } 3273 3274 SDValue 3275 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 3276 SelectionDAG &DAG) const { 3277 auto *Store = cast<StoreSDNode>(Op); 3278 3279 SDLoc DL(Op); 3280 MVT VT = Store->getValue().getSimpleValueType(); 3281 3282 // FIXME: We probably need to zero any extra bits in a byte for mask stores. 3283 // This is tricky to do. 3284 3285 MVT ContainerVT = getContainerForFixedLengthVector(VT); 3286 3287 SDValue VL = 3288 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 3289 3290 SDValue NewValue = 3291 convertToScalableVector(ContainerVT, Store->getValue(), DAG, Subtarget); 3292 return DAG.getMemIntrinsicNode( 3293 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 3294 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 3295 Store->getMemoryVT(), Store->getMemOperand()); 3296 } 3297 3298 SDValue RISCVTargetLowering::lowerMLOAD(SDValue Op, SelectionDAG &DAG) const { 3299 auto *Load = cast<MaskedLoadSDNode>(Op); 3300 3301 SDLoc DL(Op); 3302 MVT VT = Op.getSimpleValueType(); 3303 MVT XLenVT = Subtarget.getXLenVT(); 3304 3305 SDValue Mask = Load->getMask(); 3306 SDValue PassThru = Load->getPassThru(); 3307 SDValue VL; 3308 3309 MVT ContainerVT = VT; 3310 if (VT.isFixedLengthVector()) { 3311 ContainerVT = getContainerForFixedLengthVector(VT); 3312 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3313 3314 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 3315 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 3316 VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 3317 } else 3318 VL = DAG.getRegister(RISCV::X0, XLenVT); 3319 3320 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 3321 SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT); 3322 SDValue Ops[] = {Load->getChain(), IntID, PassThru, 3323 Load->getBasePtr(), Mask, VL}; 3324 SDValue Result = 3325 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 3326 Load->getMemoryVT(), Load->getMemOperand()); 3327 SDValue Chain = Result.getValue(1); 3328 3329 if (VT.isFixedLengthVector()) 3330 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3331 3332 return DAG.getMergeValues({Result, Chain}, DL); 3333 } 3334 3335 SDValue RISCVTargetLowering::lowerMSTORE(SDValue Op, SelectionDAG &DAG) const { 3336 auto *Store = cast<MaskedStoreSDNode>(Op); 3337 3338 SDLoc DL(Op); 3339 SDValue Val = Store->getValue(); 3340 SDValue Mask = Store->getMask(); 3341 MVT VT = Val.getSimpleValueType(); 3342 MVT XLenVT = Subtarget.getXLenVT(); 3343 SDValue VL; 3344 3345 MVT ContainerVT = VT; 3346 if (VT.isFixedLengthVector()) { 3347 ContainerVT = getContainerForFixedLengthVector(VT); 3348 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3349 3350 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 3351 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 3352 VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 3353 } else 3354 VL = DAG.getRegister(RISCV::X0, XLenVT); 3355 3356 SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vse_mask, DL, XLenVT); 3357 return DAG.getMemIntrinsicNode( 3358 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 3359 {Store->getChain(), IntID, Val, Store->getBasePtr(), Mask, VL}, 3360 Store->getMemoryVT(), Store->getMemOperand()); 3361 } 3362 3363 SDValue 3364 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 3365 SelectionDAG &DAG) const { 3366 MVT InVT = Op.getOperand(0).getSimpleValueType(); 3367 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 3368 3369 MVT VT = Op.getSimpleValueType(); 3370 3371 SDValue Op1 = 3372 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 3373 SDValue Op2 = 3374 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 3375 3376 SDLoc DL(Op); 3377 SDValue VL = 3378 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 3379 3380 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3381 3382 bool Invert = false; 3383 Optional<unsigned> LogicOpc; 3384 if (ContainerVT.isFloatingPoint()) { 3385 bool Swap = false; 3386 switch (CC) { 3387 default: 3388 break; 3389 case ISD::SETULE: 3390 case ISD::SETULT: 3391 Swap = true; 3392 LLVM_FALLTHROUGH; 3393 case ISD::SETUGE: 3394 case ISD::SETUGT: 3395 CC = getSetCCInverse(CC, ContainerVT); 3396 Invert = true; 3397 break; 3398 case ISD::SETOGE: 3399 case ISD::SETOGT: 3400 case ISD::SETGE: 3401 case ISD::SETGT: 3402 Swap = true; 3403 break; 3404 case ISD::SETUEQ: 3405 // Use !((OLT Op1, Op2) || (OLT Op2, Op1)) 3406 Invert = true; 3407 LogicOpc = RISCVISD::VMOR_VL; 3408 CC = ISD::SETOLT; 3409 break; 3410 case ISD::SETONE: 3411 // Use ((OLT Op1, Op2) || (OLT Op2, Op1)) 3412 LogicOpc = RISCVISD::VMOR_VL; 3413 CC = ISD::SETOLT; 3414 break; 3415 case ISD::SETO: 3416 // Use (OEQ Op1, Op1) && (OEQ Op2, Op2) 3417 LogicOpc = RISCVISD::VMAND_VL; 3418 CC = ISD::SETOEQ; 3419 break; 3420 case ISD::SETUO: 3421 // Use (UNE Op1, Op1) || (UNE Op2, Op2) 3422 LogicOpc = RISCVISD::VMOR_VL; 3423 CC = ISD::SETUNE; 3424 break; 3425 } 3426 3427 if (Swap) { 3428 CC = getSetCCSwappedOperands(CC); 3429 std::swap(Op1, Op2); 3430 } 3431 } 3432 3433 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3434 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3435 3436 // There are 3 cases we need to emit. 3437 // 1. For (OEQ Op1, Op1) && (OEQ Op2, Op2) or (UNE Op1, Op1) || (UNE Op2, Op2) 3438 // we need to compare each operand with itself. 3439 // 2. For (OLT Op1, Op2) || (OLT Op2, Op1) we need to compare Op1 and Op2 in 3440 // both orders. 3441 // 3. For any other case we just need one compare with Op1 and Op2. 3442 SDValue Cmp; 3443 if (LogicOpc && (CC == ISD::SETOEQ || CC == ISD::SETUNE)) { 3444 Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op1, 3445 DAG.getCondCode(CC), Mask, VL); 3446 SDValue Cmp2 = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op2, Op2, 3447 DAG.getCondCode(CC), Mask, VL); 3448 Cmp = DAG.getNode(*LogicOpc, DL, MaskVT, Cmp, Cmp2, VL); 3449 } else { 3450 Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 3451 DAG.getCondCode(CC), Mask, VL); 3452 if (LogicOpc) { 3453 SDValue Cmp2 = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op2, Op1, 3454 DAG.getCondCode(CC), Mask, VL); 3455 Cmp = DAG.getNode(*LogicOpc, DL, MaskVT, Cmp, Cmp2, VL); 3456 } 3457 } 3458 3459 if (Invert) { 3460 SDValue AllOnes = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 3461 Cmp = DAG.getNode(RISCVISD::VMXOR_VL, DL, MaskVT, Cmp, AllOnes, VL); 3462 } 3463 3464 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 3465 } 3466 3467 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 3468 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 3469 MVT VT = Op.getSimpleValueType(); 3470 3471 if (VT.getVectorElementType() == MVT::i1) 3472 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 3473 3474 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 3475 } 3476 3477 // Lower vector ABS to smax(X, sub(0, X)). 3478 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 3479 SDLoc DL(Op); 3480 MVT VT = Op.getSimpleValueType(); 3481 SDValue X = Op.getOperand(0); 3482 3483 assert(VT.isFixedLengthVector() && "Unexpected type"); 3484 3485 MVT ContainerVT = getContainerForFixedLengthVector(VT); 3486 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 3487 3488 SDValue Mask, VL; 3489 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3490 3491 SDValue SplatZero = 3492 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 3493 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 3494 SDValue NegX = 3495 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 3496 SDValue Max = 3497 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 3498 3499 return convertFromScalableVector(VT, Max, DAG, Subtarget); 3500 } 3501 3502 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 3503 SDValue Op, SelectionDAG &DAG) const { 3504 SDLoc DL(Op); 3505 MVT VT = Op.getSimpleValueType(); 3506 SDValue Mag = Op.getOperand(0); 3507 SDValue Sign = Op.getOperand(1); 3508 assert(Mag.getValueType() == Sign.getValueType() && 3509 "Can only handle COPYSIGN with matching types."); 3510 3511 MVT ContainerVT = getContainerForFixedLengthVector(VT); 3512 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 3513 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 3514 3515 SDValue Mask, VL; 3516 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3517 3518 SDValue CopySign = 3519 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 3520 3521 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 3522 } 3523 3524 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 3525 SDValue Op, SelectionDAG &DAG) const { 3526 MVT VT = Op.getSimpleValueType(); 3527 MVT ContainerVT = getContainerForFixedLengthVector(VT); 3528 3529 MVT I1ContainerVT = 3530 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3531 3532 SDValue CC = 3533 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 3534 SDValue Op1 = 3535 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 3536 SDValue Op2 = 3537 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 3538 3539 SDLoc DL(Op); 3540 SDValue Mask, VL; 3541 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3542 3543 SDValue Select = 3544 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 3545 3546 return convertFromScalableVector(VT, Select, DAG, Subtarget); 3547 } 3548 3549 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 3550 unsigned NewOpc, 3551 bool HasMask) const { 3552 MVT VT = Op.getSimpleValueType(); 3553 assert(useRVVForFixedLengthVectorVT(VT) && 3554 "Only expected to lower fixed length vector operation!"); 3555 MVT ContainerVT = getContainerForFixedLengthVector(VT); 3556 3557 // Create list of operands by converting existing ones to scalable types. 3558 SmallVector<SDValue, 6> Ops; 3559 for (const SDValue &V : Op->op_values()) { 3560 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 3561 3562 // Pass through non-vector operands. 3563 if (!V.getValueType().isVector()) { 3564 Ops.push_back(V); 3565 continue; 3566 } 3567 3568 // "cast" fixed length vector to a scalable vector. 3569 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 3570 "Only fixed length vectors are supported!"); 3571 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 3572 } 3573 3574 SDLoc DL(Op); 3575 SDValue Mask, VL; 3576 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3577 if (HasMask) 3578 Ops.push_back(Mask); 3579 Ops.push_back(VL); 3580 3581 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 3582 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 3583 } 3584 3585 // Custom lower MGATHER to a legalized form for RVV. It will then be matched to 3586 // a RVV indexed load. The RVV indexed load instructions only support the 3587 // "unsigned unscaled" addressing mode; indices are implicitly zero-extended or 3588 // truncated to XLEN and are treated as byte offsets. Any signed or scaled 3589 // indexing is extended to the XLEN value type and scaled accordingly. 3590 SDValue RISCVTargetLowering::lowerMGATHER(SDValue Op, SelectionDAG &DAG) const { 3591 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 3592 SDLoc DL(Op); 3593 3594 SDValue Index = MGN->getIndex(); 3595 SDValue Mask = MGN->getMask(); 3596 SDValue PassThru = MGN->getPassThru(); 3597 3598 MVT VT = Op.getSimpleValueType(); 3599 MVT IndexVT = Index.getSimpleValueType(); 3600 MVT XLenVT = Subtarget.getXLenVT(); 3601 3602 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 3603 "Unexpected VTs!"); 3604 assert(MGN->getBasePtr().getSimpleValueType() == XLenVT && 3605 "Unexpected pointer type"); 3606 // Targets have to explicitly opt-in for extending vector loads. 3607 assert(MGN->getExtensionType() == ISD::NON_EXTLOAD && 3608 "Unexpected extending MGATHER"); 3609 3610 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 3611 // the selection of the masked intrinsics doesn't do this for us. 3612 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 3613 3614 SDValue VL; 3615 MVT ContainerVT = VT; 3616 if (VT.isFixedLengthVector()) { 3617 // We need to use the larger of the result and index type to determine the 3618 // scalable type to use so we don't increase LMUL for any operand/result. 3619 if (VT.bitsGE(IndexVT)) { 3620 ContainerVT = getContainerForFixedLengthVector(VT); 3621 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 3622 ContainerVT.getVectorElementCount()); 3623 } else { 3624 IndexVT = getContainerForFixedLengthVector(IndexVT); 3625 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 3626 IndexVT.getVectorElementCount()); 3627 } 3628 3629 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 3630 3631 if (!IsUnmasked) { 3632 MVT MaskVT = 3633 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 3634 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 3635 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 3636 } 3637 3638 VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 3639 } else 3640 VL = DAG.getRegister(RISCV::X0, XLenVT); 3641 3642 unsigned IntID = 3643 IsUnmasked ? Intrinsic::riscv_vloxei : Intrinsic::riscv_vloxei_mask; 3644 SmallVector<SDValue, 8> Ops{MGN->getChain(), 3645 DAG.getTargetConstant(IntID, DL, XLenVT)}; 3646 if (!IsUnmasked) 3647 Ops.push_back(PassThru); 3648 Ops.push_back(MGN->getBasePtr()); 3649 Ops.push_back(Index); 3650 if (!IsUnmasked) 3651 Ops.push_back(Mask); 3652 Ops.push_back(VL); 3653 3654 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 3655 SDValue Result = 3656 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 3657 MGN->getMemoryVT(), MGN->getMemOperand()); 3658 SDValue Chain = Result.getValue(1); 3659 3660 if (VT.isFixedLengthVector()) 3661 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 3662 3663 return DAG.getMergeValues({Result, Chain}, DL); 3664 } 3665 3666 // Custom lower MSCATTER to a legalized form for RVV. It will then be matched to 3667 // a RVV indexed store. The RVV indexed store instructions only support the 3668 // "unsigned unscaled" addressing mode; indices are implicitly zero-extended or 3669 // truncated to XLEN and are treated as byte offsets. Any signed or scaled 3670 // indexing is extended to the XLEN value type and scaled accordingly. 3671 SDValue RISCVTargetLowering::lowerMSCATTER(SDValue Op, 3672 SelectionDAG &DAG) const { 3673 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 3674 SDLoc DL(Op); 3675 SDValue Index = MSN->getIndex(); 3676 SDValue Mask = MSN->getMask(); 3677 SDValue Val = MSN->getValue(); 3678 3679 MVT VT = Val.getSimpleValueType(); 3680 MVT IndexVT = Index.getSimpleValueType(); 3681 MVT XLenVT = Subtarget.getXLenVT(); 3682 3683 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 3684 "Unexpected VTs!"); 3685 assert(MSN->getBasePtr().getSimpleValueType() == XLenVT && 3686 "Unexpected pointer type"); 3687 // Targets have to explicitly opt-in for extending vector loads and 3688 // truncating vector stores. 3689 assert(!MSN->isTruncatingStore() && "Unexpected extending MSCATTER"); 3690 3691 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 3692 // the selection of the masked intrinsics doesn't do this for us. 3693 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 3694 3695 SDValue VL; 3696 if (VT.isFixedLengthVector()) { 3697 // We need to use the larger of the value and index type to determine the 3698 // scalable type to use so we don't increase LMUL for any operand/result. 3699 if (VT.bitsGE(IndexVT)) { 3700 VT = getContainerForFixedLengthVector(VT); 3701 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 3702 VT.getVectorElementCount()); 3703 } else { 3704 IndexVT = getContainerForFixedLengthVector(IndexVT); 3705 VT = MVT::getVectorVT(VT.getVectorElementType(), 3706 IndexVT.getVectorElementCount()); 3707 } 3708 3709 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 3710 Val = convertToScalableVector(VT, Val, DAG, Subtarget); 3711 3712 if (!IsUnmasked) { 3713 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 3714 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 3715 } 3716 3717 VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 3718 } else 3719 VL = DAG.getRegister(RISCV::X0, XLenVT); 3720 3721 unsigned IntID = 3722 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 3723 SmallVector<SDValue, 8> Ops{MSN->getChain(), 3724 DAG.getTargetConstant(IntID, DL, XLenVT)}; 3725 Ops.push_back(Val); 3726 Ops.push_back(MSN->getBasePtr()); 3727 Ops.push_back(Index); 3728 if (!IsUnmasked) 3729 Ops.push_back(Mask); 3730 Ops.push_back(VL); 3731 3732 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, MSN->getVTList(), Ops, 3733 MSN->getMemoryVT(), MSN->getMemOperand()); 3734 } 3735 3736 // Returns the opcode of the target-specific SDNode that implements the 32-bit 3737 // form of the given Opcode. 3738 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 3739 switch (Opcode) { 3740 default: 3741 llvm_unreachable("Unexpected opcode"); 3742 case ISD::SHL: 3743 return RISCVISD::SLLW; 3744 case ISD::SRA: 3745 return RISCVISD::SRAW; 3746 case ISD::SRL: 3747 return RISCVISD::SRLW; 3748 case ISD::SDIV: 3749 return RISCVISD::DIVW; 3750 case ISD::UDIV: 3751 return RISCVISD::DIVUW; 3752 case ISD::UREM: 3753 return RISCVISD::REMUW; 3754 case ISD::ROTL: 3755 return RISCVISD::ROLW; 3756 case ISD::ROTR: 3757 return RISCVISD::RORW; 3758 case RISCVISD::GREVI: 3759 return RISCVISD::GREVIW; 3760 case RISCVISD::GORCI: 3761 return RISCVISD::GORCIW; 3762 } 3763 } 3764 3765 // Converts the given 32-bit operation to a target-specific SelectionDAG node. 3766 // Because i32 isn't a legal type for RV64, these operations would otherwise 3767 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W 3768 // later one because the fact the operation was originally of type i32 is 3769 // lost. 3770 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 3771 unsigned ExtOpc = ISD::ANY_EXTEND) { 3772 SDLoc DL(N); 3773 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 3774 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 3775 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 3776 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 3777 // ReplaceNodeResults requires we maintain the same type for the return value. 3778 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 3779 } 3780 3781 // Converts the given 32-bit operation to a i64 operation with signed extension 3782 // semantic to reduce the signed extension instructions. 3783 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 3784 SDLoc DL(N); 3785 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 3786 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 3787 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 3788 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 3789 DAG.getValueType(MVT::i32)); 3790 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 3791 } 3792 3793 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 3794 SmallVectorImpl<SDValue> &Results, 3795 SelectionDAG &DAG) const { 3796 SDLoc DL(N); 3797 switch (N->getOpcode()) { 3798 default: 3799 llvm_unreachable("Don't know how to custom type legalize this operation!"); 3800 case ISD::STRICT_FP_TO_SINT: 3801 case ISD::STRICT_FP_TO_UINT: 3802 case ISD::FP_TO_SINT: 3803 case ISD::FP_TO_UINT: { 3804 bool IsStrict = N->isStrictFPOpcode(); 3805 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3806 "Unexpected custom legalisation"); 3807 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 3808 // If the FP type needs to be softened, emit a library call using the 'si' 3809 // version. If we left it to default legalization we'd end up with 'di'. If 3810 // the FP type doesn't need to be softened just let generic type 3811 // legalization promote the result type. 3812 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 3813 TargetLowering::TypeSoftenFloat) 3814 return; 3815 RTLIB::Libcall LC; 3816 if (N->getOpcode() == ISD::FP_TO_SINT || 3817 N->getOpcode() == ISD::STRICT_FP_TO_SINT) 3818 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 3819 else 3820 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 3821 MakeLibCallOptions CallOptions; 3822 EVT OpVT = Op0.getValueType(); 3823 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 3824 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 3825 SDValue Result; 3826 std::tie(Result, Chain) = 3827 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 3828 Results.push_back(Result); 3829 if (IsStrict) 3830 Results.push_back(Chain); 3831 break; 3832 } 3833 case ISD::READCYCLECOUNTER: { 3834 assert(!Subtarget.is64Bit() && 3835 "READCYCLECOUNTER only has custom type legalization on riscv32"); 3836 3837 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 3838 SDValue RCW = 3839 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 3840 3841 Results.push_back( 3842 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 3843 Results.push_back(RCW.getValue(2)); 3844 break; 3845 } 3846 case ISD::ADD: 3847 case ISD::SUB: 3848 case ISD::MUL: 3849 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3850 "Unexpected custom legalisation"); 3851 if (N->getOperand(1).getOpcode() == ISD::Constant) 3852 return; 3853 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 3854 break; 3855 case ISD::SHL: 3856 case ISD::SRA: 3857 case ISD::SRL: 3858 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3859 "Unexpected custom legalisation"); 3860 if (N->getOperand(1).getOpcode() == ISD::Constant) 3861 return; 3862 Results.push_back(customLegalizeToWOp(N, DAG)); 3863 break; 3864 case ISD::ROTL: 3865 case ISD::ROTR: 3866 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3867 "Unexpected custom legalisation"); 3868 Results.push_back(customLegalizeToWOp(N, DAG)); 3869 break; 3870 case ISD::SDIV: 3871 case ISD::UDIV: 3872 case ISD::UREM: { 3873 MVT VT = N->getSimpleValueType(0); 3874 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 3875 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 3876 "Unexpected custom legalisation"); 3877 if (N->getOperand(0).getOpcode() == ISD::Constant || 3878 N->getOperand(1).getOpcode() == ISD::Constant) 3879 return; 3880 3881 // If the input is i32, use ANY_EXTEND since the W instructions don't read 3882 // the upper 32 bits. For other types we need to sign or zero extend 3883 // based on the opcode. 3884 unsigned ExtOpc = ISD::ANY_EXTEND; 3885 if (VT != MVT::i32) 3886 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 3887 : ISD::ZERO_EXTEND; 3888 3889 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 3890 break; 3891 } 3892 case ISD::UADDO: 3893 case ISD::USUBO: { 3894 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3895 "Unexpected custom legalisation"); 3896 bool IsAdd = N->getOpcode() == ISD::UADDO; 3897 SDLoc DL(N); 3898 // Create an ADDW or SUBW. 3899 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 3900 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 3901 SDValue Res = 3902 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 3903 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 3904 DAG.getValueType(MVT::i32)); 3905 3906 // Sign extend the LHS and perform an unsigned compare with the ADDW result. 3907 // Since the inputs are sign extended from i32, this is equivalent to 3908 // comparing the lower 32 bits. 3909 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 3910 SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 3911 IsAdd ? ISD::SETULT : ISD::SETUGT); 3912 3913 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 3914 Results.push_back(Overflow); 3915 return; 3916 } 3917 case ISD::UADDSAT: 3918 case ISD::USUBSAT: { 3919 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3920 "Unexpected custom legalisation"); 3921 SDLoc DL(N); 3922 if (Subtarget.hasStdExtZbb()) { 3923 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 3924 // sign extend allows overflow of the lower 32 bits to be detected on 3925 // the promoted size. 3926 SDValue LHS = 3927 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 3928 SDValue RHS = 3929 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 3930 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 3931 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 3932 return; 3933 } 3934 3935 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 3936 // promotion for UADDO/USUBO. 3937 Results.push_back(expandAddSubSat(N, DAG)); 3938 return; 3939 } 3940 case ISD::BITCAST: { 3941 assert(((N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3942 Subtarget.hasStdExtF()) || 3943 (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh())) && 3944 "Unexpected custom legalisation"); 3945 SDValue Op0 = N->getOperand(0); 3946 if (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh()) { 3947 if (Op0.getValueType() != MVT::f16) 3948 return; 3949 SDValue FPConv = 3950 DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, Subtarget.getXLenVT(), Op0); 3951 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 3952 } else if (N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3953 Subtarget.hasStdExtF()) { 3954 if (Op0.getValueType() != MVT::f32) 3955 return; 3956 SDValue FPConv = 3957 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 3958 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 3959 } 3960 break; 3961 } 3962 case RISCVISD::GREVI: 3963 case RISCVISD::GORCI: { 3964 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3965 "Unexpected custom legalisation"); 3966 // This is similar to customLegalizeToWOp, except that we pass the second 3967 // operand (a TargetConstant) straight through: it is already of type 3968 // XLenVT. 3969 SDLoc DL(N); 3970 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 3971 SDValue NewOp0 = 3972 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 3973 SDValue NewRes = 3974 DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, N->getOperand(1)); 3975 // ReplaceNodeResults requires we maintain the same type for the return 3976 // value. 3977 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 3978 break; 3979 } 3980 case RISCVISD::SHFLI: { 3981 // There is no SHFLIW instruction, but we can just promote the operation. 3982 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3983 "Unexpected custom legalisation"); 3984 SDLoc DL(N); 3985 SDValue NewOp0 = 3986 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 3987 SDValue NewRes = 3988 DAG.getNode(RISCVISD::SHFLI, DL, MVT::i64, NewOp0, N->getOperand(1)); 3989 // ReplaceNodeResults requires we maintain the same type for the return 3990 // value. 3991 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 3992 break; 3993 } 3994 case ISD::BSWAP: 3995 case ISD::BITREVERSE: { 3996 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 3997 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 3998 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 3999 N->getOperand(0)); 4000 unsigned Imm = N->getOpcode() == ISD::BITREVERSE ? 31 : 24; 4001 SDValue GREVIW = DAG.getNode(RISCVISD::GREVIW, DL, MVT::i64, NewOp0, 4002 DAG.getTargetConstant(Imm, DL, 4003 Subtarget.getXLenVT())); 4004 // ReplaceNodeResults requires we maintain the same type for the return 4005 // value. 4006 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, GREVIW)); 4007 break; 4008 } 4009 case ISD::FSHL: 4010 case ISD::FSHR: { 4011 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 4012 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 4013 SDValue NewOp0 = 4014 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 4015 SDValue NewOp1 = 4016 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 4017 SDValue NewOp2 = 4018 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 4019 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 4020 // Mask the shift amount to 5 bits. 4021 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 4022 DAG.getConstant(0x1f, DL, MVT::i64)); 4023 unsigned Opc = 4024 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 4025 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 4026 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 4027 break; 4028 } 4029 case ISD::EXTRACT_VECTOR_ELT: { 4030 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 4031 // type is illegal (currently only vXi64 RV32). 4032 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 4033 // transferred to the destination register. We issue two of these from the 4034 // upper- and lower- halves of the SEW-bit vector element, slid down to the 4035 // first element. 4036 SDLoc DL(N); 4037 SDValue Vec = N->getOperand(0); 4038 SDValue Idx = N->getOperand(1); 4039 4040 // The vector type hasn't been legalized yet so we can't issue target 4041 // specific nodes if it needs legalization. 4042 // FIXME: We would manually legalize if it's important. 4043 if (!isTypeLegal(Vec.getValueType())) 4044 return; 4045 4046 MVT VecVT = Vec.getSimpleValueType(); 4047 4048 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 4049 VecVT.getVectorElementType() == MVT::i64 && 4050 "Unexpected EXTRACT_VECTOR_ELT legalization"); 4051 4052 // If this is a fixed vector, we need to convert it to a scalable vector. 4053 MVT ContainerVT = VecVT; 4054 if (VecVT.isFixedLengthVector()) { 4055 ContainerVT = getContainerForFixedLengthVector(VecVT); 4056 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4057 } 4058 4059 MVT XLenVT = Subtarget.getXLenVT(); 4060 4061 // Use a VL of 1 to avoid processing more elements than we need. 4062 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 4063 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4064 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4065 4066 // Unless the index is known to be 0, we must slide the vector down to get 4067 // the desired element into index 0. 4068 if (!isNullConstant(Idx)) { 4069 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4070 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4071 } 4072 4073 // Extract the lower XLEN bits of the correct vector element. 4074 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4075 4076 // To extract the upper XLEN bits of the vector element, shift the first 4077 // element right by 32 bits and re-extract the lower XLEN bits. 4078 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4079 DAG.getConstant(32, DL, XLenVT), VL); 4080 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 4081 ThirtyTwoV, Mask, VL); 4082 4083 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 4084 4085 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 4086 break; 4087 } 4088 case ISD::INTRINSIC_WO_CHAIN: { 4089 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4090 switch (IntNo) { 4091 default: 4092 llvm_unreachable( 4093 "Don't know how to custom type legalize this intrinsic!"); 4094 case Intrinsic::riscv_vmv_x_s: { 4095 EVT VT = N->getValueType(0); 4096 MVT XLenVT = Subtarget.getXLenVT(); 4097 if (VT.bitsLT(XLenVT)) { 4098 // Simple case just extract using vmv.x.s and truncate. 4099 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 4100 Subtarget.getXLenVT(), N->getOperand(1)); 4101 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 4102 return; 4103 } 4104 4105 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 4106 "Unexpected custom legalization"); 4107 4108 // We need to do the move in two steps. 4109 SDValue Vec = N->getOperand(1); 4110 MVT VecVT = Vec.getSimpleValueType(); 4111 4112 // First extract the lower XLEN bits of the element. 4113 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4114 4115 // To extract the upper XLEN bits of the vector element, shift the first 4116 // element right by 32 bits and re-extract the lower XLEN bits. 4117 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4118 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 4119 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 4120 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, 4121 DAG.getConstant(32, DL, XLenVT), VL); 4122 SDValue LShr32 = 4123 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 4124 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 4125 4126 Results.push_back( 4127 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 4128 break; 4129 } 4130 } 4131 break; 4132 } 4133 case ISD::VECREDUCE_ADD: 4134 case ISD::VECREDUCE_AND: 4135 case ISD::VECREDUCE_OR: 4136 case ISD::VECREDUCE_XOR: 4137 case ISD::VECREDUCE_SMAX: 4138 case ISD::VECREDUCE_UMAX: 4139 case ISD::VECREDUCE_SMIN: 4140 case ISD::VECREDUCE_UMIN: 4141 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 4142 Results.push_back(V); 4143 break; 4144 } 4145 } 4146 4147 // A structure to hold one of the bit-manipulation patterns below. Together, a 4148 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 4149 // (or (and (shl x, 1), 0xAAAAAAAA), 4150 // (and (srl x, 1), 0x55555555)) 4151 struct RISCVBitmanipPat { 4152 SDValue Op; 4153 unsigned ShAmt; 4154 bool IsSHL; 4155 4156 bool formsPairWith(const RISCVBitmanipPat &Other) const { 4157 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 4158 } 4159 }; 4160 4161 // Matches patterns of the form 4162 // (and (shl x, C2), (C1 << C2)) 4163 // (and (srl x, C2), C1) 4164 // (shl (and x, C1), C2) 4165 // (srl (and x, (C1 << C2)), C2) 4166 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 4167 // The expected masks for each shift amount are specified in BitmanipMasks where 4168 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 4169 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 4170 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 4171 // XLen is 64. 4172 static Optional<RISCVBitmanipPat> 4173 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 4174 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 4175 "Unexpected number of masks"); 4176 Optional<uint64_t> Mask; 4177 // Optionally consume a mask around the shift operation. 4178 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 4179 Mask = Op.getConstantOperandVal(1); 4180 Op = Op.getOperand(0); 4181 } 4182 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 4183 return None; 4184 bool IsSHL = Op.getOpcode() == ISD::SHL; 4185 4186 if (!isa<ConstantSDNode>(Op.getOperand(1))) 4187 return None; 4188 uint64_t ShAmt = Op.getConstantOperandVal(1); 4189 4190 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 4191 if (ShAmt >= Width && !isPowerOf2_64(ShAmt)) 4192 return None; 4193 // If we don't have enough masks for 64 bit, then we must be trying to 4194 // match SHFL so we're only allowed to shift 1/4 of the width. 4195 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 4196 return None; 4197 4198 SDValue Src = Op.getOperand(0); 4199 4200 // The expected mask is shifted left when the AND is found around SHL 4201 // patterns. 4202 // ((x >> 1) & 0x55555555) 4203 // ((x << 1) & 0xAAAAAAAA) 4204 bool SHLExpMask = IsSHL; 4205 4206 if (!Mask) { 4207 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 4208 // the mask is all ones: consume that now. 4209 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 4210 Mask = Src.getConstantOperandVal(1); 4211 Src = Src.getOperand(0); 4212 // The expected mask is now in fact shifted left for SRL, so reverse the 4213 // decision. 4214 // ((x & 0xAAAAAAAA) >> 1) 4215 // ((x & 0x55555555) << 1) 4216 SHLExpMask = !SHLExpMask; 4217 } else { 4218 // Use a default shifted mask of all-ones if there's no AND, truncated 4219 // down to the expected width. This simplifies the logic later on. 4220 Mask = maskTrailingOnes<uint64_t>(Width); 4221 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 4222 } 4223 } 4224 4225 unsigned MaskIdx = Log2_32(ShAmt); 4226 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 4227 4228 if (SHLExpMask) 4229 ExpMask <<= ShAmt; 4230 4231 if (Mask != ExpMask) 4232 return None; 4233 4234 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 4235 } 4236 4237 // Matches any of the following bit-manipulation patterns: 4238 // (and (shl x, 1), (0x55555555 << 1)) 4239 // (and (srl x, 1), 0x55555555) 4240 // (shl (and x, 0x55555555), 1) 4241 // (srl (and x, (0x55555555 << 1)), 1) 4242 // where the shift amount and mask may vary thus: 4243 // [1] = 0x55555555 / 0xAAAAAAAA 4244 // [2] = 0x33333333 / 0xCCCCCCCC 4245 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 4246 // [8] = 0x00FF00FF / 0xFF00FF00 4247 // [16] = 0x0000FFFF / 0xFFFFFFFF 4248 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 4249 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 4250 // These are the unshifted masks which we use to match bit-manipulation 4251 // patterns. They may be shifted left in certain circumstances. 4252 static const uint64_t BitmanipMasks[] = { 4253 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 4254 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 4255 4256 return matchRISCVBitmanipPat(Op, BitmanipMasks); 4257 } 4258 4259 // Match the following pattern as a GREVI(W) operation 4260 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 4261 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 4262 const RISCVSubtarget &Subtarget) { 4263 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 4264 EVT VT = Op.getValueType(); 4265 4266 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 4267 auto LHS = matchGREVIPat(Op.getOperand(0)); 4268 auto RHS = matchGREVIPat(Op.getOperand(1)); 4269 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 4270 SDLoc DL(Op); 4271 return DAG.getNode( 4272 RISCVISD::GREVI, DL, VT, LHS->Op, 4273 DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT())); 4274 } 4275 } 4276 return SDValue(); 4277 } 4278 4279 // Matches any the following pattern as a GORCI(W) operation 4280 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 4281 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 4282 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 4283 // Note that with the variant of 3., 4284 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 4285 // the inner pattern will first be matched as GREVI and then the outer 4286 // pattern will be matched to GORC via the first rule above. 4287 // 4. (or (rotl/rotr x, bitwidth/2), x) 4288 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 4289 const RISCVSubtarget &Subtarget) { 4290 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 4291 EVT VT = Op.getValueType(); 4292 4293 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 4294 SDLoc DL(Op); 4295 SDValue Op0 = Op.getOperand(0); 4296 SDValue Op1 = Op.getOperand(1); 4297 4298 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 4299 if (Reverse.getOpcode() == RISCVISD::GREVI && Reverse.getOperand(0) == X && 4300 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 4301 return DAG.getNode(RISCVISD::GORCI, DL, VT, X, Reverse.getOperand(1)); 4302 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 4303 if ((Reverse.getOpcode() == ISD::ROTL || 4304 Reverse.getOpcode() == ISD::ROTR) && 4305 Reverse.getOperand(0) == X && 4306 isa<ConstantSDNode>(Reverse.getOperand(1))) { 4307 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 4308 if (RotAmt == (VT.getSizeInBits() / 2)) 4309 return DAG.getNode( 4310 RISCVISD::GORCI, DL, VT, X, 4311 DAG.getTargetConstant(RotAmt, DL, Subtarget.getXLenVT())); 4312 } 4313 return SDValue(); 4314 }; 4315 4316 // Check for either commutable permutation of (or (GREVI x, shamt), x) 4317 if (SDValue V = MatchOROfReverse(Op0, Op1)) 4318 return V; 4319 if (SDValue V = MatchOROfReverse(Op1, Op0)) 4320 return V; 4321 4322 // OR is commutable so canonicalize its OR operand to the left 4323 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 4324 std::swap(Op0, Op1); 4325 if (Op0.getOpcode() != ISD::OR) 4326 return SDValue(); 4327 SDValue OrOp0 = Op0.getOperand(0); 4328 SDValue OrOp1 = Op0.getOperand(1); 4329 auto LHS = matchGREVIPat(OrOp0); 4330 // OR is commutable so swap the operands and try again: x might have been 4331 // on the left 4332 if (!LHS) { 4333 std::swap(OrOp0, OrOp1); 4334 LHS = matchGREVIPat(OrOp0); 4335 } 4336 auto RHS = matchGREVIPat(Op1); 4337 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 4338 return DAG.getNode( 4339 RISCVISD::GORCI, DL, VT, LHS->Op, 4340 DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT())); 4341 } 4342 } 4343 return SDValue(); 4344 } 4345 4346 // Matches any of the following bit-manipulation patterns: 4347 // (and (shl x, 1), (0x22222222 << 1)) 4348 // (and (srl x, 1), 0x22222222) 4349 // (shl (and x, 0x22222222), 1) 4350 // (srl (and x, (0x22222222 << 1)), 1) 4351 // where the shift amount and mask may vary thus: 4352 // [1] = 0x22222222 / 0x44444444 4353 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 4354 // [4] = 0x00F000F0 / 0x0F000F00 4355 // [8] = 0x0000FF00 / 0x00FF0000 4356 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 4357 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 4358 // These are the unshifted masks which we use to match bit-manipulation 4359 // patterns. They may be shifted left in certain circumstances. 4360 static const uint64_t BitmanipMasks[] = { 4361 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 4362 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 4363 4364 return matchRISCVBitmanipPat(Op, BitmanipMasks); 4365 } 4366 4367 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 4368 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 4369 const RISCVSubtarget &Subtarget) { 4370 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 4371 EVT VT = Op.getValueType(); 4372 4373 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 4374 return SDValue(); 4375 4376 SDValue Op0 = Op.getOperand(0); 4377 SDValue Op1 = Op.getOperand(1); 4378 4379 // Or is commutable so canonicalize the second OR to the LHS. 4380 if (Op0.getOpcode() != ISD::OR) 4381 std::swap(Op0, Op1); 4382 if (Op0.getOpcode() != ISD::OR) 4383 return SDValue(); 4384 4385 // We found an inner OR, so our operands are the operands of the inner OR 4386 // and the other operand of the outer OR. 4387 SDValue A = Op0.getOperand(0); 4388 SDValue B = Op0.getOperand(1); 4389 SDValue C = Op1; 4390 4391 auto Match1 = matchSHFLPat(A); 4392 auto Match2 = matchSHFLPat(B); 4393 4394 // If neither matched, we failed. 4395 if (!Match1 && !Match2) 4396 return SDValue(); 4397 4398 // We had at least one match. if one failed, try the remaining C operand. 4399 if (!Match1) { 4400 std::swap(A, C); 4401 Match1 = matchSHFLPat(A); 4402 if (!Match1) 4403 return SDValue(); 4404 } else if (!Match2) { 4405 std::swap(B, C); 4406 Match2 = matchSHFLPat(B); 4407 if (!Match2) 4408 return SDValue(); 4409 } 4410 assert(Match1 && Match2); 4411 4412 // Make sure our matches pair up. 4413 if (!Match1->formsPairWith(*Match2)) 4414 return SDValue(); 4415 4416 // All the remains is to make sure C is an AND with the same input, that masks 4417 // out the bits that are being shuffled. 4418 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 4419 C.getOperand(0) != Match1->Op) 4420 return SDValue(); 4421 4422 uint64_t Mask = C.getConstantOperandVal(1); 4423 4424 static const uint64_t BitmanipMasks[] = { 4425 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 4426 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 4427 }; 4428 4429 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 4430 unsigned MaskIdx = Log2_32(Match1->ShAmt); 4431 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 4432 4433 if (Mask != ExpMask) 4434 return SDValue(); 4435 4436 SDLoc DL(Op); 4437 return DAG.getNode( 4438 RISCVISD::SHFLI, DL, VT, Match1->Op, 4439 DAG.getTargetConstant(Match1->ShAmt, DL, Subtarget.getXLenVT())); 4440 } 4441 4442 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 4443 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 4444 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 4445 // not undo itself, but they are redundant. 4446 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 4447 unsigned ShAmt1 = N->getConstantOperandVal(1); 4448 SDValue Src = N->getOperand(0); 4449 4450 if (Src.getOpcode() != N->getOpcode()) 4451 return SDValue(); 4452 4453 unsigned ShAmt2 = Src.getConstantOperandVal(1); 4454 Src = Src.getOperand(0); 4455 4456 unsigned CombinedShAmt; 4457 if (N->getOpcode() == RISCVISD::GORCI || N->getOpcode() == RISCVISD::GORCIW) 4458 CombinedShAmt = ShAmt1 | ShAmt2; 4459 else 4460 CombinedShAmt = ShAmt1 ^ ShAmt2; 4461 4462 if (CombinedShAmt == 0) 4463 return Src; 4464 4465 SDLoc DL(N); 4466 return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), Src, 4467 DAG.getTargetConstant(CombinedShAmt, DL, 4468 N->getOperand(1).getValueType())); 4469 } 4470 4471 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 4472 DAGCombinerInfo &DCI) const { 4473 SelectionDAG &DAG = DCI.DAG; 4474 4475 switch (N->getOpcode()) { 4476 default: 4477 break; 4478 case RISCVISD::SplitF64: { 4479 SDValue Op0 = N->getOperand(0); 4480 // If the input to SplitF64 is just BuildPairF64 then the operation is 4481 // redundant. Instead, use BuildPairF64's operands directly. 4482 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 4483 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 4484 4485 SDLoc DL(N); 4486 4487 // It's cheaper to materialise two 32-bit integers than to load a double 4488 // from the constant pool and transfer it to integer registers through the 4489 // stack. 4490 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 4491 APInt V = C->getValueAPF().bitcastToAPInt(); 4492 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 4493 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 4494 return DCI.CombineTo(N, Lo, Hi); 4495 } 4496 4497 // This is a target-specific version of a DAGCombine performed in 4498 // DAGCombiner::visitBITCAST. It performs the equivalent of: 4499 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 4500 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 4501 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 4502 !Op0.getNode()->hasOneUse()) 4503 break; 4504 SDValue NewSplitF64 = 4505 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 4506 Op0.getOperand(0)); 4507 SDValue Lo = NewSplitF64.getValue(0); 4508 SDValue Hi = NewSplitF64.getValue(1); 4509 APInt SignBit = APInt::getSignMask(32); 4510 if (Op0.getOpcode() == ISD::FNEG) { 4511 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 4512 DAG.getConstant(SignBit, DL, MVT::i32)); 4513 return DCI.CombineTo(N, Lo, NewHi); 4514 } 4515 assert(Op0.getOpcode() == ISD::FABS); 4516 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 4517 DAG.getConstant(~SignBit, DL, MVT::i32)); 4518 return DCI.CombineTo(N, Lo, NewHi); 4519 } 4520 case RISCVISD::SLLW: 4521 case RISCVISD::SRAW: 4522 case RISCVISD::SRLW: 4523 case RISCVISD::ROLW: 4524 case RISCVISD::RORW: { 4525 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 4526 SDValue LHS = N->getOperand(0); 4527 SDValue RHS = N->getOperand(1); 4528 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 4529 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5); 4530 if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) || 4531 SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) { 4532 if (N->getOpcode() != ISD::DELETED_NODE) 4533 DCI.AddToWorklist(N); 4534 return SDValue(N, 0); 4535 } 4536 break; 4537 } 4538 case RISCVISD::FSL: 4539 case RISCVISD::FSR: { 4540 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 4541 SDValue ShAmt = N->getOperand(2); 4542 unsigned BitWidth = ShAmt.getValueSizeInBits(); 4543 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 4544 APInt ShAmtMask(BitWidth, (BitWidth * 2) - 1); 4545 if (SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) { 4546 if (N->getOpcode() != ISD::DELETED_NODE) 4547 DCI.AddToWorklist(N); 4548 return SDValue(N, 0); 4549 } 4550 break; 4551 } 4552 case RISCVISD::FSLW: 4553 case RISCVISD::FSRW: { 4554 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 4555 // read. 4556 SDValue Op0 = N->getOperand(0); 4557 SDValue Op1 = N->getOperand(1); 4558 SDValue ShAmt = N->getOperand(2); 4559 APInt OpMask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32); 4560 APInt ShAmtMask = APInt::getLowBitsSet(ShAmt.getValueSizeInBits(), 6); 4561 if (SimplifyDemandedBits(Op0, OpMask, DCI) || 4562 SimplifyDemandedBits(Op1, OpMask, DCI) || 4563 SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) { 4564 if (N->getOpcode() != ISD::DELETED_NODE) 4565 DCI.AddToWorklist(N); 4566 return SDValue(N, 0); 4567 } 4568 break; 4569 } 4570 case RISCVISD::GREVIW: 4571 case RISCVISD::GORCIW: { 4572 // Only the lower 32 bits of the first operand are read 4573 SDValue Op0 = N->getOperand(0); 4574 APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32); 4575 if (SimplifyDemandedBits(Op0, Mask, DCI)) { 4576 if (N->getOpcode() != ISD::DELETED_NODE) 4577 DCI.AddToWorklist(N); 4578 return SDValue(N, 0); 4579 } 4580 4581 return combineGREVI_GORCI(N, DCI.DAG); 4582 } 4583 case RISCVISD::FMV_X_ANYEXTW_RV64: { 4584 SDLoc DL(N); 4585 SDValue Op0 = N->getOperand(0); 4586 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 4587 // conversion is unnecessary and can be replaced with an ANY_EXTEND 4588 // of the FMV_W_X_RV64 operand. 4589 if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) { 4590 assert(Op0.getOperand(0).getValueType() == MVT::i64 && 4591 "Unexpected value type!"); 4592 return Op0.getOperand(0); 4593 } 4594 4595 // This is a target-specific version of a DAGCombine performed in 4596 // DAGCombiner::visitBITCAST. It performs the equivalent of: 4597 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 4598 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 4599 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 4600 !Op0.getNode()->hasOneUse()) 4601 break; 4602 SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, 4603 Op0.getOperand(0)); 4604 APInt SignBit = APInt::getSignMask(32).sext(64); 4605 if (Op0.getOpcode() == ISD::FNEG) 4606 return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV, 4607 DAG.getConstant(SignBit, DL, MVT::i64)); 4608 4609 assert(Op0.getOpcode() == ISD::FABS); 4610 return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV, 4611 DAG.getConstant(~SignBit, DL, MVT::i64)); 4612 } 4613 case RISCVISD::GREVI: 4614 case RISCVISD::GORCI: 4615 return combineGREVI_GORCI(N, DCI.DAG); 4616 case ISD::OR: 4617 if (auto GREV = combineORToGREV(SDValue(N, 0), DCI.DAG, Subtarget)) 4618 return GREV; 4619 if (auto GORC = combineORToGORC(SDValue(N, 0), DCI.DAG, Subtarget)) 4620 return GORC; 4621 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DCI.DAG, Subtarget)) 4622 return SHFL; 4623 break; 4624 case RISCVISD::SELECT_CC: { 4625 // Transform 4626 SDValue LHS = N->getOperand(0); 4627 SDValue RHS = N->getOperand(1); 4628 auto CCVal = static_cast<ISD::CondCode>(N->getConstantOperandVal(2)); 4629 if (!ISD::isIntEqualitySetCC(CCVal)) 4630 break; 4631 4632 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 4633 // (select_cc X, Y, lt, trueV, falseV) 4634 // Sometimes the setcc is introduced after select_cc has been formed. 4635 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 4636 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 4637 // If we're looking for eq 0 instead of ne 0, we need to invert the 4638 // condition. 4639 bool Invert = CCVal == ISD::SETEQ; 4640 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 4641 if (Invert) 4642 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 4643 4644 SDLoc DL(N); 4645 RHS = LHS.getOperand(1); 4646 LHS = LHS.getOperand(0); 4647 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4648 4649 SDValue TargetCC = DAG.getConstant(CCVal, DL, Subtarget.getXLenVT()); 4650 return DAG.getNode( 4651 RISCVISD::SELECT_CC, DL, N->getValueType(0), 4652 {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)}); 4653 } 4654 4655 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 4656 // (select_cc X, Y, eq/ne, trueV, falseV) 4657 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 4658 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 4659 {LHS.getOperand(0), LHS.getOperand(1), 4660 N->getOperand(2), N->getOperand(3), 4661 N->getOperand(4)}); 4662 // (select_cc X, 1, setne, trueV, falseV) -> 4663 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 4664 // This can occur when legalizing some floating point comparisons. 4665 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 4666 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 4667 SDLoc DL(N); 4668 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 4669 SDValue TargetCC = DAG.getConstant(CCVal, DL, Subtarget.getXLenVT()); 4670 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 4671 return DAG.getNode( 4672 RISCVISD::SELECT_CC, DL, N->getValueType(0), 4673 {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)}); 4674 } 4675 4676 break; 4677 } 4678 case RISCVISD::BR_CC: { 4679 SDValue LHS = N->getOperand(1); 4680 SDValue RHS = N->getOperand(2); 4681 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 4682 if (!ISD::isIntEqualitySetCC(CCVal)) 4683 break; 4684 4685 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 4686 // (br_cc X, Y, lt, dest) 4687 // Sometimes the setcc is introduced after br_cc has been formed. 4688 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 4689 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 4690 // If we're looking for eq 0 instead of ne 0, we need to invert the 4691 // condition. 4692 bool Invert = CCVal == ISD::SETEQ; 4693 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 4694 if (Invert) 4695 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 4696 4697 SDLoc DL(N); 4698 RHS = LHS.getOperand(1); 4699 LHS = LHS.getOperand(0); 4700 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 4701 4702 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 4703 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 4704 N->getOperand(4)); 4705 } 4706 4707 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 4708 // (br_cc X, Y, eq/ne, trueV, falseV) 4709 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 4710 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 4711 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 4712 N->getOperand(3), N->getOperand(4)); 4713 4714 // (br_cc X, 1, setne, br_cc) -> 4715 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 4716 // This can occur when legalizing some floating point comparisons. 4717 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 4718 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 4719 SDLoc DL(N); 4720 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 4721 SDValue TargetCC = DAG.getCondCode(CCVal); 4722 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 4723 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 4724 N->getOperand(0), LHS, RHS, TargetCC, 4725 N->getOperand(4)); 4726 } 4727 break; 4728 } 4729 case ISD::FCOPYSIGN: { 4730 EVT VT = N->getValueType(0); 4731 if (!VT.isVector()) 4732 break; 4733 // There is a form of VFSGNJ which injects the negated sign of its second 4734 // operand. Try and bubble any FNEG up after the extend/round to produce 4735 // this optimized pattern. Avoid modifying cases where FP_ROUND and 4736 // TRUNC=1. 4737 SDValue In2 = N->getOperand(1); 4738 // Avoid cases where the extend/round has multiple uses, as duplicating 4739 // those is typically more expensive than removing a fneg. 4740 if (!In2.hasOneUse()) 4741 break; 4742 if (In2.getOpcode() != ISD::FP_EXTEND && 4743 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 4744 break; 4745 In2 = In2.getOperand(0); 4746 if (In2.getOpcode() != ISD::FNEG) 4747 break; 4748 SDLoc DL(N); 4749 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 4750 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 4751 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 4752 } 4753 case ISD::MGATHER: 4754 case ISD::MSCATTER: { 4755 if (!DCI.isBeforeLegalize()) 4756 break; 4757 MaskedGatherScatterSDNode *MGSN = cast<MaskedGatherScatterSDNode>(N); 4758 SDValue Index = MGSN->getIndex(); 4759 EVT IndexVT = Index.getValueType(); 4760 MVT XLenVT = Subtarget.getXLenVT(); 4761 // RISCV indexed loads only support the "unsigned unscaled" addressing 4762 // mode, so anything else must be manually legalized. 4763 bool NeedsIdxLegalization = MGSN->isIndexScaled() || 4764 (MGSN->isIndexSigned() && 4765 IndexVT.getVectorElementType().bitsLT(XLenVT)); 4766 if (!NeedsIdxLegalization) 4767 break; 4768 4769 SDLoc DL(N); 4770 4771 // Any index legalization should first promote to XLenVT, so we don't lose 4772 // bits when scaling. This may create an illegal index type so we let 4773 // LLVM's legalization take care of the splitting. 4774 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 4775 IndexVT = IndexVT.changeVectorElementType(XLenVT); 4776 Index = DAG.getNode(MGSN->isIndexSigned() ? ISD::SIGN_EXTEND 4777 : ISD::ZERO_EXTEND, 4778 DL, IndexVT, Index); 4779 } 4780 4781 unsigned Scale = N->getConstantOperandVal(5); 4782 if (MGSN->isIndexScaled() && Scale != 1) { 4783 // Manually scale the indices by the element size. 4784 // TODO: Sanitize the scale operand here? 4785 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 4786 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 4787 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 4788 } 4789 4790 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 4791 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) { 4792 return DAG.getMaskedGather( 4793 N->getVTList(), MGSN->getMemoryVT(), DL, 4794 {MGSN->getChain(), MGN->getPassThru(), MGSN->getMask(), 4795 MGSN->getBasePtr(), Index, MGN->getScale()}, 4796 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 4797 } 4798 const auto *MSN = cast<MaskedScatterSDNode>(N); 4799 return DAG.getMaskedScatter( 4800 N->getVTList(), MGSN->getMemoryVT(), DL, 4801 {MGSN->getChain(), MSN->getValue(), MGSN->getMask(), MGSN->getBasePtr(), 4802 Index, MGSN->getScale()}, 4803 MGSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 4804 } 4805 } 4806 4807 return SDValue(); 4808 } 4809 4810 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 4811 const SDNode *N, CombineLevel Level) const { 4812 // The following folds are only desirable if `(OP _, c1 << c2)` can be 4813 // materialised in fewer instructions than `(OP _, c1)`: 4814 // 4815 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4816 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 4817 SDValue N0 = N->getOperand(0); 4818 EVT Ty = N0.getValueType(); 4819 if (Ty.isScalarInteger() && 4820 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 4821 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 4822 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 4823 if (C1 && C2) { 4824 const APInt &C1Int = C1->getAPIntValue(); 4825 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 4826 4827 // We can materialise `c1 << c2` into an add immediate, so it's "free", 4828 // and the combine should happen, to potentially allow further combines 4829 // later. 4830 if (ShiftedC1Int.getMinSignedBits() <= 64 && 4831 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 4832 return true; 4833 4834 // We can materialise `c1` in an add immediate, so it's "free", and the 4835 // combine should be prevented. 4836 if (C1Int.getMinSignedBits() <= 64 && 4837 isLegalAddImmediate(C1Int.getSExtValue())) 4838 return false; 4839 4840 // Neither constant will fit into an immediate, so find materialisation 4841 // costs. 4842 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 4843 Subtarget.is64Bit()); 4844 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 4845 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit()); 4846 4847 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 4848 // combine should be prevented. 4849 if (C1Cost < ShiftedC1Cost) 4850 return false; 4851 } 4852 } 4853 return true; 4854 } 4855 4856 bool RISCVTargetLowering::targetShrinkDemandedConstant( 4857 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 4858 TargetLoweringOpt &TLO) const { 4859 // Delay this optimization as late as possible. 4860 if (!TLO.LegalOps) 4861 return false; 4862 4863 EVT VT = Op.getValueType(); 4864 if (VT.isVector()) 4865 return false; 4866 4867 // Only handle AND for now. 4868 if (Op.getOpcode() != ISD::AND) 4869 return false; 4870 4871 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4872 if (!C) 4873 return false; 4874 4875 const APInt &Mask = C->getAPIntValue(); 4876 4877 // Clear all non-demanded bits initially. 4878 APInt ShrunkMask = Mask & DemandedBits; 4879 4880 // If the shrunk mask fits in sign extended 12 bits, let the target 4881 // independent code apply it. 4882 if (ShrunkMask.isSignedIntN(12)) 4883 return false; 4884 4885 // Try to make a smaller immediate by setting undemanded bits. 4886 4887 // We need to be able to make a negative number through a combination of mask 4888 // and undemanded bits. 4889 APInt ExpandedMask = Mask | ~DemandedBits; 4890 if (!ExpandedMask.isNegative()) 4891 return false; 4892 4893 // What is the fewest number of bits we need to represent the negative number. 4894 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 4895 4896 // Try to make a 12 bit negative immediate. If that fails try to make a 32 4897 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 4898 APInt NewMask = ShrunkMask; 4899 if (MinSignedBits <= 12) 4900 NewMask.setBitsFrom(11); 4901 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 4902 NewMask.setBitsFrom(31); 4903 else 4904 return false; 4905 4906 // Sanity check that our new mask is a subset of the demanded mask. 4907 assert(NewMask.isSubsetOf(ExpandedMask)); 4908 4909 // If we aren't changing the mask, just return true to keep it and prevent 4910 // the caller from optimizing. 4911 if (NewMask == Mask) 4912 return true; 4913 4914 // Replace the constant with the new mask. 4915 SDLoc DL(Op); 4916 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 4917 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 4918 return TLO.CombineTo(Op, NewOp); 4919 } 4920 4921 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 4922 KnownBits &Known, 4923 const APInt &DemandedElts, 4924 const SelectionDAG &DAG, 4925 unsigned Depth) const { 4926 unsigned BitWidth = Known.getBitWidth(); 4927 unsigned Opc = Op.getOpcode(); 4928 assert((Opc >= ISD::BUILTIN_OP_END || 4929 Opc == ISD::INTRINSIC_WO_CHAIN || 4930 Opc == ISD::INTRINSIC_W_CHAIN || 4931 Opc == ISD::INTRINSIC_VOID) && 4932 "Should use MaskedValueIsZero if you don't know whether Op" 4933 " is a target node!"); 4934 4935 Known.resetAll(); 4936 switch (Opc) { 4937 default: break; 4938 case RISCVISD::SELECT_CC: { 4939 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 4940 // If we don't know any bits, early out. 4941 if (Known.isUnknown()) 4942 break; 4943 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 4944 4945 // Only known if known in both the LHS and RHS. 4946 Known = KnownBits::commonBits(Known, Known2); 4947 break; 4948 } 4949 case RISCVISD::REMUW: { 4950 KnownBits Known2; 4951 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4952 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4953 // We only care about the lower 32 bits. 4954 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 4955 // Restore the original width by sign extending. 4956 Known = Known.sext(BitWidth); 4957 break; 4958 } 4959 case RISCVISD::DIVUW: { 4960 KnownBits Known2; 4961 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4962 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4963 // We only care about the lower 32 bits. 4964 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 4965 // Restore the original width by sign extending. 4966 Known = Known.sext(BitWidth); 4967 break; 4968 } 4969 case RISCVISD::READ_VLENB: 4970 // We assume VLENB is at least 8 bytes. 4971 // FIXME: The 1.0 draft spec defines minimum VLEN as 128 bits. 4972 Known.Zero.setLowBits(3); 4973 break; 4974 } 4975 } 4976 4977 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 4978 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 4979 unsigned Depth) const { 4980 switch (Op.getOpcode()) { 4981 default: 4982 break; 4983 case RISCVISD::SLLW: 4984 case RISCVISD::SRAW: 4985 case RISCVISD::SRLW: 4986 case RISCVISD::DIVW: 4987 case RISCVISD::DIVUW: 4988 case RISCVISD::REMUW: 4989 case RISCVISD::ROLW: 4990 case RISCVISD::RORW: 4991 case RISCVISD::GREVIW: 4992 case RISCVISD::GORCIW: 4993 case RISCVISD::FSLW: 4994 case RISCVISD::FSRW: 4995 // TODO: As the result is sign-extended, this is conservatively correct. A 4996 // more precise answer could be calculated for SRAW depending on known 4997 // bits in the shift amount. 4998 return 33; 4999 case RISCVISD::SHFLI: { 5000 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 5001 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 5002 // will stay within the upper 32 bits. If there were more than 32 sign bits 5003 // before there will be at least 33 sign bits after. 5004 if (Op.getValueType() == MVT::i64 && 5005 (Op.getConstantOperandVal(1) & 0x10) == 0) { 5006 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 5007 if (Tmp > 32) 5008 return 33; 5009 } 5010 break; 5011 } 5012 case RISCVISD::VMV_X_S: 5013 // The number of sign bits of the scalar result is computed by obtaining the 5014 // element type of the input vector operand, subtracting its width from the 5015 // XLEN, and then adding one (sign bit within the element type). If the 5016 // element type is wider than XLen, the least-significant XLEN bits are 5017 // taken. 5018 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 5019 return 1; 5020 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 5021 } 5022 5023 return 1; 5024 } 5025 5026 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 5027 MachineBasicBlock *BB) { 5028 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 5029 5030 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 5031 // Should the count have wrapped while it was being read, we need to try 5032 // again. 5033 // ... 5034 // read: 5035 // rdcycleh x3 # load high word of cycle 5036 // rdcycle x2 # load low word of cycle 5037 // rdcycleh x4 # load high word of cycle 5038 // bne x3, x4, read # check if high word reads match, otherwise try again 5039 // ... 5040 5041 MachineFunction &MF = *BB->getParent(); 5042 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 5043 MachineFunction::iterator It = ++BB->getIterator(); 5044 5045 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 5046 MF.insert(It, LoopMBB); 5047 5048 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 5049 MF.insert(It, DoneMBB); 5050 5051 // Transfer the remainder of BB and its successor edges to DoneMBB. 5052 DoneMBB->splice(DoneMBB->begin(), BB, 5053 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 5054 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 5055 5056 BB->addSuccessor(LoopMBB); 5057 5058 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5059 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 5060 Register LoReg = MI.getOperand(0).getReg(); 5061 Register HiReg = MI.getOperand(1).getReg(); 5062 DebugLoc DL = MI.getDebugLoc(); 5063 5064 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 5065 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 5066 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 5067 .addReg(RISCV::X0); 5068 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 5069 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 5070 .addReg(RISCV::X0); 5071 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 5072 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 5073 .addReg(RISCV::X0); 5074 5075 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 5076 .addReg(HiReg) 5077 .addReg(ReadAgainReg) 5078 .addMBB(LoopMBB); 5079 5080 LoopMBB->addSuccessor(LoopMBB); 5081 LoopMBB->addSuccessor(DoneMBB); 5082 5083 MI.eraseFromParent(); 5084 5085 return DoneMBB; 5086 } 5087 5088 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 5089 MachineBasicBlock *BB) { 5090 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 5091 5092 MachineFunction &MF = *BB->getParent(); 5093 DebugLoc DL = MI.getDebugLoc(); 5094 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 5095 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 5096 Register LoReg = MI.getOperand(0).getReg(); 5097 Register HiReg = MI.getOperand(1).getReg(); 5098 Register SrcReg = MI.getOperand(2).getReg(); 5099 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 5100 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 5101 5102 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 5103 RI); 5104 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 5105 MachineMemOperand *MMOLo = 5106 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 5107 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 5108 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 5109 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 5110 .addFrameIndex(FI) 5111 .addImm(0) 5112 .addMemOperand(MMOLo); 5113 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 5114 .addFrameIndex(FI) 5115 .addImm(4) 5116 .addMemOperand(MMOHi); 5117 MI.eraseFromParent(); // The pseudo instruction is gone now. 5118 return BB; 5119 } 5120 5121 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 5122 MachineBasicBlock *BB) { 5123 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 5124 "Unexpected instruction"); 5125 5126 MachineFunction &MF = *BB->getParent(); 5127 DebugLoc DL = MI.getDebugLoc(); 5128 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 5129 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 5130 Register DstReg = MI.getOperand(0).getReg(); 5131 Register LoReg = MI.getOperand(1).getReg(); 5132 Register HiReg = MI.getOperand(2).getReg(); 5133 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 5134 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 5135 5136 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 5137 MachineMemOperand *MMOLo = 5138 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 5139 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 5140 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 5141 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 5142 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 5143 .addFrameIndex(FI) 5144 .addImm(0) 5145 .addMemOperand(MMOLo); 5146 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 5147 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 5148 .addFrameIndex(FI) 5149 .addImm(4) 5150 .addMemOperand(MMOHi); 5151 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 5152 MI.eraseFromParent(); // The pseudo instruction is gone now. 5153 return BB; 5154 } 5155 5156 static bool isSelectPseudo(MachineInstr &MI) { 5157 switch (MI.getOpcode()) { 5158 default: 5159 return false; 5160 case RISCV::Select_GPR_Using_CC_GPR: 5161 case RISCV::Select_FPR16_Using_CC_GPR: 5162 case RISCV::Select_FPR32_Using_CC_GPR: 5163 case RISCV::Select_FPR64_Using_CC_GPR: 5164 return true; 5165 } 5166 } 5167 5168 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 5169 MachineBasicBlock *BB) { 5170 // To "insert" Select_* instructions, we actually have to insert the triangle 5171 // control-flow pattern. The incoming instructions know the destination vreg 5172 // to set, the condition code register to branch on, the true/false values to 5173 // select between, and the condcode to use to select the appropriate branch. 5174 // 5175 // We produce the following control flow: 5176 // HeadMBB 5177 // | \ 5178 // | IfFalseMBB 5179 // | / 5180 // TailMBB 5181 // 5182 // When we find a sequence of selects we attempt to optimize their emission 5183 // by sharing the control flow. Currently we only handle cases where we have 5184 // multiple selects with the exact same condition (same LHS, RHS and CC). 5185 // The selects may be interleaved with other instructions if the other 5186 // instructions meet some requirements we deem safe: 5187 // - They are debug instructions. Otherwise, 5188 // - They do not have side-effects, do not access memory and their inputs do 5189 // not depend on the results of the select pseudo-instructions. 5190 // The TrueV/FalseV operands of the selects cannot depend on the result of 5191 // previous selects in the sequence. 5192 // These conditions could be further relaxed. See the X86 target for a 5193 // related approach and more information. 5194 Register LHS = MI.getOperand(1).getReg(); 5195 Register RHS = MI.getOperand(2).getReg(); 5196 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm()); 5197 5198 SmallVector<MachineInstr *, 4> SelectDebugValues; 5199 SmallSet<Register, 4> SelectDests; 5200 SelectDests.insert(MI.getOperand(0).getReg()); 5201 5202 MachineInstr *LastSelectPseudo = &MI; 5203 5204 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 5205 SequenceMBBI != E; ++SequenceMBBI) { 5206 if (SequenceMBBI->isDebugInstr()) 5207 continue; 5208 else if (isSelectPseudo(*SequenceMBBI)) { 5209 if (SequenceMBBI->getOperand(1).getReg() != LHS || 5210 SequenceMBBI->getOperand(2).getReg() != RHS || 5211 SequenceMBBI->getOperand(3).getImm() != CC || 5212 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 5213 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 5214 break; 5215 LastSelectPseudo = &*SequenceMBBI; 5216 SequenceMBBI->collectDebugValues(SelectDebugValues); 5217 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 5218 } else { 5219 if (SequenceMBBI->hasUnmodeledSideEffects() || 5220 SequenceMBBI->mayLoadOrStore()) 5221 break; 5222 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 5223 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 5224 })) 5225 break; 5226 } 5227 } 5228 5229 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 5230 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 5231 DebugLoc DL = MI.getDebugLoc(); 5232 MachineFunction::iterator I = ++BB->getIterator(); 5233 5234 MachineBasicBlock *HeadMBB = BB; 5235 MachineFunction *F = BB->getParent(); 5236 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 5237 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 5238 5239 F->insert(I, IfFalseMBB); 5240 F->insert(I, TailMBB); 5241 5242 // Transfer debug instructions associated with the selects to TailMBB. 5243 for (MachineInstr *DebugInstr : SelectDebugValues) { 5244 TailMBB->push_back(DebugInstr->removeFromParent()); 5245 } 5246 5247 // Move all instructions after the sequence to TailMBB. 5248 TailMBB->splice(TailMBB->end(), HeadMBB, 5249 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 5250 // Update machine-CFG edges by transferring all successors of the current 5251 // block to the new block which will contain the Phi nodes for the selects. 5252 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 5253 // Set the successors for HeadMBB. 5254 HeadMBB->addSuccessor(IfFalseMBB); 5255 HeadMBB->addSuccessor(TailMBB); 5256 5257 // Insert appropriate branch. 5258 unsigned Opcode = getBranchOpcodeForIntCondCode(CC); 5259 5260 BuildMI(HeadMBB, DL, TII.get(Opcode)) 5261 .addReg(LHS) 5262 .addReg(RHS) 5263 .addMBB(TailMBB); 5264 5265 // IfFalseMBB just falls through to TailMBB. 5266 IfFalseMBB->addSuccessor(TailMBB); 5267 5268 // Create PHIs for all of the select pseudo-instructions. 5269 auto SelectMBBI = MI.getIterator(); 5270 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 5271 auto InsertionPoint = TailMBB->begin(); 5272 while (SelectMBBI != SelectEnd) { 5273 auto Next = std::next(SelectMBBI); 5274 if (isSelectPseudo(*SelectMBBI)) { 5275 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 5276 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 5277 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 5278 .addReg(SelectMBBI->getOperand(4).getReg()) 5279 .addMBB(HeadMBB) 5280 .addReg(SelectMBBI->getOperand(5).getReg()) 5281 .addMBB(IfFalseMBB); 5282 SelectMBBI->eraseFromParent(); 5283 } 5284 SelectMBBI = Next; 5285 } 5286 5287 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 5288 return TailMBB; 5289 } 5290 5291 static MachineInstr *elideCopies(MachineInstr *MI, 5292 const MachineRegisterInfo &MRI) { 5293 while (true) { 5294 if (!MI->isFullCopy()) 5295 return MI; 5296 if (!Register::isVirtualRegister(MI->getOperand(1).getReg())) 5297 return nullptr; 5298 MI = MRI.getVRegDef(MI->getOperand(1).getReg()); 5299 if (!MI) 5300 return nullptr; 5301 } 5302 } 5303 5304 static MachineBasicBlock *addVSetVL(MachineInstr &MI, MachineBasicBlock *BB, 5305 int VLIndex, unsigned SEWIndex, 5306 RISCVVLMUL VLMul, bool ForceTailAgnostic) { 5307 MachineFunction &MF = *BB->getParent(); 5308 DebugLoc DL = MI.getDebugLoc(); 5309 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 5310 5311 unsigned SEW = MI.getOperand(SEWIndex).getImm(); 5312 assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW"); 5313 RISCVVSEW ElementWidth = static_cast<RISCVVSEW>(Log2_32(SEW / 8)); 5314 5315 MachineRegisterInfo &MRI = MF.getRegInfo(); 5316 5317 auto BuildVSETVLI = [&]() { 5318 if (VLIndex >= 0) { 5319 Register DestReg = MRI.createVirtualRegister(&RISCV::GPRRegClass); 5320 Register VLReg = MI.getOperand(VLIndex).getReg(); 5321 5322 // VL might be a compile time constant, but isel would have to put it 5323 // in a register. See if VL comes from an ADDI X0, imm. 5324 if (VLReg.isVirtual()) { 5325 MachineInstr *Def = MRI.getVRegDef(VLReg); 5326 if (Def && Def->getOpcode() == RISCV::ADDI && 5327 Def->getOperand(1).getReg() == RISCV::X0 && 5328 Def->getOperand(2).isImm()) { 5329 uint64_t Imm = Def->getOperand(2).getImm(); 5330 // VSETIVLI allows a 5-bit zero extended immediate. 5331 if (isUInt<5>(Imm)) 5332 return BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETIVLI)) 5333 .addReg(DestReg, RegState::Define | RegState::Dead) 5334 .addImm(Imm); 5335 } 5336 } 5337 5338 return BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI)) 5339 .addReg(DestReg, RegState::Define | RegState::Dead) 5340 .addReg(VLReg); 5341 } 5342 5343 // With no VL operator in the pseudo, do not modify VL (rd = X0, rs1 = X0). 5344 return BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI)) 5345 .addReg(RISCV::X0, RegState::Define | RegState::Dead) 5346 .addReg(RISCV::X0, RegState::Kill); 5347 }; 5348 5349 MachineInstrBuilder MIB = BuildVSETVLI(); 5350 5351 // Default to tail agnostic unless the destination is tied to a source. In 5352 // that case the user would have some control over the tail values. The tail 5353 // policy is also ignored on instructions that only update element 0 like 5354 // vmv.s.x or reductions so use agnostic there to match the common case. 5355 // FIXME: This is conservatively correct, but we might want to detect that 5356 // the input is undefined. 5357 bool TailAgnostic = true; 5358 unsigned UseOpIdx; 5359 if (!ForceTailAgnostic && MI.isRegTiedToUseOperand(0, &UseOpIdx)) { 5360 TailAgnostic = false; 5361 // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic. 5362 const MachineOperand &UseMO = MI.getOperand(UseOpIdx); 5363 MachineInstr *UseMI = MRI.getVRegDef(UseMO.getReg()); 5364 if (UseMI) { 5365 UseMI = elideCopies(UseMI, MRI); 5366 if (UseMI && UseMI->isImplicitDef()) 5367 TailAgnostic = true; 5368 } 5369 } 5370 5371 // For simplicity we reuse the vtype representation here. 5372 MIB.addImm(RISCVVType::encodeVTYPE(VLMul, ElementWidth, 5373 /*TailAgnostic*/ TailAgnostic, 5374 /*MaskAgnostic*/ false)); 5375 5376 // Remove (now) redundant operands from pseudo 5377 if (VLIndex >= 0) { 5378 MI.getOperand(VLIndex).setReg(RISCV::NoRegister); 5379 MI.getOperand(VLIndex).setIsKill(false); 5380 } 5381 5382 return BB; 5383 } 5384 5385 MachineBasicBlock * 5386 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 5387 MachineBasicBlock *BB) const { 5388 uint64_t TSFlags = MI.getDesc().TSFlags; 5389 5390 if (TSFlags & RISCVII::HasSEWOpMask) { 5391 unsigned NumOperands = MI.getNumExplicitOperands(); 5392 int VLIndex = (TSFlags & RISCVII::HasVLOpMask) ? NumOperands - 2 : -1; 5393 unsigned SEWIndex = NumOperands - 1; 5394 bool ForceTailAgnostic = TSFlags & RISCVII::ForceTailAgnosticMask; 5395 5396 RISCVVLMUL VLMul = static_cast<RISCVVLMUL>((TSFlags & RISCVII::VLMulMask) >> 5397 RISCVII::VLMulShift); 5398 return addVSetVL(MI, BB, VLIndex, SEWIndex, VLMul, ForceTailAgnostic); 5399 } 5400 5401 switch (MI.getOpcode()) { 5402 default: 5403 llvm_unreachable("Unexpected instr type to insert"); 5404 case RISCV::ReadCycleWide: 5405 assert(!Subtarget.is64Bit() && 5406 "ReadCycleWrite is only to be used on riscv32"); 5407 return emitReadCycleWidePseudo(MI, BB); 5408 case RISCV::Select_GPR_Using_CC_GPR: 5409 case RISCV::Select_FPR16_Using_CC_GPR: 5410 case RISCV::Select_FPR32_Using_CC_GPR: 5411 case RISCV::Select_FPR64_Using_CC_GPR: 5412 return emitSelectPseudo(MI, BB); 5413 case RISCV::BuildPairF64Pseudo: 5414 return emitBuildPairF64Pseudo(MI, BB); 5415 case RISCV::SplitF64Pseudo: 5416 return emitSplitF64Pseudo(MI, BB); 5417 } 5418 } 5419 5420 // Calling Convention Implementation. 5421 // The expectations for frontend ABI lowering vary from target to target. 5422 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 5423 // details, but this is a longer term goal. For now, we simply try to keep the 5424 // role of the frontend as simple and well-defined as possible. The rules can 5425 // be summarised as: 5426 // * Never split up large scalar arguments. We handle them here. 5427 // * If a hardfloat calling convention is being used, and the struct may be 5428 // passed in a pair of registers (fp+fp, int+fp), and both registers are 5429 // available, then pass as two separate arguments. If either the GPRs or FPRs 5430 // are exhausted, then pass according to the rule below. 5431 // * If a struct could never be passed in registers or directly in a stack 5432 // slot (as it is larger than 2*XLEN and the floating point rules don't 5433 // apply), then pass it using a pointer with the byval attribute. 5434 // * If a struct is less than 2*XLEN, then coerce to either a two-element 5435 // word-sized array or a 2*XLEN scalar (depending on alignment). 5436 // * The frontend can determine whether a struct is returned by reference or 5437 // not based on its size and fields. If it will be returned by reference, the 5438 // frontend must modify the prototype so a pointer with the sret annotation is 5439 // passed as the first argument. This is not necessary for large scalar 5440 // returns. 5441 // * Struct return values and varargs should be coerced to structs containing 5442 // register-size fields in the same situations they would be for fixed 5443 // arguments. 5444 5445 static const MCPhysReg ArgGPRs[] = { 5446 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 5447 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 5448 }; 5449 static const MCPhysReg ArgFPR16s[] = { 5450 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 5451 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 5452 }; 5453 static const MCPhysReg ArgFPR32s[] = { 5454 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 5455 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 5456 }; 5457 static const MCPhysReg ArgFPR64s[] = { 5458 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 5459 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 5460 }; 5461 // This is an interim calling convention and it may be changed in the future. 5462 static const MCPhysReg ArgVRs[] = { 5463 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 5464 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 5465 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 5466 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 5467 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 5468 RISCV::V20M2, RISCV::V22M2}; 5469 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 5470 RISCV::V20M4}; 5471 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 5472 5473 // Pass a 2*XLEN argument that has been split into two XLEN values through 5474 // registers or the stack as necessary. 5475 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 5476 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 5477 MVT ValVT2, MVT LocVT2, 5478 ISD::ArgFlagsTy ArgFlags2) { 5479 unsigned XLenInBytes = XLen / 8; 5480 if (Register Reg = State.AllocateReg(ArgGPRs)) { 5481 // At least one half can be passed via register. 5482 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 5483 VA1.getLocVT(), CCValAssign::Full)); 5484 } else { 5485 // Both halves must be passed on the stack, with proper alignment. 5486 Align StackAlign = 5487 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 5488 State.addLoc( 5489 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 5490 State.AllocateStack(XLenInBytes, StackAlign), 5491 VA1.getLocVT(), CCValAssign::Full)); 5492 State.addLoc(CCValAssign::getMem( 5493 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 5494 LocVT2, CCValAssign::Full)); 5495 return false; 5496 } 5497 5498 if (Register Reg = State.AllocateReg(ArgGPRs)) { 5499 // The second half can also be passed via register. 5500 State.addLoc( 5501 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 5502 } else { 5503 // The second half is passed via the stack, without additional alignment. 5504 State.addLoc(CCValAssign::getMem( 5505 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 5506 LocVT2, CCValAssign::Full)); 5507 } 5508 5509 return false; 5510 } 5511 5512 // Implements the RISC-V calling convention. Returns true upon failure. 5513 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 5514 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 5515 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 5516 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 5517 Optional<unsigned> FirstMaskArgument) { 5518 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 5519 assert(XLen == 32 || XLen == 64); 5520 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 5521 5522 // Any return value split in to more than two values can't be returned 5523 // directly. Vectors are returned via the available vector registers. 5524 if (!LocVT.isVector() && IsRet && ValNo > 1) 5525 return true; 5526 5527 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 5528 // variadic argument, or if no F16/F32 argument registers are available. 5529 bool UseGPRForF16_F32 = true; 5530 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 5531 // variadic argument, or if no F64 argument registers are available. 5532 bool UseGPRForF64 = true; 5533 5534 switch (ABI) { 5535 default: 5536 llvm_unreachable("Unexpected ABI"); 5537 case RISCVABI::ABI_ILP32: 5538 case RISCVABI::ABI_LP64: 5539 break; 5540 case RISCVABI::ABI_ILP32F: 5541 case RISCVABI::ABI_LP64F: 5542 UseGPRForF16_F32 = !IsFixed; 5543 break; 5544 case RISCVABI::ABI_ILP32D: 5545 case RISCVABI::ABI_LP64D: 5546 UseGPRForF16_F32 = !IsFixed; 5547 UseGPRForF64 = !IsFixed; 5548 break; 5549 } 5550 5551 // FPR16, FPR32, and FPR64 alias each other. 5552 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 5553 UseGPRForF16_F32 = true; 5554 UseGPRForF64 = true; 5555 } 5556 5557 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 5558 // similar local variables rather than directly checking against the target 5559 // ABI. 5560 5561 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 5562 LocVT = XLenVT; 5563 LocInfo = CCValAssign::BCvt; 5564 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 5565 LocVT = MVT::i64; 5566 LocInfo = CCValAssign::BCvt; 5567 } 5568 5569 // If this is a variadic argument, the RISC-V calling convention requires 5570 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 5571 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 5572 // be used regardless of whether the original argument was split during 5573 // legalisation or not. The argument will not be passed by registers if the 5574 // original type is larger than 2*XLEN, so the register alignment rule does 5575 // not apply. 5576 unsigned TwoXLenInBytes = (2 * XLen) / 8; 5577 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 5578 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 5579 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 5580 // Skip 'odd' register if necessary. 5581 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 5582 State.AllocateReg(ArgGPRs); 5583 } 5584 5585 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 5586 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 5587 State.getPendingArgFlags(); 5588 5589 assert(PendingLocs.size() == PendingArgFlags.size() && 5590 "PendingLocs and PendingArgFlags out of sync"); 5591 5592 // Handle passing f64 on RV32D with a soft float ABI or when floating point 5593 // registers are exhausted. 5594 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 5595 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 5596 "Can't lower f64 if it is split"); 5597 // Depending on available argument GPRS, f64 may be passed in a pair of 5598 // GPRs, split between a GPR and the stack, or passed completely on the 5599 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 5600 // cases. 5601 Register Reg = State.AllocateReg(ArgGPRs); 5602 LocVT = MVT::i32; 5603 if (!Reg) { 5604 unsigned StackOffset = State.AllocateStack(8, Align(8)); 5605 State.addLoc( 5606 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 5607 return false; 5608 } 5609 if (!State.AllocateReg(ArgGPRs)) 5610 State.AllocateStack(4, Align(4)); 5611 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 5612 return false; 5613 } 5614 5615 // Fixed-length vectors are located in the corresponding scalable-vector 5616 // container types. 5617 if (ValVT.isFixedLengthVector()) 5618 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 5619 5620 // Split arguments might be passed indirectly, so keep track of the pending 5621 // values. Split vectors are passed via a mix of registers and indirectly, so 5622 // treat them as we would any other argument. 5623 if (!LocVT.isVector() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 5624 LocVT = XLenVT; 5625 LocInfo = CCValAssign::Indirect; 5626 PendingLocs.push_back( 5627 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 5628 PendingArgFlags.push_back(ArgFlags); 5629 if (!ArgFlags.isSplitEnd()) { 5630 return false; 5631 } 5632 } 5633 5634 // If the split argument only had two elements, it should be passed directly 5635 // in registers or on the stack. 5636 if (!LocVT.isVector() && ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) { 5637 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 5638 // Apply the normal calling convention rules to the first half of the 5639 // split argument. 5640 CCValAssign VA = PendingLocs[0]; 5641 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 5642 PendingLocs.clear(); 5643 PendingArgFlags.clear(); 5644 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 5645 ArgFlags); 5646 } 5647 5648 // Allocate to a register if possible, or else a stack slot. 5649 Register Reg; 5650 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 5651 Reg = State.AllocateReg(ArgFPR16s); 5652 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 5653 Reg = State.AllocateReg(ArgFPR32s); 5654 else if (ValVT == MVT::f64 && !UseGPRForF64) 5655 Reg = State.AllocateReg(ArgFPR64s); 5656 else if (ValVT.isVector()) { 5657 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 5658 if (RC == &RISCV::VRRegClass) { 5659 // Assign the first mask argument to V0. 5660 // This is an interim calling convention and it may be changed in the 5661 // future. 5662 if (FirstMaskArgument.hasValue() && 5663 ValNo == FirstMaskArgument.getValue()) { 5664 Reg = State.AllocateReg(RISCV::V0); 5665 } else { 5666 Reg = State.AllocateReg(ArgVRs); 5667 } 5668 } else if (RC == &RISCV::VRM2RegClass) { 5669 Reg = State.AllocateReg(ArgVRM2s); 5670 } else if (RC == &RISCV::VRM4RegClass) { 5671 Reg = State.AllocateReg(ArgVRM4s); 5672 } else if (RC == &RISCV::VRM8RegClass) { 5673 Reg = State.AllocateReg(ArgVRM8s); 5674 } else { 5675 llvm_unreachable("Unhandled class register for ValueType"); 5676 } 5677 if (!Reg) { 5678 // For return values, the vector must be passed fully via registers or 5679 // via the stack. 5680 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 5681 // but we're using all of them. 5682 if (IsRet) 5683 return true; 5684 LocInfo = CCValAssign::Indirect; 5685 // Try using a GPR to pass the address 5686 Reg = State.AllocateReg(ArgGPRs); 5687 LocVT = XLenVT; 5688 } 5689 } else 5690 Reg = State.AllocateReg(ArgGPRs); 5691 unsigned StackOffset = 5692 Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8)); 5693 5694 // If we reach this point and PendingLocs is non-empty, we must be at the 5695 // end of a split argument that must be passed indirectly. 5696 if (!PendingLocs.empty()) { 5697 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 5698 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 5699 5700 for (auto &It : PendingLocs) { 5701 if (Reg) 5702 It.convertToReg(Reg); 5703 else 5704 It.convertToMem(StackOffset); 5705 State.addLoc(It); 5706 } 5707 PendingLocs.clear(); 5708 PendingArgFlags.clear(); 5709 return false; 5710 } 5711 5712 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 5713 (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) && 5714 "Expected an XLenVT or vector types at this stage"); 5715 5716 if (Reg) { 5717 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 5718 return false; 5719 } 5720 5721 // When a floating-point value is passed on the stack, no bit-conversion is 5722 // needed. 5723 if (ValVT.isFloatingPoint()) { 5724 LocVT = ValVT; 5725 LocInfo = CCValAssign::Full; 5726 } 5727 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 5728 return false; 5729 } 5730 5731 template <typename ArgTy> 5732 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 5733 for (const auto &ArgIdx : enumerate(Args)) { 5734 MVT ArgVT = ArgIdx.value().VT; 5735 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 5736 return ArgIdx.index(); 5737 } 5738 return None; 5739 } 5740 5741 void RISCVTargetLowering::analyzeInputArgs( 5742 MachineFunction &MF, CCState &CCInfo, 5743 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const { 5744 unsigned NumArgs = Ins.size(); 5745 FunctionType *FType = MF.getFunction().getFunctionType(); 5746 5747 Optional<unsigned> FirstMaskArgument; 5748 if (Subtarget.hasStdExtV()) 5749 FirstMaskArgument = preAssignMask(Ins); 5750 5751 for (unsigned i = 0; i != NumArgs; ++i) { 5752 MVT ArgVT = Ins[i].VT; 5753 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 5754 5755 Type *ArgTy = nullptr; 5756 if (IsRet) 5757 ArgTy = FType->getReturnType(); 5758 else if (Ins[i].isOrigArg()) 5759 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 5760 5761 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 5762 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 5763 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 5764 FirstMaskArgument)) { 5765 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 5766 << EVT(ArgVT).getEVTString() << '\n'); 5767 llvm_unreachable(nullptr); 5768 } 5769 } 5770 } 5771 5772 void RISCVTargetLowering::analyzeOutputArgs( 5773 MachineFunction &MF, CCState &CCInfo, 5774 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 5775 CallLoweringInfo *CLI) const { 5776 unsigned NumArgs = Outs.size(); 5777 5778 Optional<unsigned> FirstMaskArgument; 5779 if (Subtarget.hasStdExtV()) 5780 FirstMaskArgument = preAssignMask(Outs); 5781 5782 for (unsigned i = 0; i != NumArgs; i++) { 5783 MVT ArgVT = Outs[i].VT; 5784 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5785 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 5786 5787 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 5788 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 5789 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 5790 FirstMaskArgument)) { 5791 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 5792 << EVT(ArgVT).getEVTString() << "\n"); 5793 llvm_unreachable(nullptr); 5794 } 5795 } 5796 } 5797 5798 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 5799 // values. 5800 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 5801 const CCValAssign &VA, const SDLoc &DL, 5802 const RISCVSubtarget &Subtarget) { 5803 switch (VA.getLocInfo()) { 5804 default: 5805 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 5806 case CCValAssign::Full: 5807 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 5808 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 5809 break; 5810 case CCValAssign::BCvt: 5811 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 5812 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 5813 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 5814 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 5815 else 5816 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 5817 break; 5818 } 5819 return Val; 5820 } 5821 5822 // The caller is responsible for loading the full value if the argument is 5823 // passed with CCValAssign::Indirect. 5824 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 5825 const CCValAssign &VA, const SDLoc &DL, 5826 const RISCVTargetLowering &TLI) { 5827 MachineFunction &MF = DAG.getMachineFunction(); 5828 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5829 EVT LocVT = VA.getLocVT(); 5830 SDValue Val; 5831 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 5832 Register VReg = RegInfo.createVirtualRegister(RC); 5833 RegInfo.addLiveIn(VA.getLocReg(), VReg); 5834 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 5835 5836 if (VA.getLocInfo() == CCValAssign::Indirect) 5837 return Val; 5838 5839 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 5840 } 5841 5842 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 5843 const CCValAssign &VA, const SDLoc &DL, 5844 const RISCVSubtarget &Subtarget) { 5845 EVT LocVT = VA.getLocVT(); 5846 5847 switch (VA.getLocInfo()) { 5848 default: 5849 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 5850 case CCValAssign::Full: 5851 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 5852 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 5853 break; 5854 case CCValAssign::BCvt: 5855 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 5856 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 5857 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 5858 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 5859 else 5860 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 5861 break; 5862 } 5863 return Val; 5864 } 5865 5866 // The caller is responsible for loading the full value if the argument is 5867 // passed with CCValAssign::Indirect. 5868 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 5869 const CCValAssign &VA, const SDLoc &DL) { 5870 MachineFunction &MF = DAG.getMachineFunction(); 5871 MachineFrameInfo &MFI = MF.getFrameInfo(); 5872 EVT LocVT = VA.getLocVT(); 5873 EVT ValVT = VA.getValVT(); 5874 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 5875 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8, 5876 VA.getLocMemOffset(), /*Immutable=*/true); 5877 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 5878 SDValue Val; 5879 5880 ISD::LoadExtType ExtType; 5881 switch (VA.getLocInfo()) { 5882 default: 5883 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 5884 case CCValAssign::Full: 5885 case CCValAssign::Indirect: 5886 case CCValAssign::BCvt: 5887 ExtType = ISD::NON_EXTLOAD; 5888 break; 5889 } 5890 Val = DAG.getExtLoad( 5891 ExtType, DL, LocVT, Chain, FIN, 5892 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 5893 return Val; 5894 } 5895 5896 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 5897 const CCValAssign &VA, const SDLoc &DL) { 5898 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 5899 "Unexpected VA"); 5900 MachineFunction &MF = DAG.getMachineFunction(); 5901 MachineFrameInfo &MFI = MF.getFrameInfo(); 5902 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5903 5904 if (VA.isMemLoc()) { 5905 // f64 is passed on the stack. 5906 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 5907 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 5908 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 5909 MachinePointerInfo::getFixedStack(MF, FI)); 5910 } 5911 5912 assert(VA.isRegLoc() && "Expected register VA assignment"); 5913 5914 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 5915 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 5916 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 5917 SDValue Hi; 5918 if (VA.getLocReg() == RISCV::X17) { 5919 // Second half of f64 is passed on the stack. 5920 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 5921 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 5922 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 5923 MachinePointerInfo::getFixedStack(MF, FI)); 5924 } else { 5925 // Second half of f64 is passed in another GPR. 5926 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 5927 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 5928 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 5929 } 5930 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 5931 } 5932 5933 // FastCC has less than 1% performance improvement for some particular 5934 // benchmark. But theoretically, it may has benenfit for some cases. 5935 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT, 5936 CCValAssign::LocInfo LocInfo, 5937 ISD::ArgFlagsTy ArgFlags, CCState &State) { 5938 5939 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 5940 // X5 and X6 might be used for save-restore libcall. 5941 static const MCPhysReg GPRList[] = { 5942 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 5943 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 5944 RISCV::X29, RISCV::X30, RISCV::X31}; 5945 if (unsigned Reg = State.AllocateReg(GPRList)) { 5946 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 5947 return false; 5948 } 5949 } 5950 5951 if (LocVT == MVT::f16) { 5952 static const MCPhysReg FPR16List[] = { 5953 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 5954 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 5955 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 5956 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 5957 if (unsigned Reg = State.AllocateReg(FPR16List)) { 5958 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 5959 return false; 5960 } 5961 } 5962 5963 if (LocVT == MVT::f32) { 5964 static const MCPhysReg FPR32List[] = { 5965 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 5966 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 5967 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 5968 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 5969 if (unsigned Reg = State.AllocateReg(FPR32List)) { 5970 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 5971 return false; 5972 } 5973 } 5974 5975 if (LocVT == MVT::f64) { 5976 static const MCPhysReg FPR64List[] = { 5977 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 5978 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 5979 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 5980 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 5981 if (unsigned Reg = State.AllocateReg(FPR64List)) { 5982 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 5983 return false; 5984 } 5985 } 5986 5987 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 5988 unsigned Offset4 = State.AllocateStack(4, Align(4)); 5989 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 5990 return false; 5991 } 5992 5993 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 5994 unsigned Offset5 = State.AllocateStack(8, Align(8)); 5995 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 5996 return false; 5997 } 5998 5999 return true; // CC didn't match. 6000 } 6001 6002 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 6003 CCValAssign::LocInfo LocInfo, 6004 ISD::ArgFlagsTy ArgFlags, CCState &State) { 6005 6006 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 6007 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 6008 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 6009 static const MCPhysReg GPRList[] = { 6010 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 6011 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 6012 if (unsigned Reg = State.AllocateReg(GPRList)) { 6013 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 6014 return false; 6015 } 6016 } 6017 6018 if (LocVT == MVT::f32) { 6019 // Pass in STG registers: F1, ..., F6 6020 // fs0 ... fs5 6021 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 6022 RISCV::F18_F, RISCV::F19_F, 6023 RISCV::F20_F, RISCV::F21_F}; 6024 if (unsigned Reg = State.AllocateReg(FPR32List)) { 6025 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 6026 return false; 6027 } 6028 } 6029 6030 if (LocVT == MVT::f64) { 6031 // Pass in STG registers: D1, ..., D6 6032 // fs6 ... fs11 6033 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 6034 RISCV::F24_D, RISCV::F25_D, 6035 RISCV::F26_D, RISCV::F27_D}; 6036 if (unsigned Reg = State.AllocateReg(FPR64List)) { 6037 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 6038 return false; 6039 } 6040 } 6041 6042 report_fatal_error("No registers left in GHC calling convention"); 6043 return true; 6044 } 6045 6046 // Transform physical registers into virtual registers. 6047 SDValue RISCVTargetLowering::LowerFormalArguments( 6048 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 6049 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 6050 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6051 6052 MachineFunction &MF = DAG.getMachineFunction(); 6053 6054 switch (CallConv) { 6055 default: 6056 report_fatal_error("Unsupported calling convention"); 6057 case CallingConv::C: 6058 case CallingConv::Fast: 6059 break; 6060 case CallingConv::GHC: 6061 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 6062 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 6063 report_fatal_error( 6064 "GHC calling convention requires the F and D instruction set extensions"); 6065 } 6066 6067 const Function &Func = MF.getFunction(); 6068 if (Func.hasFnAttribute("interrupt")) { 6069 if (!Func.arg_empty()) 6070 report_fatal_error( 6071 "Functions with the interrupt attribute cannot have arguments!"); 6072 6073 StringRef Kind = 6074 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 6075 6076 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 6077 report_fatal_error( 6078 "Function interrupt attribute argument not supported!"); 6079 } 6080 6081 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6082 MVT XLenVT = Subtarget.getXLenVT(); 6083 unsigned XLenInBytes = Subtarget.getXLen() / 8; 6084 // Used with vargs to acumulate store chains. 6085 std::vector<SDValue> OutChains; 6086 6087 // Assign locations to all of the incoming arguments. 6088 SmallVector<CCValAssign, 16> ArgLocs; 6089 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 6090 6091 if (CallConv == CallingConv::Fast) 6092 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC); 6093 else if (CallConv == CallingConv::GHC) 6094 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 6095 else 6096 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false); 6097 6098 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 6099 CCValAssign &VA = ArgLocs[i]; 6100 SDValue ArgValue; 6101 // Passing f64 on RV32D with a soft float ABI must be handled as a special 6102 // case. 6103 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 6104 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 6105 else if (VA.isRegLoc()) 6106 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 6107 else 6108 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 6109 6110 if (VA.getLocInfo() == CCValAssign::Indirect) { 6111 // If the original argument was split and passed by reference (e.g. i128 6112 // on RV32), we need to load all parts of it here (using the same 6113 // address). Vectors may be partly split to registers and partly to the 6114 // stack, in which case the base address is partly offset and subsequent 6115 // stores are relative to that. 6116 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 6117 MachinePointerInfo())); 6118 unsigned ArgIndex = Ins[i].OrigArgIndex; 6119 unsigned ArgPartOffset = Ins[i].PartOffset; 6120 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 6121 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 6122 CCValAssign &PartVA = ArgLocs[i + 1]; 6123 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 6124 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, 6125 DAG.getIntPtrConstant(PartOffset, DL)); 6126 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 6127 MachinePointerInfo())); 6128 ++i; 6129 } 6130 continue; 6131 } 6132 InVals.push_back(ArgValue); 6133 } 6134 6135 if (IsVarArg) { 6136 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 6137 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 6138 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 6139 MachineFrameInfo &MFI = MF.getFrameInfo(); 6140 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6141 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 6142 6143 // Offset of the first variable argument from stack pointer, and size of 6144 // the vararg save area. For now, the varargs save area is either zero or 6145 // large enough to hold a0-a7. 6146 int VaArgOffset, VarArgsSaveSize; 6147 6148 // If all registers are allocated, then all varargs must be passed on the 6149 // stack and we don't need to save any argregs. 6150 if (ArgRegs.size() == Idx) { 6151 VaArgOffset = CCInfo.getNextStackOffset(); 6152 VarArgsSaveSize = 0; 6153 } else { 6154 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 6155 VaArgOffset = -VarArgsSaveSize; 6156 } 6157 6158 // Record the frame index of the first variable argument 6159 // which is a value necessary to VASTART. 6160 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 6161 RVFI->setVarArgsFrameIndex(FI); 6162 6163 // If saving an odd number of registers then create an extra stack slot to 6164 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 6165 // offsets to even-numbered registered remain 2*XLEN-aligned. 6166 if (Idx % 2) { 6167 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 6168 VarArgsSaveSize += XLenInBytes; 6169 } 6170 6171 // Copy the integer registers that may have been used for passing varargs 6172 // to the vararg save area. 6173 for (unsigned I = Idx; I < ArgRegs.size(); 6174 ++I, VaArgOffset += XLenInBytes) { 6175 const Register Reg = RegInfo.createVirtualRegister(RC); 6176 RegInfo.addLiveIn(ArgRegs[I], Reg); 6177 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 6178 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 6179 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 6180 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 6181 MachinePointerInfo::getFixedStack(MF, FI)); 6182 cast<StoreSDNode>(Store.getNode()) 6183 ->getMemOperand() 6184 ->setValue((Value *)nullptr); 6185 OutChains.push_back(Store); 6186 } 6187 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 6188 } 6189 6190 // All stores are grouped in one node to allow the matching between 6191 // the size of Ins and InVals. This only happens for vararg functions. 6192 if (!OutChains.empty()) { 6193 OutChains.push_back(Chain); 6194 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 6195 } 6196 6197 return Chain; 6198 } 6199 6200 /// isEligibleForTailCallOptimization - Check whether the call is eligible 6201 /// for tail call optimization. 6202 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 6203 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 6204 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 6205 const SmallVector<CCValAssign, 16> &ArgLocs) const { 6206 6207 auto &Callee = CLI.Callee; 6208 auto CalleeCC = CLI.CallConv; 6209 auto &Outs = CLI.Outs; 6210 auto &Caller = MF.getFunction(); 6211 auto CallerCC = Caller.getCallingConv(); 6212 6213 // Exception-handling functions need a special set of instructions to 6214 // indicate a return to the hardware. Tail-calling another function would 6215 // probably break this. 6216 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 6217 // should be expanded as new function attributes are introduced. 6218 if (Caller.hasFnAttribute("interrupt")) 6219 return false; 6220 6221 // Do not tail call opt if the stack is used to pass parameters. 6222 if (CCInfo.getNextStackOffset() != 0) 6223 return false; 6224 6225 // Do not tail call opt if any parameters need to be passed indirectly. 6226 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 6227 // passed indirectly. So the address of the value will be passed in a 6228 // register, or if not available, then the address is put on the stack. In 6229 // order to pass indirectly, space on the stack often needs to be allocated 6230 // in order to store the value. In this case the CCInfo.getNextStackOffset() 6231 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 6232 // are passed CCValAssign::Indirect. 6233 for (auto &VA : ArgLocs) 6234 if (VA.getLocInfo() == CCValAssign::Indirect) 6235 return false; 6236 6237 // Do not tail call opt if either caller or callee uses struct return 6238 // semantics. 6239 auto IsCallerStructRet = Caller.hasStructRetAttr(); 6240 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 6241 if (IsCallerStructRet || IsCalleeStructRet) 6242 return false; 6243 6244 // Externally-defined functions with weak linkage should not be 6245 // tail-called. The behaviour of branch instructions in this situation (as 6246 // used for tail calls) is implementation-defined, so we cannot rely on the 6247 // linker replacing the tail call with a return. 6248 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 6249 const GlobalValue *GV = G->getGlobal(); 6250 if (GV->hasExternalWeakLinkage()) 6251 return false; 6252 } 6253 6254 // The callee has to preserve all registers the caller needs to preserve. 6255 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6256 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 6257 if (CalleeCC != CallerCC) { 6258 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 6259 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 6260 return false; 6261 } 6262 6263 // Byval parameters hand the function a pointer directly into the stack area 6264 // we want to reuse during a tail call. Working around this *is* possible 6265 // but less efficient and uglier in LowerCall. 6266 for (auto &Arg : Outs) 6267 if (Arg.Flags.isByVal()) 6268 return false; 6269 6270 return true; 6271 } 6272 6273 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 6274 // and output parameter nodes. 6275 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 6276 SmallVectorImpl<SDValue> &InVals) const { 6277 SelectionDAG &DAG = CLI.DAG; 6278 SDLoc &DL = CLI.DL; 6279 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 6280 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 6281 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 6282 SDValue Chain = CLI.Chain; 6283 SDValue Callee = CLI.Callee; 6284 bool &IsTailCall = CLI.IsTailCall; 6285 CallingConv::ID CallConv = CLI.CallConv; 6286 bool IsVarArg = CLI.IsVarArg; 6287 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6288 MVT XLenVT = Subtarget.getXLenVT(); 6289 6290 MachineFunction &MF = DAG.getMachineFunction(); 6291 6292 // Analyze the operands of the call, assigning locations to each operand. 6293 SmallVector<CCValAssign, 16> ArgLocs; 6294 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 6295 6296 if (CallConv == CallingConv::Fast) 6297 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC); 6298 else if (CallConv == CallingConv::GHC) 6299 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 6300 else 6301 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI); 6302 6303 // Check if it's really possible to do a tail call. 6304 if (IsTailCall) 6305 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 6306 6307 if (IsTailCall) 6308 ++NumTailCalls; 6309 else if (CLI.CB && CLI.CB->isMustTailCall()) 6310 report_fatal_error("failed to perform tail call elimination on a call " 6311 "site marked musttail"); 6312 6313 // Get a count of how many bytes are to be pushed on the stack. 6314 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 6315 6316 // Create local copies for byval args 6317 SmallVector<SDValue, 8> ByValArgs; 6318 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 6319 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6320 if (!Flags.isByVal()) 6321 continue; 6322 6323 SDValue Arg = OutVals[i]; 6324 unsigned Size = Flags.getByValSize(); 6325 Align Alignment = Flags.getNonZeroByValAlign(); 6326 6327 int FI = 6328 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 6329 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 6330 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 6331 6332 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 6333 /*IsVolatile=*/false, 6334 /*AlwaysInline=*/false, IsTailCall, 6335 MachinePointerInfo(), MachinePointerInfo()); 6336 ByValArgs.push_back(FIPtr); 6337 } 6338 6339 if (!IsTailCall) 6340 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 6341 6342 // Copy argument values to their designated locations. 6343 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 6344 SmallVector<SDValue, 8> MemOpChains; 6345 SDValue StackPtr; 6346 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 6347 CCValAssign &VA = ArgLocs[i]; 6348 SDValue ArgValue = OutVals[i]; 6349 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6350 6351 // Handle passing f64 on RV32D with a soft float ABI as a special case. 6352 bool IsF64OnRV32DSoftABI = 6353 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 6354 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 6355 SDValue SplitF64 = DAG.getNode( 6356 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 6357 SDValue Lo = SplitF64.getValue(0); 6358 SDValue Hi = SplitF64.getValue(1); 6359 6360 Register RegLo = VA.getLocReg(); 6361 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 6362 6363 if (RegLo == RISCV::X17) { 6364 // Second half of f64 is passed on the stack. 6365 // Work out the address of the stack slot. 6366 if (!StackPtr.getNode()) 6367 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 6368 // Emit the store. 6369 MemOpChains.push_back( 6370 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 6371 } else { 6372 // Second half of f64 is passed in another GPR. 6373 assert(RegLo < RISCV::X31 && "Invalid register pair"); 6374 Register RegHigh = RegLo + 1; 6375 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 6376 } 6377 continue; 6378 } 6379 6380 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 6381 // as any other MemLoc. 6382 6383 // Promote the value if needed. 6384 // For now, only handle fully promoted and indirect arguments. 6385 if (VA.getLocInfo() == CCValAssign::Indirect) { 6386 // Store the argument in a stack slot and pass its address. 6387 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT); 6388 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 6389 MemOpChains.push_back( 6390 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 6391 MachinePointerInfo::getFixedStack(MF, FI))); 6392 // If the original argument was split (e.g. i128), we need 6393 // to store the required parts of it here (and pass just one address). 6394 // Vectors may be partly split to registers and partly to the stack, in 6395 // which case the base address is partly offset and subsequent stores are 6396 // relative to that. 6397 unsigned ArgIndex = Outs[i].OrigArgIndex; 6398 unsigned ArgPartOffset = Outs[i].PartOffset; 6399 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 6400 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 6401 SDValue PartValue = OutVals[i + 1]; 6402 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 6403 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, 6404 DAG.getIntPtrConstant(PartOffset, DL)); 6405 MemOpChains.push_back( 6406 DAG.getStore(Chain, DL, PartValue, Address, 6407 MachinePointerInfo::getFixedStack(MF, FI))); 6408 ++i; 6409 } 6410 ArgValue = SpillSlot; 6411 } else { 6412 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 6413 } 6414 6415 // Use local copy if it is a byval arg. 6416 if (Flags.isByVal()) 6417 ArgValue = ByValArgs[j++]; 6418 6419 if (VA.isRegLoc()) { 6420 // Queue up the argument copies and emit them at the end. 6421 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 6422 } else { 6423 assert(VA.isMemLoc() && "Argument not register or memory"); 6424 assert(!IsTailCall && "Tail call not allowed if stack is used " 6425 "for passing parameters"); 6426 6427 // Work out the address of the stack slot. 6428 if (!StackPtr.getNode()) 6429 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 6430 SDValue Address = 6431 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 6432 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 6433 6434 // Emit the store. 6435 MemOpChains.push_back( 6436 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 6437 } 6438 } 6439 6440 // Join the stores, which are independent of one another. 6441 if (!MemOpChains.empty()) 6442 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 6443 6444 SDValue Glue; 6445 6446 // Build a sequence of copy-to-reg nodes, chained and glued together. 6447 for (auto &Reg : RegsToPass) { 6448 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 6449 Glue = Chain.getValue(1); 6450 } 6451 6452 // Validate that none of the argument registers have been marked as 6453 // reserved, if so report an error. Do the same for the return address if this 6454 // is not a tailcall. 6455 validateCCReservedRegs(RegsToPass, MF); 6456 if (!IsTailCall && 6457 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 6458 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 6459 MF.getFunction(), 6460 "Return address register required, but has been reserved."}); 6461 6462 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 6463 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 6464 // split it and then direct call can be matched by PseudoCALL. 6465 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 6466 const GlobalValue *GV = S->getGlobal(); 6467 6468 unsigned OpFlags = RISCVII::MO_CALL; 6469 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 6470 OpFlags = RISCVII::MO_PLT; 6471 6472 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 6473 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 6474 unsigned OpFlags = RISCVII::MO_CALL; 6475 6476 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 6477 nullptr)) 6478 OpFlags = RISCVII::MO_PLT; 6479 6480 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 6481 } 6482 6483 // The first call operand is the chain and the second is the target address. 6484 SmallVector<SDValue, 8> Ops; 6485 Ops.push_back(Chain); 6486 Ops.push_back(Callee); 6487 6488 // Add argument registers to the end of the list so that they are 6489 // known live into the call. 6490 for (auto &Reg : RegsToPass) 6491 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 6492 6493 if (!IsTailCall) { 6494 // Add a register mask operand representing the call-preserved registers. 6495 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6496 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 6497 assert(Mask && "Missing call preserved mask for calling convention"); 6498 Ops.push_back(DAG.getRegisterMask(Mask)); 6499 } 6500 6501 // Glue the call to the argument copies, if any. 6502 if (Glue.getNode()) 6503 Ops.push_back(Glue); 6504 6505 // Emit the call. 6506 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6507 6508 if (IsTailCall) { 6509 MF.getFrameInfo().setHasTailCall(); 6510 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 6511 } 6512 6513 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 6514 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 6515 Glue = Chain.getValue(1); 6516 6517 // Mark the end of the call, which is glued to the call itself. 6518 Chain = DAG.getCALLSEQ_END(Chain, 6519 DAG.getConstant(NumBytes, DL, PtrVT, true), 6520 DAG.getConstant(0, DL, PtrVT, true), 6521 Glue, DL); 6522 Glue = Chain.getValue(1); 6523 6524 // Assign locations to each value returned by this call. 6525 SmallVector<CCValAssign, 16> RVLocs; 6526 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 6527 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true); 6528 6529 // Copy all of the result registers out of their specified physreg. 6530 for (auto &VA : RVLocs) { 6531 // Copy the value out 6532 SDValue RetValue = 6533 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 6534 // Glue the RetValue to the end of the call sequence 6535 Chain = RetValue.getValue(1); 6536 Glue = RetValue.getValue(2); 6537 6538 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 6539 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 6540 SDValue RetValue2 = 6541 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 6542 Chain = RetValue2.getValue(1); 6543 Glue = RetValue2.getValue(2); 6544 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 6545 RetValue2); 6546 } 6547 6548 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 6549 6550 InVals.push_back(RetValue); 6551 } 6552 6553 return Chain; 6554 } 6555 6556 bool RISCVTargetLowering::CanLowerReturn( 6557 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 6558 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 6559 SmallVector<CCValAssign, 16> RVLocs; 6560 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 6561 6562 Optional<unsigned> FirstMaskArgument; 6563 if (Subtarget.hasStdExtV()) 6564 FirstMaskArgument = preAssignMask(Outs); 6565 6566 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 6567 MVT VT = Outs[i].VT; 6568 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 6569 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 6570 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 6571 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 6572 *this, FirstMaskArgument)) 6573 return false; 6574 } 6575 return true; 6576 } 6577 6578 SDValue 6579 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6580 bool IsVarArg, 6581 const SmallVectorImpl<ISD::OutputArg> &Outs, 6582 const SmallVectorImpl<SDValue> &OutVals, 6583 const SDLoc &DL, SelectionDAG &DAG) const { 6584 const MachineFunction &MF = DAG.getMachineFunction(); 6585 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 6586 6587 // Stores the assignment of the return value to a location. 6588 SmallVector<CCValAssign, 16> RVLocs; 6589 6590 // Info about the registers and stack slot. 6591 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 6592 *DAG.getContext()); 6593 6594 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 6595 nullptr); 6596 6597 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 6598 report_fatal_error("GHC functions return void only"); 6599 6600 SDValue Glue; 6601 SmallVector<SDValue, 4> RetOps(1, Chain); 6602 6603 // Copy the result values into the output registers. 6604 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 6605 SDValue Val = OutVals[i]; 6606 CCValAssign &VA = RVLocs[i]; 6607 assert(VA.isRegLoc() && "Can only return in registers!"); 6608 6609 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 6610 // Handle returning f64 on RV32D with a soft float ABI. 6611 assert(VA.isRegLoc() && "Expected return via registers"); 6612 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 6613 DAG.getVTList(MVT::i32, MVT::i32), Val); 6614 SDValue Lo = SplitF64.getValue(0); 6615 SDValue Hi = SplitF64.getValue(1); 6616 Register RegLo = VA.getLocReg(); 6617 assert(RegLo < RISCV::X31 && "Invalid register pair"); 6618 Register RegHi = RegLo + 1; 6619 6620 if (STI.isRegisterReservedByUser(RegLo) || 6621 STI.isRegisterReservedByUser(RegHi)) 6622 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 6623 MF.getFunction(), 6624 "Return value register required, but has been reserved."}); 6625 6626 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 6627 Glue = Chain.getValue(1); 6628 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 6629 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 6630 Glue = Chain.getValue(1); 6631 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 6632 } else { 6633 // Handle a 'normal' return. 6634 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 6635 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 6636 6637 if (STI.isRegisterReservedByUser(VA.getLocReg())) 6638 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 6639 MF.getFunction(), 6640 "Return value register required, but has been reserved."}); 6641 6642 // Guarantee that all emitted copies are stuck together. 6643 Glue = Chain.getValue(1); 6644 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6645 } 6646 } 6647 6648 RetOps[0] = Chain; // Update chain. 6649 6650 // Add the glue node if we have it. 6651 if (Glue.getNode()) { 6652 RetOps.push_back(Glue); 6653 } 6654 6655 // Interrupt service routines use different return instructions. 6656 const Function &Func = DAG.getMachineFunction().getFunction(); 6657 if (Func.hasFnAttribute("interrupt")) { 6658 if (!Func.getReturnType()->isVoidTy()) 6659 report_fatal_error( 6660 "Functions with the interrupt attribute must have void return type!"); 6661 6662 MachineFunction &MF = DAG.getMachineFunction(); 6663 StringRef Kind = 6664 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 6665 6666 unsigned RetOpc; 6667 if (Kind == "user") 6668 RetOpc = RISCVISD::URET_FLAG; 6669 else if (Kind == "supervisor") 6670 RetOpc = RISCVISD::SRET_FLAG; 6671 else 6672 RetOpc = RISCVISD::MRET_FLAG; 6673 6674 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 6675 } 6676 6677 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps); 6678 } 6679 6680 void RISCVTargetLowering::validateCCReservedRegs( 6681 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 6682 MachineFunction &MF) const { 6683 const Function &F = MF.getFunction(); 6684 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 6685 6686 if (llvm::any_of(Regs, [&STI](auto Reg) { 6687 return STI.isRegisterReservedByUser(Reg.first); 6688 })) 6689 F.getContext().diagnose(DiagnosticInfoUnsupported{ 6690 F, "Argument register required, but has been reserved."}); 6691 } 6692 6693 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 6694 return CI->isTailCall(); 6695 } 6696 6697 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 6698 #define NODE_NAME_CASE(NODE) \ 6699 case RISCVISD::NODE: \ 6700 return "RISCVISD::" #NODE; 6701 // clang-format off 6702 switch ((RISCVISD::NodeType)Opcode) { 6703 case RISCVISD::FIRST_NUMBER: 6704 break; 6705 NODE_NAME_CASE(RET_FLAG) 6706 NODE_NAME_CASE(URET_FLAG) 6707 NODE_NAME_CASE(SRET_FLAG) 6708 NODE_NAME_CASE(MRET_FLAG) 6709 NODE_NAME_CASE(CALL) 6710 NODE_NAME_CASE(SELECT_CC) 6711 NODE_NAME_CASE(BR_CC) 6712 NODE_NAME_CASE(BuildPairF64) 6713 NODE_NAME_CASE(SplitF64) 6714 NODE_NAME_CASE(TAIL) 6715 NODE_NAME_CASE(SLLW) 6716 NODE_NAME_CASE(SRAW) 6717 NODE_NAME_CASE(SRLW) 6718 NODE_NAME_CASE(DIVW) 6719 NODE_NAME_CASE(DIVUW) 6720 NODE_NAME_CASE(REMUW) 6721 NODE_NAME_CASE(ROLW) 6722 NODE_NAME_CASE(RORW) 6723 NODE_NAME_CASE(FSLW) 6724 NODE_NAME_CASE(FSRW) 6725 NODE_NAME_CASE(FSL) 6726 NODE_NAME_CASE(FSR) 6727 NODE_NAME_CASE(FMV_H_X) 6728 NODE_NAME_CASE(FMV_X_ANYEXTH) 6729 NODE_NAME_CASE(FMV_W_X_RV64) 6730 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 6731 NODE_NAME_CASE(READ_CYCLE_WIDE) 6732 NODE_NAME_CASE(GREVI) 6733 NODE_NAME_CASE(GREVIW) 6734 NODE_NAME_CASE(GORCI) 6735 NODE_NAME_CASE(GORCIW) 6736 NODE_NAME_CASE(SHFLI) 6737 NODE_NAME_CASE(VMV_V_X_VL) 6738 NODE_NAME_CASE(VFMV_V_F_VL) 6739 NODE_NAME_CASE(VMV_X_S) 6740 NODE_NAME_CASE(VMV_S_XF_VL) 6741 NODE_NAME_CASE(SPLAT_VECTOR_I64) 6742 NODE_NAME_CASE(READ_VLENB) 6743 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 6744 NODE_NAME_CASE(VLEFF) 6745 NODE_NAME_CASE(VLEFF_MASK) 6746 NODE_NAME_CASE(VSLIDEUP_VL) 6747 NODE_NAME_CASE(VSLIDE1UP_VL) 6748 NODE_NAME_CASE(VSLIDEDOWN_VL) 6749 NODE_NAME_CASE(VID_VL) 6750 NODE_NAME_CASE(VFNCVT_ROD_VL) 6751 NODE_NAME_CASE(VECREDUCE_ADD_VL) 6752 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 6753 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 6754 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 6755 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 6756 NODE_NAME_CASE(VECREDUCE_AND_VL) 6757 NODE_NAME_CASE(VECREDUCE_OR_VL) 6758 NODE_NAME_CASE(VECREDUCE_XOR_VL) 6759 NODE_NAME_CASE(VECREDUCE_FADD_VL) 6760 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 6761 NODE_NAME_CASE(ADD_VL) 6762 NODE_NAME_CASE(AND_VL) 6763 NODE_NAME_CASE(MUL_VL) 6764 NODE_NAME_CASE(OR_VL) 6765 NODE_NAME_CASE(SDIV_VL) 6766 NODE_NAME_CASE(SHL_VL) 6767 NODE_NAME_CASE(SREM_VL) 6768 NODE_NAME_CASE(SRA_VL) 6769 NODE_NAME_CASE(SRL_VL) 6770 NODE_NAME_CASE(SUB_VL) 6771 NODE_NAME_CASE(UDIV_VL) 6772 NODE_NAME_CASE(UREM_VL) 6773 NODE_NAME_CASE(XOR_VL) 6774 NODE_NAME_CASE(FADD_VL) 6775 NODE_NAME_CASE(FSUB_VL) 6776 NODE_NAME_CASE(FMUL_VL) 6777 NODE_NAME_CASE(FDIV_VL) 6778 NODE_NAME_CASE(FNEG_VL) 6779 NODE_NAME_CASE(FABS_VL) 6780 NODE_NAME_CASE(FSQRT_VL) 6781 NODE_NAME_CASE(FMA_VL) 6782 NODE_NAME_CASE(FCOPYSIGN_VL) 6783 NODE_NAME_CASE(SMIN_VL) 6784 NODE_NAME_CASE(SMAX_VL) 6785 NODE_NAME_CASE(UMIN_VL) 6786 NODE_NAME_CASE(UMAX_VL) 6787 NODE_NAME_CASE(MULHS_VL) 6788 NODE_NAME_CASE(MULHU_VL) 6789 NODE_NAME_CASE(FP_TO_SINT_VL) 6790 NODE_NAME_CASE(FP_TO_UINT_VL) 6791 NODE_NAME_CASE(SINT_TO_FP_VL) 6792 NODE_NAME_CASE(UINT_TO_FP_VL) 6793 NODE_NAME_CASE(FP_EXTEND_VL) 6794 NODE_NAME_CASE(FP_ROUND_VL) 6795 NODE_NAME_CASE(SETCC_VL) 6796 NODE_NAME_CASE(VSELECT_VL) 6797 NODE_NAME_CASE(VMAND_VL) 6798 NODE_NAME_CASE(VMOR_VL) 6799 NODE_NAME_CASE(VMXOR_VL) 6800 NODE_NAME_CASE(VMCLR_VL) 6801 NODE_NAME_CASE(VMSET_VL) 6802 NODE_NAME_CASE(VRGATHER_VX_VL) 6803 NODE_NAME_CASE(VRGATHER_VV_VL) 6804 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 6805 NODE_NAME_CASE(VSEXT_VL) 6806 NODE_NAME_CASE(VZEXT_VL) 6807 NODE_NAME_CASE(VLE_VL) 6808 NODE_NAME_CASE(VSE_VL) 6809 } 6810 // clang-format on 6811 return nullptr; 6812 #undef NODE_NAME_CASE 6813 } 6814 6815 /// getConstraintType - Given a constraint letter, return the type of 6816 /// constraint it is for this target. 6817 RISCVTargetLowering::ConstraintType 6818 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 6819 if (Constraint.size() == 1) { 6820 switch (Constraint[0]) { 6821 default: 6822 break; 6823 case 'f': 6824 case 'v': 6825 return C_RegisterClass; 6826 case 'I': 6827 case 'J': 6828 case 'K': 6829 return C_Immediate; 6830 case 'A': 6831 return C_Memory; 6832 } 6833 } 6834 return TargetLowering::getConstraintType(Constraint); 6835 } 6836 6837 std::pair<unsigned, const TargetRegisterClass *> 6838 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 6839 StringRef Constraint, 6840 MVT VT) const { 6841 // First, see if this is a constraint that directly corresponds to a 6842 // RISCV register class. 6843 if (Constraint.size() == 1) { 6844 switch (Constraint[0]) { 6845 case 'r': 6846 return std::make_pair(0U, &RISCV::GPRRegClass); 6847 case 'f': 6848 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 6849 return std::make_pair(0U, &RISCV::FPR16RegClass); 6850 if (Subtarget.hasStdExtF() && VT == MVT::f32) 6851 return std::make_pair(0U, &RISCV::FPR32RegClass); 6852 if (Subtarget.hasStdExtD() && VT == MVT::f64) 6853 return std::make_pair(0U, &RISCV::FPR64RegClass); 6854 break; 6855 case 'v': 6856 for (const auto *RC : 6857 {&RISCV::VMRegClass, &RISCV::VRRegClass, &RISCV::VRM2RegClass, 6858 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 6859 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 6860 return std::make_pair(0U, RC); 6861 } 6862 break; 6863 default: 6864 break; 6865 } 6866 } 6867 6868 // Clang will correctly decode the usage of register name aliases into their 6869 // official names. However, other frontends like `rustc` do not. This allows 6870 // users of these frontends to use the ABI names for registers in LLVM-style 6871 // register constraints. 6872 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 6873 .Case("{zero}", RISCV::X0) 6874 .Case("{ra}", RISCV::X1) 6875 .Case("{sp}", RISCV::X2) 6876 .Case("{gp}", RISCV::X3) 6877 .Case("{tp}", RISCV::X4) 6878 .Case("{t0}", RISCV::X5) 6879 .Case("{t1}", RISCV::X6) 6880 .Case("{t2}", RISCV::X7) 6881 .Cases("{s0}", "{fp}", RISCV::X8) 6882 .Case("{s1}", RISCV::X9) 6883 .Case("{a0}", RISCV::X10) 6884 .Case("{a1}", RISCV::X11) 6885 .Case("{a2}", RISCV::X12) 6886 .Case("{a3}", RISCV::X13) 6887 .Case("{a4}", RISCV::X14) 6888 .Case("{a5}", RISCV::X15) 6889 .Case("{a6}", RISCV::X16) 6890 .Case("{a7}", RISCV::X17) 6891 .Case("{s2}", RISCV::X18) 6892 .Case("{s3}", RISCV::X19) 6893 .Case("{s4}", RISCV::X20) 6894 .Case("{s5}", RISCV::X21) 6895 .Case("{s6}", RISCV::X22) 6896 .Case("{s7}", RISCV::X23) 6897 .Case("{s8}", RISCV::X24) 6898 .Case("{s9}", RISCV::X25) 6899 .Case("{s10}", RISCV::X26) 6900 .Case("{s11}", RISCV::X27) 6901 .Case("{t3}", RISCV::X28) 6902 .Case("{t4}", RISCV::X29) 6903 .Case("{t5}", RISCV::X30) 6904 .Case("{t6}", RISCV::X31) 6905 .Default(RISCV::NoRegister); 6906 if (XRegFromAlias != RISCV::NoRegister) 6907 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 6908 6909 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 6910 // TableGen record rather than the AsmName to choose registers for InlineAsm 6911 // constraints, plus we want to match those names to the widest floating point 6912 // register type available, manually select floating point registers here. 6913 // 6914 // The second case is the ABI name of the register, so that frontends can also 6915 // use the ABI names in register constraint lists. 6916 if (Subtarget.hasStdExtF()) { 6917 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 6918 .Cases("{f0}", "{ft0}", RISCV::F0_F) 6919 .Cases("{f1}", "{ft1}", RISCV::F1_F) 6920 .Cases("{f2}", "{ft2}", RISCV::F2_F) 6921 .Cases("{f3}", "{ft3}", RISCV::F3_F) 6922 .Cases("{f4}", "{ft4}", RISCV::F4_F) 6923 .Cases("{f5}", "{ft5}", RISCV::F5_F) 6924 .Cases("{f6}", "{ft6}", RISCV::F6_F) 6925 .Cases("{f7}", "{ft7}", RISCV::F7_F) 6926 .Cases("{f8}", "{fs0}", RISCV::F8_F) 6927 .Cases("{f9}", "{fs1}", RISCV::F9_F) 6928 .Cases("{f10}", "{fa0}", RISCV::F10_F) 6929 .Cases("{f11}", "{fa1}", RISCV::F11_F) 6930 .Cases("{f12}", "{fa2}", RISCV::F12_F) 6931 .Cases("{f13}", "{fa3}", RISCV::F13_F) 6932 .Cases("{f14}", "{fa4}", RISCV::F14_F) 6933 .Cases("{f15}", "{fa5}", RISCV::F15_F) 6934 .Cases("{f16}", "{fa6}", RISCV::F16_F) 6935 .Cases("{f17}", "{fa7}", RISCV::F17_F) 6936 .Cases("{f18}", "{fs2}", RISCV::F18_F) 6937 .Cases("{f19}", "{fs3}", RISCV::F19_F) 6938 .Cases("{f20}", "{fs4}", RISCV::F20_F) 6939 .Cases("{f21}", "{fs5}", RISCV::F21_F) 6940 .Cases("{f22}", "{fs6}", RISCV::F22_F) 6941 .Cases("{f23}", "{fs7}", RISCV::F23_F) 6942 .Cases("{f24}", "{fs8}", RISCV::F24_F) 6943 .Cases("{f25}", "{fs9}", RISCV::F25_F) 6944 .Cases("{f26}", "{fs10}", RISCV::F26_F) 6945 .Cases("{f27}", "{fs11}", RISCV::F27_F) 6946 .Cases("{f28}", "{ft8}", RISCV::F28_F) 6947 .Cases("{f29}", "{ft9}", RISCV::F29_F) 6948 .Cases("{f30}", "{ft10}", RISCV::F30_F) 6949 .Cases("{f31}", "{ft11}", RISCV::F31_F) 6950 .Default(RISCV::NoRegister); 6951 if (FReg != RISCV::NoRegister) { 6952 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 6953 if (Subtarget.hasStdExtD()) { 6954 unsigned RegNo = FReg - RISCV::F0_F; 6955 unsigned DReg = RISCV::F0_D + RegNo; 6956 return std::make_pair(DReg, &RISCV::FPR64RegClass); 6957 } 6958 return std::make_pair(FReg, &RISCV::FPR32RegClass); 6959 } 6960 } 6961 6962 if (Subtarget.hasStdExtV()) { 6963 Register VReg = StringSwitch<Register>(Constraint.lower()) 6964 .Case("{v0}", RISCV::V0) 6965 .Case("{v1}", RISCV::V1) 6966 .Case("{v2}", RISCV::V2) 6967 .Case("{v3}", RISCV::V3) 6968 .Case("{v4}", RISCV::V4) 6969 .Case("{v5}", RISCV::V5) 6970 .Case("{v6}", RISCV::V6) 6971 .Case("{v7}", RISCV::V7) 6972 .Case("{v8}", RISCV::V8) 6973 .Case("{v9}", RISCV::V9) 6974 .Case("{v10}", RISCV::V10) 6975 .Case("{v11}", RISCV::V11) 6976 .Case("{v12}", RISCV::V12) 6977 .Case("{v13}", RISCV::V13) 6978 .Case("{v14}", RISCV::V14) 6979 .Case("{v15}", RISCV::V15) 6980 .Case("{v16}", RISCV::V16) 6981 .Case("{v17}", RISCV::V17) 6982 .Case("{v18}", RISCV::V18) 6983 .Case("{v19}", RISCV::V19) 6984 .Case("{v20}", RISCV::V20) 6985 .Case("{v21}", RISCV::V21) 6986 .Case("{v22}", RISCV::V22) 6987 .Case("{v23}", RISCV::V23) 6988 .Case("{v24}", RISCV::V24) 6989 .Case("{v25}", RISCV::V25) 6990 .Case("{v26}", RISCV::V26) 6991 .Case("{v27}", RISCV::V27) 6992 .Case("{v28}", RISCV::V28) 6993 .Case("{v29}", RISCV::V29) 6994 .Case("{v30}", RISCV::V30) 6995 .Case("{v31}", RISCV::V31) 6996 .Default(RISCV::NoRegister); 6997 if (VReg != RISCV::NoRegister) { 6998 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 6999 return std::make_pair(VReg, &RISCV::VMRegClass); 7000 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 7001 return std::make_pair(VReg, &RISCV::VRRegClass); 7002 for (const auto *RC : 7003 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 7004 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 7005 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 7006 return std::make_pair(VReg, RC); 7007 } 7008 } 7009 } 7010 } 7011 7012 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7013 } 7014 7015 unsigned 7016 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 7017 // Currently only support length 1 constraints. 7018 if (ConstraintCode.size() == 1) { 7019 switch (ConstraintCode[0]) { 7020 case 'A': 7021 return InlineAsm::Constraint_A; 7022 default: 7023 break; 7024 } 7025 } 7026 7027 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 7028 } 7029 7030 void RISCVTargetLowering::LowerAsmOperandForConstraint( 7031 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 7032 SelectionDAG &DAG) const { 7033 // Currently only support length 1 constraints. 7034 if (Constraint.length() == 1) { 7035 switch (Constraint[0]) { 7036 case 'I': 7037 // Validate & create a 12-bit signed immediate operand. 7038 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 7039 uint64_t CVal = C->getSExtValue(); 7040 if (isInt<12>(CVal)) 7041 Ops.push_back( 7042 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 7043 } 7044 return; 7045 case 'J': 7046 // Validate & create an integer zero operand. 7047 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 7048 if (C->getZExtValue() == 0) 7049 Ops.push_back( 7050 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 7051 return; 7052 case 'K': 7053 // Validate & create a 5-bit unsigned immediate operand. 7054 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 7055 uint64_t CVal = C->getZExtValue(); 7056 if (isUInt<5>(CVal)) 7057 Ops.push_back( 7058 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 7059 } 7060 return; 7061 default: 7062 break; 7063 } 7064 } 7065 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 7066 } 7067 7068 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 7069 Instruction *Inst, 7070 AtomicOrdering Ord) const { 7071 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 7072 return Builder.CreateFence(Ord); 7073 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 7074 return Builder.CreateFence(AtomicOrdering::Release); 7075 return nullptr; 7076 } 7077 7078 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 7079 Instruction *Inst, 7080 AtomicOrdering Ord) const { 7081 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 7082 return Builder.CreateFence(AtomicOrdering::Acquire); 7083 return nullptr; 7084 } 7085 7086 TargetLowering::AtomicExpansionKind 7087 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 7088 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 7089 // point operations can't be used in an lr/sc sequence without breaking the 7090 // forward-progress guarantee. 7091 if (AI->isFloatingPointOperation()) 7092 return AtomicExpansionKind::CmpXChg; 7093 7094 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 7095 if (Size == 8 || Size == 16) 7096 return AtomicExpansionKind::MaskedIntrinsic; 7097 return AtomicExpansionKind::None; 7098 } 7099 7100 static Intrinsic::ID 7101 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 7102 if (XLen == 32) { 7103 switch (BinOp) { 7104 default: 7105 llvm_unreachable("Unexpected AtomicRMW BinOp"); 7106 case AtomicRMWInst::Xchg: 7107 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 7108 case AtomicRMWInst::Add: 7109 return Intrinsic::riscv_masked_atomicrmw_add_i32; 7110 case AtomicRMWInst::Sub: 7111 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 7112 case AtomicRMWInst::Nand: 7113 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 7114 case AtomicRMWInst::Max: 7115 return Intrinsic::riscv_masked_atomicrmw_max_i32; 7116 case AtomicRMWInst::Min: 7117 return Intrinsic::riscv_masked_atomicrmw_min_i32; 7118 case AtomicRMWInst::UMax: 7119 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 7120 case AtomicRMWInst::UMin: 7121 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 7122 } 7123 } 7124 7125 if (XLen == 64) { 7126 switch (BinOp) { 7127 default: 7128 llvm_unreachable("Unexpected AtomicRMW BinOp"); 7129 case AtomicRMWInst::Xchg: 7130 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 7131 case AtomicRMWInst::Add: 7132 return Intrinsic::riscv_masked_atomicrmw_add_i64; 7133 case AtomicRMWInst::Sub: 7134 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 7135 case AtomicRMWInst::Nand: 7136 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 7137 case AtomicRMWInst::Max: 7138 return Intrinsic::riscv_masked_atomicrmw_max_i64; 7139 case AtomicRMWInst::Min: 7140 return Intrinsic::riscv_masked_atomicrmw_min_i64; 7141 case AtomicRMWInst::UMax: 7142 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 7143 case AtomicRMWInst::UMin: 7144 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 7145 } 7146 } 7147 7148 llvm_unreachable("Unexpected XLen\n"); 7149 } 7150 7151 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 7152 IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 7153 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 7154 unsigned XLen = Subtarget.getXLen(); 7155 Value *Ordering = 7156 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 7157 Type *Tys[] = {AlignedAddr->getType()}; 7158 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 7159 AI->getModule(), 7160 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 7161 7162 if (XLen == 64) { 7163 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 7164 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 7165 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 7166 } 7167 7168 Value *Result; 7169 7170 // Must pass the shift amount needed to sign extend the loaded value prior 7171 // to performing a signed comparison for min/max. ShiftAmt is the number of 7172 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 7173 // is the number of bits to left+right shift the value in order to 7174 // sign-extend. 7175 if (AI->getOperation() == AtomicRMWInst::Min || 7176 AI->getOperation() == AtomicRMWInst::Max) { 7177 const DataLayout &DL = AI->getModule()->getDataLayout(); 7178 unsigned ValWidth = 7179 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 7180 Value *SextShamt = 7181 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 7182 Result = Builder.CreateCall(LrwOpScwLoop, 7183 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 7184 } else { 7185 Result = 7186 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 7187 } 7188 7189 if (XLen == 64) 7190 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 7191 return Result; 7192 } 7193 7194 TargetLowering::AtomicExpansionKind 7195 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 7196 AtomicCmpXchgInst *CI) const { 7197 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 7198 if (Size == 8 || Size == 16) 7199 return AtomicExpansionKind::MaskedIntrinsic; 7200 return AtomicExpansionKind::None; 7201 } 7202 7203 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 7204 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 7205 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 7206 unsigned XLen = Subtarget.getXLen(); 7207 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 7208 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 7209 if (XLen == 64) { 7210 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 7211 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 7212 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 7213 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 7214 } 7215 Type *Tys[] = {AlignedAddr->getType()}; 7216 Function *MaskedCmpXchg = 7217 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 7218 Value *Result = Builder.CreateCall( 7219 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 7220 if (XLen == 64) 7221 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 7222 return Result; 7223 } 7224 7225 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 7226 return false; 7227 } 7228 7229 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 7230 EVT VT) const { 7231 VT = VT.getScalarType(); 7232 7233 if (!VT.isSimple()) 7234 return false; 7235 7236 switch (VT.getSimpleVT().SimpleTy) { 7237 case MVT::f16: 7238 return Subtarget.hasStdExtZfh(); 7239 case MVT::f32: 7240 return Subtarget.hasStdExtF(); 7241 case MVT::f64: 7242 return Subtarget.hasStdExtD(); 7243 default: 7244 break; 7245 } 7246 7247 return false; 7248 } 7249 7250 Register RISCVTargetLowering::getExceptionPointerRegister( 7251 const Constant *PersonalityFn) const { 7252 return RISCV::X10; 7253 } 7254 7255 Register RISCVTargetLowering::getExceptionSelectorRegister( 7256 const Constant *PersonalityFn) const { 7257 return RISCV::X11; 7258 } 7259 7260 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 7261 // Return false to suppress the unnecessary extensions if the LibCall 7262 // arguments or return value is f32 type for LP64 ABI. 7263 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 7264 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 7265 return false; 7266 7267 return true; 7268 } 7269 7270 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 7271 if (Subtarget.is64Bit() && Type == MVT::i32) 7272 return true; 7273 7274 return IsSigned; 7275 } 7276 7277 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 7278 SDValue C) const { 7279 // Check integral scalar types. 7280 if (VT.isScalarInteger()) { 7281 // Omit the optimization if the sub target has the M extension and the data 7282 // size exceeds XLen. 7283 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 7284 return false; 7285 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 7286 // Break the MUL to a SLLI and an ADD/SUB. 7287 const APInt &Imm = ConstNode->getAPIntValue(); 7288 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 7289 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 7290 return true; 7291 // Omit the following optimization if the sub target has the M extension 7292 // and the data size >= XLen. 7293 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 7294 return false; 7295 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 7296 // a pair of LUI/ADDI. 7297 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 7298 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 7299 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 7300 (1 - ImmS).isPowerOf2()) 7301 return true; 7302 } 7303 } 7304 } 7305 7306 return false; 7307 } 7308 7309 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 7310 if (!Subtarget.useRVVForFixedLengthVectors()) 7311 return false; 7312 7313 if (!VT.isFixedLengthVector()) 7314 return false; 7315 7316 // Don't use RVV for vectors we cannot scalarize if required. 7317 switch (VT.getVectorElementType().SimpleTy) { 7318 // i1 is supported but has different rules. 7319 default: 7320 return false; 7321 case MVT::i1: 7322 // Masks can only use a single register. 7323 if (VT.getVectorNumElements() > Subtarget.getMinRVVVectorSizeInBits()) 7324 return false; 7325 break; 7326 case MVT::i8: 7327 case MVT::i16: 7328 case MVT::i32: 7329 case MVT::i64: 7330 break; 7331 case MVT::f16: 7332 if (!Subtarget.hasStdExtZfh()) 7333 return false; 7334 break; 7335 case MVT::f32: 7336 if (!Subtarget.hasStdExtF()) 7337 return false; 7338 break; 7339 case MVT::f64: 7340 if (!Subtarget.hasStdExtD()) 7341 return false; 7342 break; 7343 } 7344 7345 unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT); 7346 // Don't use RVV for types that don't fit. 7347 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 7348 return false; 7349 7350 // TODO: Perhaps an artificial restriction, but worth having whilst getting 7351 // the base fixed length RVV support in place. 7352 if (!VT.isPow2VectorType()) 7353 return false; 7354 7355 return true; 7356 } 7357 7358 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 7359 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 7360 bool *Fast) const { 7361 if (!VT.isScalableVector()) 7362 return false; 7363 7364 EVT ElemVT = VT.getVectorElementType(); 7365 if (Alignment >= ElemVT.getStoreSize()) { 7366 if (Fast) 7367 *Fast = true; 7368 return true; 7369 } 7370 7371 return false; 7372 } 7373 7374 bool RISCVTargetLowering::splitValueIntoRegisterParts( 7375 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 7376 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 7377 EVT ValueVT = Val.getValueType(); 7378 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 7379 LLVMContext &Context = *DAG.getContext(); 7380 EVT ValueEltVT = ValueVT.getVectorElementType(); 7381 EVT PartEltVT = PartVT.getVectorElementType(); 7382 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 7383 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 7384 if (PartVTBitSize % ValueVTBitSize == 0) { 7385 // If the element types are different, bitcast to the same element type of 7386 // PartVT first. 7387 if (ValueEltVT != PartEltVT) { 7388 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 7389 assert(Count != 0 && "The number of element should not be zero."); 7390 EVT SameEltTypeVT = 7391 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 7392 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 7393 } 7394 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 7395 Val, DAG.getConstant(0, DL, Subtarget.getXLenVT())); 7396 Parts[0] = Val; 7397 return true; 7398 } 7399 } 7400 return false; 7401 } 7402 7403 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 7404 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 7405 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 7406 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 7407 LLVMContext &Context = *DAG.getContext(); 7408 SDValue Val = Parts[0]; 7409 EVT ValueEltVT = ValueVT.getVectorElementType(); 7410 EVT PartEltVT = PartVT.getVectorElementType(); 7411 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 7412 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 7413 if (PartVTBitSize % ValueVTBitSize == 0) { 7414 EVT SameEltTypeVT = ValueVT; 7415 // If the element types are different, convert it to the same element type 7416 // of PartVT. 7417 if (ValueEltVT != PartEltVT) { 7418 unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits(); 7419 assert(Count != 0 && "The number of element should not be zero."); 7420 SameEltTypeVT = 7421 EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true); 7422 } 7423 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val, 7424 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 7425 if (ValueEltVT != PartEltVT) 7426 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 7427 return Val; 7428 } 7429 } 7430 return SDValue(); 7431 } 7432 7433 #define GET_REGISTER_MATCHER 7434 #include "RISCVGenAsmMatcher.inc" 7435 7436 Register 7437 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 7438 const MachineFunction &MF) const { 7439 Register Reg = MatchRegisterAltName(RegName); 7440 if (Reg == RISCV::NoRegister) 7441 Reg = MatchRegisterName(RegName); 7442 if (Reg == RISCV::NoRegister) 7443 report_fatal_error( 7444 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 7445 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 7446 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 7447 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 7448 StringRef(RegName) + "\".")); 7449 return Reg; 7450 } 7451 7452 namespace llvm { 7453 namespace RISCVVIntrinsicsTable { 7454 7455 #define GET_RISCVVIntrinsicsTable_IMPL 7456 #include "RISCVGenSearchableTables.inc" 7457 7458 } // namespace RISCVVIntrinsicsTable 7459 7460 } // namespace llvm 7461