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) 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::SELECT_CC, XLenVT, Expand); 185 186 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 187 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 188 189 setOperationAction(ISD::VASTART, MVT::Other, Custom); 190 setOperationAction(ISD::VAARG, MVT::Other, Expand); 191 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 192 setOperationAction(ISD::VAEND, MVT::Other, Expand); 193 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 195 if (!Subtarget.hasStdExtZbb()) { 196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 198 } 199 200 if (Subtarget.is64Bit()) { 201 setOperationAction(ISD::ADD, MVT::i32, Custom); 202 setOperationAction(ISD::SUB, MVT::i32, Custom); 203 setOperationAction(ISD::SHL, MVT::i32, Custom); 204 setOperationAction(ISD::SRA, MVT::i32, Custom); 205 setOperationAction(ISD::SRL, MVT::i32, Custom); 206 } 207 208 if (!Subtarget.hasStdExtM()) { 209 setOperationAction(ISD::MUL, XLenVT, Expand); 210 setOperationAction(ISD::MULHS, XLenVT, Expand); 211 setOperationAction(ISD::MULHU, XLenVT, Expand); 212 setOperationAction(ISD::SDIV, XLenVT, Expand); 213 setOperationAction(ISD::UDIV, XLenVT, Expand); 214 setOperationAction(ISD::SREM, XLenVT, Expand); 215 setOperationAction(ISD::UREM, XLenVT, Expand); 216 } 217 218 if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) { 219 setOperationAction(ISD::MUL, MVT::i32, Custom); 220 221 setOperationAction(ISD::SDIV, MVT::i8, Custom); 222 setOperationAction(ISD::UDIV, MVT::i8, Custom); 223 setOperationAction(ISD::UREM, MVT::i8, Custom); 224 setOperationAction(ISD::SDIV, MVT::i16, Custom); 225 setOperationAction(ISD::UDIV, MVT::i16, Custom); 226 setOperationAction(ISD::UREM, MVT::i16, Custom); 227 setOperationAction(ISD::SDIV, MVT::i32, Custom); 228 setOperationAction(ISD::UDIV, MVT::i32, Custom); 229 setOperationAction(ISD::UREM, MVT::i32, Custom); 230 } 231 232 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 233 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 234 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 235 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 236 237 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 238 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 239 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 240 241 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 242 if (Subtarget.is64Bit()) { 243 setOperationAction(ISD::ROTL, MVT::i32, Custom); 244 setOperationAction(ISD::ROTR, MVT::i32, Custom); 245 } 246 } else { 247 setOperationAction(ISD::ROTL, XLenVT, Expand); 248 setOperationAction(ISD::ROTR, XLenVT, Expand); 249 } 250 251 if (Subtarget.hasStdExtZbp()) { 252 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 253 // more combining. 254 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 255 setOperationAction(ISD::BSWAP, XLenVT, Custom); 256 257 if (Subtarget.is64Bit()) { 258 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 259 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 260 } 261 } else { 262 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 263 // pattern match it directly in isel. 264 setOperationAction(ISD::BSWAP, XLenVT, 265 Subtarget.hasStdExtZbb() ? Legal : Expand); 266 } 267 268 if (Subtarget.hasStdExtZbb()) { 269 setOperationAction(ISD::SMIN, XLenVT, Legal); 270 setOperationAction(ISD::SMAX, XLenVT, Legal); 271 setOperationAction(ISD::UMIN, XLenVT, Legal); 272 setOperationAction(ISD::UMAX, XLenVT, Legal); 273 } else { 274 setOperationAction(ISD::CTTZ, XLenVT, Expand); 275 setOperationAction(ISD::CTLZ, XLenVT, Expand); 276 setOperationAction(ISD::CTPOP, XLenVT, Expand); 277 } 278 279 if (Subtarget.hasStdExtZbt()) { 280 setOperationAction(ISD::FSHL, XLenVT, Custom); 281 setOperationAction(ISD::FSHR, XLenVT, Custom); 282 setOperationAction(ISD::SELECT, XLenVT, Legal); 283 284 if (Subtarget.is64Bit()) { 285 setOperationAction(ISD::FSHL, MVT::i32, Custom); 286 setOperationAction(ISD::FSHR, MVT::i32, Custom); 287 } 288 } else { 289 setOperationAction(ISD::SELECT, XLenVT, Custom); 290 } 291 292 ISD::CondCode FPCCToExpand[] = { 293 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 294 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 295 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 296 297 ISD::NodeType FPOpToExpand[] = { 298 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP, 299 ISD::FP_TO_FP16}; 300 301 if (Subtarget.hasStdExtZfh()) 302 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 303 304 if (Subtarget.hasStdExtZfh()) { 305 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 306 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 307 for (auto CC : FPCCToExpand) 308 setCondCodeAction(CC, MVT::f16, Expand); 309 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 310 setOperationAction(ISD::SELECT, MVT::f16, Custom); 311 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 312 for (auto Op : FPOpToExpand) 313 setOperationAction(Op, MVT::f16, Expand); 314 } 315 316 if (Subtarget.hasStdExtF()) { 317 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 318 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 319 for (auto CC : FPCCToExpand) 320 setCondCodeAction(CC, MVT::f32, Expand); 321 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 322 setOperationAction(ISD::SELECT, MVT::f32, Custom); 323 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 324 for (auto Op : FPOpToExpand) 325 setOperationAction(Op, MVT::f32, Expand); 326 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 327 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 328 } 329 330 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 331 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 332 333 if (Subtarget.hasStdExtD()) { 334 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 335 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 336 for (auto CC : FPCCToExpand) 337 setCondCodeAction(CC, MVT::f64, Expand); 338 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 339 setOperationAction(ISD::SELECT, MVT::f64, Custom); 340 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 341 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 342 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 343 for (auto Op : FPOpToExpand) 344 setOperationAction(Op, MVT::f64, Expand); 345 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 346 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 347 } 348 349 if (Subtarget.is64Bit()) { 350 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 351 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 352 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 353 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 354 } 355 356 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 357 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 358 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 359 setOperationAction(ISD::JumpTable, XLenVT, Custom); 360 361 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 362 363 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 364 // Unfortunately this can't be determined just from the ISA naming string. 365 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 366 Subtarget.is64Bit() ? Legal : Custom); 367 368 setOperationAction(ISD::TRAP, MVT::Other, Legal); 369 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 370 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 371 372 if (Subtarget.hasStdExtA()) { 373 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 374 setMinCmpXchgSizeInBits(32); 375 } else { 376 setMaxAtomicSizeInBitsSupported(0); 377 } 378 379 setBooleanContents(ZeroOrOneBooleanContent); 380 381 if (Subtarget.hasStdExtV()) { 382 setBooleanVectorContents(ZeroOrOneBooleanContent); 383 384 setOperationAction(ISD::VSCALE, XLenVT, Custom); 385 386 // RVV intrinsics may have illegal operands. 387 // We also need to custom legalize vmv.x.s. 388 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 389 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 390 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 391 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 392 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 393 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 394 395 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 396 397 if (Subtarget.is64Bit()) { 398 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 399 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 400 } else { 401 // We must custom-lower certain vXi64 operations on RV32 due to the vector 402 // element type being illegal. 403 setOperationAction(ISD::SPLAT_VECTOR, MVT::i64, Custom); 404 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom); 405 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom); 406 407 setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom); 408 setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom); 409 setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom); 410 setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom); 411 setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom); 412 setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom); 413 setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom); 414 setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom); 415 } 416 417 for (MVT VT : BoolVecVTs) { 418 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 419 420 // Mask VTs are custom-expanded into a series of standard nodes 421 setOperationAction(ISD::TRUNCATE, VT, Custom); 422 } 423 424 for (MVT VT : IntVecVTs) { 425 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 426 427 setOperationAction(ISD::SMIN, VT, Legal); 428 setOperationAction(ISD::SMAX, VT, Legal); 429 setOperationAction(ISD::UMIN, VT, Legal); 430 setOperationAction(ISD::UMAX, VT, Legal); 431 432 setOperationAction(ISD::ROTL, VT, Expand); 433 setOperationAction(ISD::ROTR, VT, Expand); 434 435 // Custom-lower extensions and truncations from/to mask types. 436 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 437 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 438 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 439 440 // RVV has native int->float & float->int conversions where the 441 // element type sizes are within one power-of-two of each other. Any 442 // wider distances between type sizes have to be lowered as sequences 443 // which progressively narrow the gap in stages. 444 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 445 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 446 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 447 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 448 449 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR" 450 // nodes which truncate by one power of two at a time. 451 setOperationAction(ISD::TRUNCATE, VT, Custom); 452 453 // Custom-lower insert/extract operations to simplify patterns. 454 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 455 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 456 457 // Custom-lower reduction operations to set up the corresponding custom 458 // nodes' operands. 459 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 460 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 461 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 462 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 463 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 464 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 465 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 466 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 467 } 468 469 // Expand various CCs to best match the RVV ISA, which natively supports UNE 470 // but no other unordered comparisons, and supports all ordered comparisons 471 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 472 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 473 // and we pattern-match those back to the "original", swapping operands once 474 // more. This way we catch both operations and both "vf" and "fv" forms with 475 // fewer patterns. 476 ISD::CondCode VFPCCToExpand[] = { 477 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 478 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 479 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 480 }; 481 482 // Sets common operation actions on RVV floating-point vector types. 483 const auto SetCommonVFPActions = [&](MVT VT) { 484 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 485 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 486 // sizes are within one power-of-two of each other. Therefore conversions 487 // between vXf16 and vXf64 must be lowered as sequences which convert via 488 // vXf32. 489 setOperationAction(ISD::FP_ROUND, VT, Custom); 490 setOperationAction(ISD::FP_EXTEND, VT, Custom); 491 // Custom-lower insert/extract operations to simplify patterns. 492 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 493 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 494 // Expand various condition codes (explained above). 495 for (auto CC : VFPCCToExpand) 496 setCondCodeAction(CC, VT, Expand); 497 498 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 499 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 500 }; 501 502 if (Subtarget.hasStdExtZfh()) 503 for (MVT VT : F16VecVTs) 504 SetCommonVFPActions(VT); 505 506 if (Subtarget.hasStdExtF()) 507 for (MVT VT : F32VecVTs) 508 SetCommonVFPActions(VT); 509 510 if (Subtarget.hasStdExtD()) 511 for (MVT VT : F64VecVTs) 512 SetCommonVFPActions(VT); 513 514 if (Subtarget.useRVVForFixedLengthVectors()) { 515 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 516 if (!useRVVForFixedLengthVectorVT(VT)) 517 continue; 518 519 // By default everything must be expanded. 520 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 521 setOperationAction(Op, VT, Expand); 522 523 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 524 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 525 526 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 527 528 setOperationAction(ISD::LOAD, VT, Custom); 529 setOperationAction(ISD::STORE, VT, Custom); 530 setOperationAction(ISD::ADD, VT, Custom); 531 setOperationAction(ISD::MUL, VT, Custom); 532 setOperationAction(ISD::SUB, VT, Custom); 533 setOperationAction(ISD::AND, VT, Custom); 534 setOperationAction(ISD::OR, VT, Custom); 535 setOperationAction(ISD::XOR, VT, Custom); 536 setOperationAction(ISD::SDIV, VT, Custom); 537 setOperationAction(ISD::SREM, VT, Custom); 538 setOperationAction(ISD::UDIV, VT, Custom); 539 setOperationAction(ISD::UREM, VT, Custom); 540 setOperationAction(ISD::SHL, VT, Custom); 541 setOperationAction(ISD::SRA, VT, Custom); 542 setOperationAction(ISD::SRL, VT, Custom); 543 } 544 545 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 546 if (!useRVVForFixedLengthVectorVT(VT)) 547 continue; 548 549 // By default everything must be expanded. 550 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 551 setOperationAction(Op, VT, Expand); 552 553 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 554 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 555 556 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 557 558 setOperationAction(ISD::LOAD, VT, Custom); 559 setOperationAction(ISD::STORE, VT, Custom); 560 setOperationAction(ISD::FADD, VT, Custom); 561 setOperationAction(ISD::FSUB, VT, Custom); 562 setOperationAction(ISD::FMUL, VT, Custom); 563 setOperationAction(ISD::FDIV, VT, Custom); 564 setOperationAction(ISD::FNEG, VT, Custom); 565 setOperationAction(ISD::FMA, VT, Custom); 566 } 567 } 568 } 569 570 // Function alignments. 571 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 572 setMinFunctionAlignment(FunctionAlignment); 573 setPrefFunctionAlignment(FunctionAlignment); 574 575 setMinimumJumpTableEntries(5); 576 577 // Jumps are expensive, compared to logic 578 setJumpIsExpensive(); 579 580 // We can use any register for comparisons 581 setHasMultipleConditionRegisters(); 582 583 setTargetDAGCombine(ISD::SETCC); 584 if (Subtarget.hasStdExtZbp()) { 585 setTargetDAGCombine(ISD::OR); 586 } 587 } 588 589 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 590 LLVMContext &Context, 591 EVT VT) const { 592 if (!VT.isVector()) 593 return getPointerTy(DL); 594 if (Subtarget.hasStdExtV() && VT.isScalableVector()) 595 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 596 return VT.changeVectorElementTypeToInteger(); 597 } 598 599 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 600 const CallInst &I, 601 MachineFunction &MF, 602 unsigned Intrinsic) const { 603 switch (Intrinsic) { 604 default: 605 return false; 606 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 607 case Intrinsic::riscv_masked_atomicrmw_add_i32: 608 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 609 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 610 case Intrinsic::riscv_masked_atomicrmw_max_i32: 611 case Intrinsic::riscv_masked_atomicrmw_min_i32: 612 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 613 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 614 case Intrinsic::riscv_masked_cmpxchg_i32: 615 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 616 Info.opc = ISD::INTRINSIC_W_CHAIN; 617 Info.memVT = MVT::getVT(PtrTy->getElementType()); 618 Info.ptrVal = I.getArgOperand(0); 619 Info.offset = 0; 620 Info.align = Align(4); 621 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 622 MachineMemOperand::MOVolatile; 623 return true; 624 } 625 } 626 627 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 628 const AddrMode &AM, Type *Ty, 629 unsigned AS, 630 Instruction *I) const { 631 // No global is ever allowed as a base. 632 if (AM.BaseGV) 633 return false; 634 635 // Require a 12-bit signed offset. 636 if (!isInt<12>(AM.BaseOffs)) 637 return false; 638 639 switch (AM.Scale) { 640 case 0: // "r+i" or just "i", depending on HasBaseReg. 641 break; 642 case 1: 643 if (!AM.HasBaseReg) // allow "r+i". 644 break; 645 return false; // disallow "r+r" or "r+r+i". 646 default: 647 return false; 648 } 649 650 return true; 651 } 652 653 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 654 return isInt<12>(Imm); 655 } 656 657 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 658 return isInt<12>(Imm); 659 } 660 661 // On RV32, 64-bit integers are split into their high and low parts and held 662 // in two different registers, so the trunc is free since the low register can 663 // just be used. 664 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 665 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 666 return false; 667 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 668 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 669 return (SrcBits == 64 && DestBits == 32); 670 } 671 672 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 673 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 674 !SrcVT.isInteger() || !DstVT.isInteger()) 675 return false; 676 unsigned SrcBits = SrcVT.getSizeInBits(); 677 unsigned DestBits = DstVT.getSizeInBits(); 678 return (SrcBits == 64 && DestBits == 32); 679 } 680 681 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 682 // Zexts are free if they can be combined with a load. 683 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 684 EVT MemVT = LD->getMemoryVT(); 685 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 686 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 687 (LD->getExtensionType() == ISD::NON_EXTLOAD || 688 LD->getExtensionType() == ISD::ZEXTLOAD)) 689 return true; 690 } 691 692 return TargetLowering::isZExtFree(Val, VT2); 693 } 694 695 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 696 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 697 } 698 699 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 700 return Subtarget.hasStdExtZbb(); 701 } 702 703 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 704 return Subtarget.hasStdExtZbb(); 705 } 706 707 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 708 bool ForCodeSize) const { 709 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 710 return false; 711 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 712 return false; 713 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 714 return false; 715 if (Imm.isNegZero()) 716 return false; 717 return Imm.isZero(); 718 } 719 720 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 721 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 722 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 723 (VT == MVT::f64 && Subtarget.hasStdExtD()); 724 } 725 726 // Changes the condition code and swaps operands if necessary, so the SetCC 727 // operation matches one of the comparisons supported directly in the RISC-V 728 // ISA. 729 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) { 730 switch (CC) { 731 default: 732 break; 733 case ISD::SETGT: 734 case ISD::SETLE: 735 case ISD::SETUGT: 736 case ISD::SETULE: 737 CC = ISD::getSetCCSwappedOperands(CC); 738 std::swap(LHS, RHS); 739 break; 740 } 741 } 742 743 // Return the RISC-V branch opcode that matches the given DAG integer 744 // condition code. The CondCode must be one of those supported by the RISC-V 745 // ISA (see normaliseSetCC). 746 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) { 747 switch (CC) { 748 default: 749 llvm_unreachable("Unsupported CondCode"); 750 case ISD::SETEQ: 751 return RISCV::BEQ; 752 case ISD::SETNE: 753 return RISCV::BNE; 754 case ISD::SETLT: 755 return RISCV::BLT; 756 case ISD::SETGE: 757 return RISCV::BGE; 758 case ISD::SETULT: 759 return RISCV::BLTU; 760 case ISD::SETUGE: 761 return RISCV::BGEU; 762 } 763 } 764 765 // Return the largest legal scalable vector type that matches VT's element type. 766 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 767 const RISCVSubtarget &Subtarget) { 768 assert(VT.isFixedLengthVector() && 769 DAG.getTargetLoweringInfo().isTypeLegal(VT) && 770 "Expected legal fixed length vector!"); 771 772 unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT); 773 assert(LMul <= 8 && isPowerOf2_32(LMul) && "Unexpected LMUL!"); 774 775 switch (VT.getVectorElementType().SimpleTy) { 776 default: 777 llvm_unreachable("unexpected element type for RVV container"); 778 case MVT::i8: 779 return MVT::getScalableVectorVT(MVT::i8, LMul * 8); 780 case MVT::i16: 781 return MVT::getScalableVectorVT(MVT::i16, LMul * 4); 782 case MVT::i32: 783 return MVT::getScalableVectorVT(MVT::i32, LMul * 2); 784 case MVT::i64: 785 return MVT::getScalableVectorVT(MVT::i64, LMul); 786 case MVT::f16: 787 return MVT::getScalableVectorVT(MVT::f16, LMul * 4); 788 case MVT::f32: 789 return MVT::getScalableVectorVT(MVT::f32, LMul * 2); 790 case MVT::f64: 791 return MVT::getScalableVectorVT(MVT::f64, LMul); 792 } 793 } 794 795 // Grow V to consume an entire RVV register. 796 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 797 const RISCVSubtarget &Subtarget) { 798 assert(VT.isScalableVector() && 799 "Expected to convert into a scalable vector!"); 800 assert(V.getValueType().isFixedLengthVector() && 801 "Expected a fixed length vector operand!"); 802 SDLoc DL(V); 803 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 804 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 805 } 806 807 // Shrink V so it's just big enough to maintain a VT's worth of data. 808 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 809 const RISCVSubtarget &Subtarget) { 810 assert(VT.isFixedLengthVector() && 811 "Expected to convert into a fixed length vector!"); 812 assert(V.getValueType().isScalableVector() && 813 "Expected a scalable vector operand!"); 814 SDLoc DL(V); 815 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 816 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 817 } 818 819 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 820 const RISCVSubtarget &Subtarget) { 821 MVT VT = Op.getSimpleValueType(); 822 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 823 824 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 825 826 SDLoc DL(Op); 827 SDValue VL = 828 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 829 830 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 831 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 832 : RISCVISD::VMV_V_X_VL; 833 Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL); 834 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 835 } 836 837 // Try and match an index sequence, which we can lower directly to the vid 838 // instruction. An all-undef vector is matched by getSplatValue, above. 839 bool IsVID = true; 840 if (VT.isInteger()) 841 for (unsigned i = 0, e = Op.getNumOperands(); i < e && IsVID; i++) 842 IsVID &= Op.getOperand(i).isUndef() || 843 (isa<ConstantSDNode>(Op.getOperand(i)) && 844 Op.getConstantOperandVal(i) == i); 845 846 if (IsVID) { 847 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 848 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 849 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 850 return convertFromScalableVector(VT, VID, DAG, Subtarget); 851 } 852 853 return SDValue(); 854 } 855 856 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 857 SelectionDAG &DAG) const { 858 switch (Op.getOpcode()) { 859 default: 860 report_fatal_error("unimplemented operand"); 861 case ISD::GlobalAddress: 862 return lowerGlobalAddress(Op, DAG); 863 case ISD::BlockAddress: 864 return lowerBlockAddress(Op, DAG); 865 case ISD::ConstantPool: 866 return lowerConstantPool(Op, DAG); 867 case ISD::JumpTable: 868 return lowerJumpTable(Op, DAG); 869 case ISD::GlobalTLSAddress: 870 return lowerGlobalTLSAddress(Op, DAG); 871 case ISD::SELECT: 872 return lowerSELECT(Op, DAG); 873 case ISD::VASTART: 874 return lowerVASTART(Op, DAG); 875 case ISD::FRAMEADDR: 876 return lowerFRAMEADDR(Op, DAG); 877 case ISD::RETURNADDR: 878 return lowerRETURNADDR(Op, DAG); 879 case ISD::SHL_PARTS: 880 return lowerShiftLeftParts(Op, DAG); 881 case ISD::SRA_PARTS: 882 return lowerShiftRightParts(Op, DAG, true); 883 case ISD::SRL_PARTS: 884 return lowerShiftRightParts(Op, DAG, false); 885 case ISD::BITCAST: { 886 assert(((Subtarget.is64Bit() && Subtarget.hasStdExtF()) || 887 Subtarget.hasStdExtZfh()) && 888 "Unexpected custom legalisation"); 889 SDLoc DL(Op); 890 SDValue Op0 = Op.getOperand(0); 891 if (Op.getValueType() == MVT::f16 && Subtarget.hasStdExtZfh()) { 892 if (Op0.getValueType() != MVT::i16) 893 return SDValue(); 894 SDValue NewOp0 = 895 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), Op0); 896 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 897 return FPConv; 898 } else if (Op.getValueType() == MVT::f32 && Subtarget.is64Bit() && 899 Subtarget.hasStdExtF()) { 900 if (Op0.getValueType() != MVT::i32) 901 return SDValue(); 902 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 903 SDValue FPConv = 904 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 905 return FPConv; 906 } 907 return SDValue(); 908 } 909 case ISD::INTRINSIC_WO_CHAIN: 910 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 911 case ISD::INTRINSIC_W_CHAIN: 912 return LowerINTRINSIC_W_CHAIN(Op, DAG); 913 case ISD::BSWAP: 914 case ISD::BITREVERSE: { 915 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 916 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 917 MVT VT = Op.getSimpleValueType(); 918 SDLoc DL(Op); 919 // Start with the maximum immediate value which is the bitwidth - 1. 920 unsigned Imm = VT.getSizeInBits() - 1; 921 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 922 if (Op.getOpcode() == ISD::BSWAP) 923 Imm &= ~0x7U; 924 return DAG.getNode(RISCVISD::GREVI, DL, VT, Op.getOperand(0), 925 DAG.getTargetConstant(Imm, DL, Subtarget.getXLenVT())); 926 } 927 case ISD::FSHL: 928 case ISD::FSHR: { 929 MVT VT = Op.getSimpleValueType(); 930 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 931 SDLoc DL(Op); 932 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 933 // use log(XLen) bits. Mask the shift amount accordingly. 934 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 935 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 936 DAG.getConstant(ShAmtWidth, DL, VT)); 937 unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR; 938 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt); 939 } 940 case ISD::TRUNCATE: { 941 SDLoc DL(Op); 942 EVT VT = Op.getValueType(); 943 // Only custom-lower vector truncates 944 if (!VT.isVector()) 945 return Op; 946 947 // Truncates to mask types are handled differently 948 if (VT.getVectorElementType() == MVT::i1) 949 return lowerVectorMaskTrunc(Op, DAG); 950 951 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 952 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR" nodes which 953 // truncate by one power of two at a time. 954 EVT DstEltVT = VT.getVectorElementType(); 955 956 SDValue Src = Op.getOperand(0); 957 EVT SrcVT = Src.getValueType(); 958 EVT SrcEltVT = SrcVT.getVectorElementType(); 959 960 assert(DstEltVT.bitsLT(SrcEltVT) && 961 isPowerOf2_64(DstEltVT.getSizeInBits()) && 962 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 963 "Unexpected vector truncate lowering"); 964 965 SDValue Result = Src; 966 LLVMContext &Context = *DAG.getContext(); 967 const ElementCount Count = SrcVT.getVectorElementCount(); 968 do { 969 SrcEltVT = EVT::getIntegerVT(Context, SrcEltVT.getSizeInBits() / 2); 970 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 971 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR, DL, ResultVT, Result); 972 } while (SrcEltVT != DstEltVT); 973 974 return Result; 975 } 976 case ISD::ANY_EXTEND: 977 case ISD::ZERO_EXTEND: 978 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 979 case ISD::SIGN_EXTEND: 980 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 981 case ISD::SPLAT_VECTOR: 982 return lowerSPLATVECTOR(Op, DAG); 983 case ISD::INSERT_VECTOR_ELT: 984 return lowerINSERT_VECTOR_ELT(Op, DAG); 985 case ISD::EXTRACT_VECTOR_ELT: 986 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 987 case ISD::VSCALE: { 988 MVT VT = Op.getSimpleValueType(); 989 SDLoc DL(Op); 990 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 991 // We define our scalable vector types for lmul=1 to use a 64 bit known 992 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 993 // vscale as VLENB / 8. 994 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 995 DAG.getConstant(3, DL, VT)); 996 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 997 } 998 case ISD::FP_EXTEND: { 999 // RVV can only do fp_extend to types double the size as the source. We 1000 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 1001 // via f32. 1002 MVT VT = Op.getSimpleValueType(); 1003 MVT SrcVT = Op.getOperand(0).getSimpleValueType(); 1004 // We only need to close the gap between vXf16->vXf64. 1005 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 1006 SrcVT.getVectorElementType() != MVT::f16) 1007 return Op; 1008 SDLoc DL(Op); 1009 MVT InterVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 1010 SDValue IntermediateRound = 1011 DAG.getFPExtendOrRound(Op.getOperand(0), DL, InterVT); 1012 return DAG.getFPExtendOrRound(IntermediateRound, DL, VT); 1013 } 1014 case ISD::FP_ROUND: { 1015 // RVV can only do fp_round to types half the size as the source. We 1016 // custom-lower f64->f16 rounds via RVV's round-to-odd float 1017 // conversion instruction. 1018 MVT VT = Op.getSimpleValueType(); 1019 MVT SrcVT = Op.getOperand(0).getSimpleValueType(); 1020 // We only need to close the gap between vXf64<->vXf16. 1021 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 || 1022 SrcVT.getVectorElementType() != MVT::f64) 1023 return Op; 1024 SDLoc DL(Op); 1025 MVT InterVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 1026 SDValue IntermediateRound = 1027 DAG.getNode(RISCVISD::VFNCVT_ROD, DL, InterVT, Op.getOperand(0)); 1028 return DAG.getFPExtendOrRound(IntermediateRound, DL, VT); 1029 } 1030 case ISD::FP_TO_SINT: 1031 case ISD::FP_TO_UINT: 1032 case ISD::SINT_TO_FP: 1033 case ISD::UINT_TO_FP: { 1034 // RVV can only do fp<->int conversions to types half/double the size as 1035 // the source. We custom-lower any conversions that do two hops into 1036 // sequences. 1037 MVT VT = Op.getSimpleValueType(); 1038 if (!VT.isVector()) 1039 return Op; 1040 SDLoc DL(Op); 1041 SDValue Src = Op.getOperand(0); 1042 MVT EltVT = VT.getVectorElementType(); 1043 MVT SrcEltVT = Src.getSimpleValueType().getVectorElementType(); 1044 unsigned EltSize = EltVT.getSizeInBits(); 1045 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 1046 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 1047 "Unexpected vector element types"); 1048 bool IsInt2FP = SrcEltVT.isInteger(); 1049 // Widening conversions 1050 if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) { 1051 if (IsInt2FP) { 1052 // Do a regular integer sign/zero extension then convert to float. 1053 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()), 1054 VT.getVectorElementCount()); 1055 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 1056 ? ISD::ZERO_EXTEND 1057 : ISD::SIGN_EXTEND; 1058 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 1059 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 1060 } 1061 // FP2Int 1062 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 1063 // Do one doubling fp_extend then complete the operation by converting 1064 // to int. 1065 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 1066 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 1067 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 1068 } 1069 1070 // Narrowing conversions 1071 if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) { 1072 if (IsInt2FP) { 1073 // One narrowing int_to_fp, then an fp_round. 1074 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 1075 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 1076 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 1077 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 1078 } 1079 // FP2Int 1080 // One narrowing fp_to_int, then truncate the integer. If the float isn't 1081 // representable by the integer, the result is poison. 1082 MVT IVecVT = 1083 MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2), 1084 VT.getVectorElementCount()); 1085 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 1086 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 1087 } 1088 1089 return Op; 1090 } 1091 case ISD::VECREDUCE_ADD: 1092 case ISD::VECREDUCE_UMAX: 1093 case ISD::VECREDUCE_SMAX: 1094 case ISD::VECREDUCE_UMIN: 1095 case ISD::VECREDUCE_SMIN: 1096 case ISD::VECREDUCE_AND: 1097 case ISD::VECREDUCE_OR: 1098 case ISD::VECREDUCE_XOR: 1099 return lowerVECREDUCE(Op, DAG); 1100 case ISD::VECREDUCE_FADD: 1101 case ISD::VECREDUCE_SEQ_FADD: 1102 return lowerFPVECREDUCE(Op, DAG); 1103 case ISD::BUILD_VECTOR: 1104 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 1105 case ISD::LOAD: 1106 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 1107 case ISD::STORE: 1108 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 1109 case ISD::ADD: 1110 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 1111 case ISD::SUB: 1112 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 1113 case ISD::MUL: 1114 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 1115 case ISD::AND: 1116 return lowerToScalableOp(Op, DAG, RISCVISD::AND_VL); 1117 case ISD::OR: 1118 return lowerToScalableOp(Op, DAG, RISCVISD::OR_VL); 1119 case ISD::XOR: 1120 return lowerToScalableOp(Op, DAG, RISCVISD::XOR_VL); 1121 case ISD::SDIV: 1122 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 1123 case ISD::SREM: 1124 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 1125 case ISD::UDIV: 1126 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 1127 case ISD::UREM: 1128 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 1129 case ISD::SHL: 1130 return lowerToScalableOp(Op, DAG, RISCVISD::SHL_VL); 1131 case ISD::SRA: 1132 return lowerToScalableOp(Op, DAG, RISCVISD::SRA_VL); 1133 case ISD::SRL: 1134 return lowerToScalableOp(Op, DAG, RISCVISD::SRL_VL); 1135 case ISD::FADD: 1136 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 1137 case ISD::FSUB: 1138 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 1139 case ISD::FMUL: 1140 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 1141 case ISD::FDIV: 1142 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 1143 case ISD::FNEG: 1144 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 1145 case ISD::FMA: 1146 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 1147 } 1148 } 1149 1150 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 1151 SelectionDAG &DAG, unsigned Flags) { 1152 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 1153 } 1154 1155 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 1156 SelectionDAG &DAG, unsigned Flags) { 1157 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 1158 Flags); 1159 } 1160 1161 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 1162 SelectionDAG &DAG, unsigned Flags) { 1163 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 1164 N->getOffset(), Flags); 1165 } 1166 1167 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 1168 SelectionDAG &DAG, unsigned Flags) { 1169 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 1170 } 1171 1172 template <class NodeTy> 1173 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 1174 bool IsLocal) const { 1175 SDLoc DL(N); 1176 EVT Ty = getPointerTy(DAG.getDataLayout()); 1177 1178 if (isPositionIndependent()) { 1179 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 1180 if (IsLocal) 1181 // Use PC-relative addressing to access the symbol. This generates the 1182 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 1183 // %pcrel_lo(auipc)). 1184 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 1185 1186 // Use PC-relative addressing to access the GOT for this symbol, then load 1187 // the address from the GOT. This generates the pattern (PseudoLA sym), 1188 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 1189 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 1190 } 1191 1192 switch (getTargetMachine().getCodeModel()) { 1193 default: 1194 report_fatal_error("Unsupported code model for lowering"); 1195 case CodeModel::Small: { 1196 // Generate a sequence for accessing addresses within the first 2 GiB of 1197 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 1198 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 1199 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 1200 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 1201 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 1202 } 1203 case CodeModel::Medium: { 1204 // Generate a sequence for accessing addresses within any 2GiB range within 1205 // the address space. This generates the pattern (PseudoLLA sym), which 1206 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 1207 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 1208 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 1209 } 1210 } 1211 } 1212 1213 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 1214 SelectionDAG &DAG) const { 1215 SDLoc DL(Op); 1216 EVT Ty = Op.getValueType(); 1217 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 1218 int64_t Offset = N->getOffset(); 1219 MVT XLenVT = Subtarget.getXLenVT(); 1220 1221 const GlobalValue *GV = N->getGlobal(); 1222 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 1223 SDValue Addr = getAddr(N, DAG, IsLocal); 1224 1225 // In order to maximise the opportunity for common subexpression elimination, 1226 // emit a separate ADD node for the global address offset instead of folding 1227 // it in the global address node. Later peephole optimisations may choose to 1228 // fold it back in when profitable. 1229 if (Offset != 0) 1230 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 1231 DAG.getConstant(Offset, DL, XLenVT)); 1232 return Addr; 1233 } 1234 1235 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 1236 SelectionDAG &DAG) const { 1237 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 1238 1239 return getAddr(N, DAG); 1240 } 1241 1242 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 1243 SelectionDAG &DAG) const { 1244 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 1245 1246 return getAddr(N, DAG); 1247 } 1248 1249 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 1250 SelectionDAG &DAG) const { 1251 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 1252 1253 return getAddr(N, DAG); 1254 } 1255 1256 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 1257 SelectionDAG &DAG, 1258 bool UseGOT) const { 1259 SDLoc DL(N); 1260 EVT Ty = getPointerTy(DAG.getDataLayout()); 1261 const GlobalValue *GV = N->getGlobal(); 1262 MVT XLenVT = Subtarget.getXLenVT(); 1263 1264 if (UseGOT) { 1265 // Use PC-relative addressing to access the GOT for this TLS symbol, then 1266 // load the address from the GOT and add the thread pointer. This generates 1267 // the pattern (PseudoLA_TLS_IE sym), which expands to 1268 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 1269 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 1270 SDValue Load = 1271 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 1272 1273 // Add the thread pointer. 1274 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 1275 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 1276 } 1277 1278 // Generate a sequence for accessing the address relative to the thread 1279 // pointer, with the appropriate adjustment for the thread pointer offset. 1280 // This generates the pattern 1281 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 1282 SDValue AddrHi = 1283 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 1284 SDValue AddrAdd = 1285 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 1286 SDValue AddrLo = 1287 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 1288 1289 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 1290 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 1291 SDValue MNAdd = SDValue( 1292 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 1293 0); 1294 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 1295 } 1296 1297 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 1298 SelectionDAG &DAG) const { 1299 SDLoc DL(N); 1300 EVT Ty = getPointerTy(DAG.getDataLayout()); 1301 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 1302 const GlobalValue *GV = N->getGlobal(); 1303 1304 // Use a PC-relative addressing mode to access the global dynamic GOT address. 1305 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 1306 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 1307 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 1308 SDValue Load = 1309 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 1310 1311 // Prepare argument list to generate call. 1312 ArgListTy Args; 1313 ArgListEntry Entry; 1314 Entry.Node = Load; 1315 Entry.Ty = CallTy; 1316 Args.push_back(Entry); 1317 1318 // Setup call to __tls_get_addr. 1319 TargetLowering::CallLoweringInfo CLI(DAG); 1320 CLI.setDebugLoc(DL) 1321 .setChain(DAG.getEntryNode()) 1322 .setLibCallee(CallingConv::C, CallTy, 1323 DAG.getExternalSymbol("__tls_get_addr", Ty), 1324 std::move(Args)); 1325 1326 return LowerCallTo(CLI).first; 1327 } 1328 1329 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 1330 SelectionDAG &DAG) const { 1331 SDLoc DL(Op); 1332 EVT Ty = Op.getValueType(); 1333 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 1334 int64_t Offset = N->getOffset(); 1335 MVT XLenVT = Subtarget.getXLenVT(); 1336 1337 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 1338 1339 if (DAG.getMachineFunction().getFunction().getCallingConv() == 1340 CallingConv::GHC) 1341 report_fatal_error("In GHC calling convention TLS is not supported"); 1342 1343 SDValue Addr; 1344 switch (Model) { 1345 case TLSModel::LocalExec: 1346 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 1347 break; 1348 case TLSModel::InitialExec: 1349 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 1350 break; 1351 case TLSModel::LocalDynamic: 1352 case TLSModel::GeneralDynamic: 1353 Addr = getDynamicTLSAddr(N, DAG); 1354 break; 1355 } 1356 1357 // In order to maximise the opportunity for common subexpression elimination, 1358 // emit a separate ADD node for the global address offset instead of folding 1359 // it in the global address node. Later peephole optimisations may choose to 1360 // fold it back in when profitable. 1361 if (Offset != 0) 1362 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 1363 DAG.getConstant(Offset, DL, XLenVT)); 1364 return Addr; 1365 } 1366 1367 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 1368 SDValue CondV = Op.getOperand(0); 1369 SDValue TrueV = Op.getOperand(1); 1370 SDValue FalseV = Op.getOperand(2); 1371 SDLoc DL(Op); 1372 MVT XLenVT = Subtarget.getXLenVT(); 1373 1374 // If the result type is XLenVT and CondV is the output of a SETCC node 1375 // which also operated on XLenVT inputs, then merge the SETCC node into the 1376 // lowered RISCVISD::SELECT_CC to take advantage of the integer 1377 // compare+branch instructions. i.e.: 1378 // (select (setcc lhs, rhs, cc), truev, falsev) 1379 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 1380 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC && 1381 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 1382 SDValue LHS = CondV.getOperand(0); 1383 SDValue RHS = CondV.getOperand(1); 1384 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 1385 ISD::CondCode CCVal = CC->get(); 1386 1387 normaliseSetCC(LHS, RHS, CCVal); 1388 1389 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT); 1390 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 1391 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 1392 } 1393 1394 // Otherwise: 1395 // (select condv, truev, falsev) 1396 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 1397 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 1398 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT); 1399 1400 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 1401 1402 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 1403 } 1404 1405 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 1406 MachineFunction &MF = DAG.getMachineFunction(); 1407 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 1408 1409 SDLoc DL(Op); 1410 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 1411 getPointerTy(MF.getDataLayout())); 1412 1413 // vastart just stores the address of the VarArgsFrameIndex slot into the 1414 // memory location argument. 1415 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1416 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 1417 MachinePointerInfo(SV)); 1418 } 1419 1420 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 1421 SelectionDAG &DAG) const { 1422 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 1423 MachineFunction &MF = DAG.getMachineFunction(); 1424 MachineFrameInfo &MFI = MF.getFrameInfo(); 1425 MFI.setFrameAddressIsTaken(true); 1426 Register FrameReg = RI.getFrameRegister(MF); 1427 int XLenInBytes = Subtarget.getXLen() / 8; 1428 1429 EVT VT = Op.getValueType(); 1430 SDLoc DL(Op); 1431 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 1432 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1433 while (Depth--) { 1434 int Offset = -(XLenInBytes * 2); 1435 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 1436 DAG.getIntPtrConstant(Offset, DL)); 1437 FrameAddr = 1438 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 1439 } 1440 return FrameAddr; 1441 } 1442 1443 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 1444 SelectionDAG &DAG) const { 1445 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 1446 MachineFunction &MF = DAG.getMachineFunction(); 1447 MachineFrameInfo &MFI = MF.getFrameInfo(); 1448 MFI.setReturnAddressIsTaken(true); 1449 MVT XLenVT = Subtarget.getXLenVT(); 1450 int XLenInBytes = Subtarget.getXLen() / 8; 1451 1452 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 1453 return SDValue(); 1454 1455 EVT VT = Op.getValueType(); 1456 SDLoc DL(Op); 1457 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1458 if (Depth) { 1459 int Off = -XLenInBytes; 1460 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 1461 SDValue Offset = DAG.getConstant(Off, DL, VT); 1462 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 1463 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 1464 MachinePointerInfo()); 1465 } 1466 1467 // Return the value of the return address register, marking it an implicit 1468 // live-in. 1469 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 1470 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 1471 } 1472 1473 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 1474 SelectionDAG &DAG) const { 1475 SDLoc DL(Op); 1476 SDValue Lo = Op.getOperand(0); 1477 SDValue Hi = Op.getOperand(1); 1478 SDValue Shamt = Op.getOperand(2); 1479 EVT VT = Lo.getValueType(); 1480 1481 // if Shamt-XLEN < 0: // Shamt < XLEN 1482 // Lo = Lo << Shamt 1483 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 1484 // else: 1485 // Lo = 0 1486 // Hi = Lo << (Shamt-XLEN) 1487 1488 SDValue Zero = DAG.getConstant(0, DL, VT); 1489 SDValue One = DAG.getConstant(1, DL, VT); 1490 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 1491 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 1492 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 1493 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 1494 1495 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 1496 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 1497 SDValue ShiftRightLo = 1498 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 1499 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 1500 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 1501 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 1502 1503 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 1504 1505 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 1506 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 1507 1508 SDValue Parts[2] = {Lo, Hi}; 1509 return DAG.getMergeValues(Parts, DL); 1510 } 1511 1512 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 1513 bool IsSRA) const { 1514 SDLoc DL(Op); 1515 SDValue Lo = Op.getOperand(0); 1516 SDValue Hi = Op.getOperand(1); 1517 SDValue Shamt = Op.getOperand(2); 1518 EVT VT = Lo.getValueType(); 1519 1520 // SRA expansion: 1521 // if Shamt-XLEN < 0: // Shamt < XLEN 1522 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 1523 // Hi = Hi >>s Shamt 1524 // else: 1525 // Lo = Hi >>s (Shamt-XLEN); 1526 // Hi = Hi >>s (XLEN-1) 1527 // 1528 // SRL expansion: 1529 // if Shamt-XLEN < 0: // Shamt < XLEN 1530 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 1531 // Hi = Hi >>u Shamt 1532 // else: 1533 // Lo = Hi >>u (Shamt-XLEN); 1534 // Hi = 0; 1535 1536 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 1537 1538 SDValue Zero = DAG.getConstant(0, DL, VT); 1539 SDValue One = DAG.getConstant(1, DL, VT); 1540 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 1541 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 1542 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 1543 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 1544 1545 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 1546 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 1547 SDValue ShiftLeftHi = 1548 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 1549 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 1550 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 1551 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 1552 SDValue HiFalse = 1553 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 1554 1555 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 1556 1557 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 1558 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 1559 1560 SDValue Parts[2] = {Lo, Hi}; 1561 return DAG.getMergeValues(Parts, DL); 1562 } 1563 1564 // Custom-lower a SPLAT_VECTOR where XLEN<SEW, as the SEW element type is 1565 // illegal (currently only vXi64 RV32). 1566 // FIXME: We could also catch non-constant sign-extended i32 values and lower 1567 // them to SPLAT_VECTOR_I64 1568 SDValue RISCVTargetLowering::lowerSPLATVECTOR(SDValue Op, 1569 SelectionDAG &DAG) const { 1570 SDLoc DL(Op); 1571 EVT VecVT = Op.getValueType(); 1572 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 1573 "Unexpected SPLAT_VECTOR lowering"); 1574 SDValue SplatVal = Op.getOperand(0); 1575 1576 // If we can prove that the value is a sign-extended 32-bit value, lower this 1577 // as a custom node in order to try and match RVV vector/scalar instructions. 1578 if (auto *CVal = dyn_cast<ConstantSDNode>(SplatVal)) { 1579 if (isInt<32>(CVal->getSExtValue())) 1580 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, 1581 DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32)); 1582 } 1583 1584 if (SplatVal.getOpcode() == ISD::SIGN_EXTEND && 1585 SplatVal.getOperand(0).getValueType() == MVT::i32) { 1586 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, 1587 SplatVal.getOperand(0)); 1588 } 1589 1590 // Else, on RV32 we lower an i64-element SPLAT_VECTOR thus, being careful not 1591 // to accidentally sign-extend the 32-bit halves to the e64 SEW: 1592 // vmv.v.x vX, hi 1593 // vsll.vx vX, vX, /*32*/ 1594 // vmv.v.x vY, lo 1595 // vsll.vx vY, vY, /*32*/ 1596 // vsrl.vx vY, vY, /*32*/ 1597 // vor.vv vX, vX, vY 1598 SDValue One = DAG.getConstant(1, DL, MVT::i32); 1599 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 1600 SDValue ThirtyTwoV = DAG.getConstant(32, DL, VecVT); 1601 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, Zero); 1602 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, One); 1603 1604 Lo = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 1605 Lo = DAG.getNode(ISD::SHL, DL, VecVT, Lo, ThirtyTwoV); 1606 Lo = DAG.getNode(ISD::SRL, DL, VecVT, Lo, ThirtyTwoV); 1607 1608 if (isNullConstant(Hi)) 1609 return Lo; 1610 1611 Hi = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Hi); 1612 Hi = DAG.getNode(ISD::SHL, DL, VecVT, Hi, ThirtyTwoV); 1613 1614 return DAG.getNode(ISD::OR, DL, VecVT, Lo, Hi); 1615 } 1616 1617 // Custom-lower extensions from mask vectors by using a vselect either with 1 1618 // for zero/any-extension or -1 for sign-extension: 1619 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 1620 // Note that any-extension is lowered identically to zero-extension. 1621 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 1622 int64_t ExtTrueVal) const { 1623 SDLoc DL(Op); 1624 EVT VecVT = Op.getValueType(); 1625 SDValue Src = Op.getOperand(0); 1626 // Only custom-lower extensions from mask types 1627 if (!Src.getValueType().isVector() || 1628 Src.getValueType().getVectorElementType() != MVT::i1) 1629 return Op; 1630 1631 // Be careful not to introduce illegal scalar types at this stage, and be 1632 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 1633 // illegal and must be expanded. Since we know that the constants are 1634 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 1635 bool IsRV32E64 = 1636 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 1637 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1638 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, Subtarget.getXLenVT()); 1639 1640 if (!IsRV32E64) { 1641 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 1642 SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal); 1643 } else { 1644 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 1645 SplatTrueVal = 1646 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal); 1647 } 1648 1649 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 1650 } 1651 1652 // Custom-lower truncations from vectors to mask vectors by using a mask and a 1653 // setcc operation: 1654 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 1655 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op, 1656 SelectionDAG &DAG) const { 1657 SDLoc DL(Op); 1658 EVT MaskVT = Op.getValueType(); 1659 // Only expect to custom-lower truncations to mask types 1660 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 1661 "Unexpected type for vector mask lowering"); 1662 SDValue Src = Op.getOperand(0); 1663 EVT VecVT = Src.getValueType(); 1664 1665 // Be careful not to introduce illegal scalar types at this stage, and be 1666 // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is 1667 // illegal and must be expanded. Since we know that the constants are 1668 // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly. 1669 bool IsRV32E64 = 1670 !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64; 1671 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 1672 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1673 1674 if (!IsRV32E64) { 1675 SplatOne = DAG.getSplatVector(VecVT, DL, SplatOne); 1676 SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero); 1677 } else { 1678 SplatOne = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatOne); 1679 SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero); 1680 } 1681 1682 SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne); 1683 1684 return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE); 1685 } 1686 1687 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 1688 SelectionDAG &DAG) const { 1689 SDLoc DL(Op); 1690 EVT VecVT = Op.getValueType(); 1691 SDValue Vec = Op.getOperand(0); 1692 SDValue Val = Op.getOperand(1); 1693 SDValue Idx = Op.getOperand(2); 1694 1695 // Custom-legalize INSERT_VECTOR_ELT where XLEN>=SEW, so that the vector is 1696 // first slid down into position, the value is inserted into the first 1697 // position, and the vector is slid back up. We do this to simplify patterns. 1698 // (slideup vec, (insertelt (slidedown impdef, vec, idx), val, 0), idx), 1699 if (Subtarget.is64Bit() || VecVT.getVectorElementType() != MVT::i64) { 1700 if (isNullConstant(Idx)) 1701 return Op; 1702 SDValue Slidedown = DAG.getNode(RISCVISD::VSLIDEDOWN, DL, VecVT, 1703 DAG.getUNDEF(VecVT), Vec, Idx); 1704 SDValue InsertElt0 = 1705 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecVT, Slidedown, Val, 1706 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 1707 1708 return DAG.getNode(RISCVISD::VSLIDEUP, DL, VecVT, Vec, InsertElt0, Idx); 1709 } 1710 1711 // Custom-legalize INSERT_VECTOR_ELT where XLEN<SEW, as the SEW element type 1712 // is illegal (currently only vXi64 RV32). 1713 // Since there is no easy way of getting a single element into a vector when 1714 // XLEN<SEW, we lower the operation to the following sequence: 1715 // splat vVal, rVal 1716 // vid.v vVid 1717 // vmseq.vx mMask, vVid, rIdx 1718 // vmerge.vvm vDest, vSrc, vVal, mMask 1719 // This essentially merges the original vector with the inserted element by 1720 // using a mask whose only set bit is that corresponding to the insert 1721 // index. 1722 SDValue SplattedVal = DAG.getSplatVector(VecVT, DL, Val); 1723 SDValue SplattedIdx = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Idx); 1724 1725 SDValue VL = DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()); 1726 MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount()); 1727 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1728 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VecVT, Mask, VL); 1729 auto SetCCVT = 1730 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VecVT); 1731 SDValue SelectCond = DAG.getSetCC(DL, SetCCVT, VID, SplattedIdx, ISD::SETEQ); 1732 1733 return DAG.getNode(ISD::VSELECT, DL, VecVT, SelectCond, SplattedVal, Vec); 1734 } 1735 1736 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 1737 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 1738 // types this is done using VMV_X_S to allow us to glean information about the 1739 // sign bits of the result. 1740 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 1741 SelectionDAG &DAG) const { 1742 SDLoc DL(Op); 1743 SDValue Idx = Op.getOperand(1); 1744 SDValue Vec = Op.getOperand(0); 1745 EVT EltVT = Op.getValueType(); 1746 EVT VecVT = Vec.getValueType(); 1747 MVT XLenVT = Subtarget.getXLenVT(); 1748 1749 // If the index is 0, the vector is already in the right position. 1750 if (!isNullConstant(Idx)) { 1751 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN, DL, VecVT, DAG.getUNDEF(VecVT), Vec, 1752 Idx); 1753 } 1754 1755 if (!EltVT.isInteger()) { 1756 // Floating-point extracts are handled in TableGen. 1757 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 1758 DAG.getConstant(0, DL, XLenVT)); 1759 } 1760 1761 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 1762 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 1763 } 1764 1765 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 1766 SelectionDAG &DAG) const { 1767 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1768 SDLoc DL(Op); 1769 1770 if (Subtarget.hasStdExtV()) { 1771 // Some RVV intrinsics may claim that they want an integer operand to be 1772 // extended. 1773 if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1774 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) { 1775 if (II->ExtendedOperand) { 1776 assert(II->ExtendedOperand < Op.getNumOperands()); 1777 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 1778 SDValue &ScalarOp = Operands[II->ExtendedOperand]; 1779 EVT OpVT = ScalarOp.getValueType(); 1780 if (OpVT == MVT::i8 || OpVT == MVT::i16 || 1781 (OpVT == MVT::i32 && Subtarget.is64Bit())) { 1782 // If the operand is a constant, sign extend to increase our chances 1783 // of being able to use a .vi instruction. ANY_EXTEND would become a 1784 // a zero extend and the simm5 check in isel would fail. 1785 // FIXME: Should we ignore the upper bits in isel instead? 1786 unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND 1787 : ISD::ANY_EXTEND; 1788 ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp); 1789 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 1790 Operands); 1791 } 1792 } 1793 } 1794 } 1795 1796 switch (IntNo) { 1797 default: 1798 return SDValue(); // Don't custom lower most intrinsics. 1799 case Intrinsic::thread_pointer: { 1800 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 1801 return DAG.getRegister(RISCV::X4, PtrVT); 1802 } 1803 case Intrinsic::riscv_vmv_x_s: 1804 assert(Op.getValueType() == Subtarget.getXLenVT() && "Unexpected VT!"); 1805 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 1806 Op.getOperand(1)); 1807 case Intrinsic::riscv_vmv_v_x: { 1808 SDValue Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), 1809 Op.getOperand(1)); 1810 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, Op.getValueType(), 1811 Scalar, Op.getOperand(2)); 1812 } 1813 case Intrinsic::riscv_vfmv_v_f: 1814 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 1815 Op.getOperand(1), Op.getOperand(2)); 1816 } 1817 } 1818 1819 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 1820 SelectionDAG &DAG) const { 1821 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 1822 SDLoc DL(Op); 1823 1824 if (Subtarget.hasStdExtV()) { 1825 // Some RVV intrinsics may claim that they want an integer operand to be 1826 // extended. 1827 if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1828 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) { 1829 if (II->ExtendedOperand) { 1830 // The operands start from the second argument in INTRINSIC_W_CHAIN. 1831 unsigned ExtendOp = II->ExtendedOperand + 1; 1832 assert(ExtendOp < Op.getNumOperands()); 1833 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 1834 SDValue &ScalarOp = Operands[ExtendOp]; 1835 EVT OpVT = ScalarOp.getValueType(); 1836 if (OpVT == MVT::i8 || OpVT == MVT::i16 || 1837 (OpVT == MVT::i32 && Subtarget.is64Bit())) { 1838 // If the operand is a constant, sign extend to increase our chances 1839 // of being able to use a .vi instruction. ANY_EXTEND would become a 1840 // a zero extend and the simm5 check in isel would fail. 1841 // FIXME: Should we ignore the upper bits in isel instead? 1842 unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND 1843 : ISD::ANY_EXTEND; 1844 ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp); 1845 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, Op->getVTList(), 1846 Operands); 1847 } 1848 } 1849 } 1850 } 1851 1852 switch (IntNo) { 1853 default: 1854 return SDValue(); // Don't custom lower most intrinsics. 1855 case Intrinsic::riscv_vleff: { 1856 SDLoc DL(Op); 1857 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other, MVT::Glue); 1858 SDValue Load = DAG.getNode(RISCVISD::VLEFF, DL, VTs, Op.getOperand(0), 1859 Op.getOperand(2), Op.getOperand(3)); 1860 SDValue ReadVL = 1861 SDValue(DAG.getMachineNode(RISCV::PseudoReadVL, DL, Op->getValueType(1), 1862 Load.getValue(2)), 1863 0); 1864 return DAG.getMergeValues({Load, ReadVL, Load.getValue(1)}, DL); 1865 } 1866 case Intrinsic::riscv_vleff_mask: { 1867 SDLoc DL(Op); 1868 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other, MVT::Glue); 1869 SDValue Load = DAG.getNode(RISCVISD::VLEFF_MASK, DL, VTs, Op.getOperand(0), 1870 Op.getOperand(2), Op.getOperand(3), 1871 Op.getOperand(4), Op.getOperand(5)); 1872 SDValue ReadVL = 1873 SDValue(DAG.getMachineNode(RISCV::PseudoReadVL, DL, Op->getValueType(1), 1874 Load.getValue(2)), 1875 0); 1876 return DAG.getMergeValues({Load, ReadVL, Load.getValue(1)}, DL); 1877 } 1878 } 1879 } 1880 1881 static std::pair<unsigned, uint64_t> 1882 getRVVReductionOpAndIdentityVal(unsigned ISDOpcode, unsigned EltSizeBits) { 1883 switch (ISDOpcode) { 1884 default: 1885 llvm_unreachable("Unhandled reduction"); 1886 case ISD::VECREDUCE_ADD: 1887 return {RISCVISD::VECREDUCE_ADD, 0}; 1888 case ISD::VECREDUCE_UMAX: 1889 return {RISCVISD::VECREDUCE_UMAX, 0}; 1890 case ISD::VECREDUCE_SMAX: 1891 return {RISCVISD::VECREDUCE_SMAX, minIntN(EltSizeBits)}; 1892 case ISD::VECREDUCE_UMIN: 1893 return {RISCVISD::VECREDUCE_UMIN, maxUIntN(EltSizeBits)}; 1894 case ISD::VECREDUCE_SMIN: 1895 return {RISCVISD::VECREDUCE_SMIN, maxIntN(EltSizeBits)}; 1896 case ISD::VECREDUCE_AND: 1897 return {RISCVISD::VECREDUCE_AND, -1}; 1898 case ISD::VECREDUCE_OR: 1899 return {RISCVISD::VECREDUCE_OR, 0}; 1900 case ISD::VECREDUCE_XOR: 1901 return {RISCVISD::VECREDUCE_XOR, 0}; 1902 } 1903 } 1904 1905 // Take a (supported) standard ISD reduction opcode and transform it to a RISCV 1906 // reduction opcode. Note that this returns a vector type, which must be 1907 // further processed to access the scalar result in element 0. 1908 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 1909 SelectionDAG &DAG) const { 1910 SDLoc DL(Op); 1911 assert(Op.getValueType().isSimple() && 1912 Op.getOperand(0).getValueType().isSimple() && 1913 "Unexpected vector-reduce lowering"); 1914 MVT VecEltVT = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 1915 unsigned RVVOpcode; 1916 uint64_t IdentityVal; 1917 std::tie(RVVOpcode, IdentityVal) = 1918 getRVVReductionOpAndIdentityVal(Op.getOpcode(), VecEltVT.getSizeInBits()); 1919 // We have to perform a bit of a dance to get from our vector type to the 1920 // correct LMUL=1 vector type. We divide our minimum VLEN (64) by the vector 1921 // element type to find the type which fills a single register. Be careful to 1922 // use the operand's vector element type rather than the reduction's value 1923 // type, as that has likely been extended to XLEN. 1924 unsigned NumElts = 64 / VecEltVT.getSizeInBits(); 1925 MVT M1VT = MVT::getScalableVectorVT(VecEltVT, NumElts); 1926 SDValue IdentitySplat = 1927 DAG.getSplatVector(M1VT, DL, DAG.getConstant(IdentityVal, DL, VecEltVT)); 1928 SDValue Reduction = 1929 DAG.getNode(RVVOpcode, DL, M1VT, Op.getOperand(0), IdentitySplat); 1930 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 1931 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 1932 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 1933 } 1934 1935 // Given a reduction op, this function returns the matching reduction opcode, 1936 // the vector SDValue and the scalar SDValue required to lower this to a 1937 // RISCVISD node. 1938 static std::tuple<unsigned, SDValue, SDValue> 1939 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 1940 SDLoc DL(Op); 1941 switch (Op.getOpcode()) { 1942 default: 1943 llvm_unreachable("Unhandled reduction"); 1944 case ISD::VECREDUCE_FADD: 1945 return std::make_tuple(RISCVISD::VECREDUCE_FADD, Op.getOperand(0), 1946 DAG.getConstantFP(0.0, DL, EltVT)); 1947 case ISD::VECREDUCE_SEQ_FADD: 1948 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD, Op.getOperand(1), 1949 Op.getOperand(0)); 1950 } 1951 } 1952 1953 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 1954 SelectionDAG &DAG) const { 1955 SDLoc DL(Op); 1956 MVT VecEltVT = Op.getSimpleValueType(); 1957 // We have to perform a bit of a dance to get from our vector type to the 1958 // correct LMUL=1 vector type. See above for an explanation. 1959 unsigned NumElts = 64 / VecEltVT.getSizeInBits(); 1960 MVT M1VT = MVT::getScalableVectorVT(VecEltVT, NumElts); 1961 1962 unsigned RVVOpcode; 1963 SDValue VectorVal, ScalarVal; 1964 std::tie(RVVOpcode, VectorVal, ScalarVal) = 1965 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 1966 1967 SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal); 1968 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, VectorVal, ScalarSplat); 1969 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 1970 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 1971 } 1972 1973 SDValue 1974 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 1975 SelectionDAG &DAG) const { 1976 auto *Load = cast<LoadSDNode>(Op); 1977 1978 SDLoc DL(Op); 1979 MVT VT = Op.getSimpleValueType(); 1980 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1981 1982 SDValue VL = 1983 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 1984 1985 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 1986 SDValue NewLoad = DAG.getMemIntrinsicNode( 1987 RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL}, 1988 Load->getMemoryVT(), Load->getMemOperand()); 1989 1990 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 1991 return DAG.getMergeValues({Result, Load->getChain()}, DL); 1992 } 1993 1994 SDValue 1995 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 1996 SelectionDAG &DAG) const { 1997 auto *Store = cast<StoreSDNode>(Op); 1998 1999 SDLoc DL(Op); 2000 MVT VT = Store->getValue().getSimpleValueType(); 2001 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2002 2003 SDValue VL = 2004 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 2005 2006 SDValue NewValue = 2007 convertToScalableVector(ContainerVT, Store->getValue(), DAG, Subtarget); 2008 return DAG.getMemIntrinsicNode( 2009 RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other), 2010 {Store->getChain(), NewValue, Store->getBasePtr(), VL}, 2011 Store->getMemoryVT(), Store->getMemOperand()); 2012 } 2013 2014 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 2015 unsigned NewOpc) const { 2016 MVT VT = Op.getSimpleValueType(); 2017 assert(useRVVForFixedLengthVectorVT(VT) && 2018 "Only expected to lower fixed length vector operation!"); 2019 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2020 2021 // Create list of operands by converting existing ones to scalable types. 2022 SmallVector<SDValue, 6> Ops; 2023 for (const SDValue &V : Op->op_values()) { 2024 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 2025 2026 // Pass through non-vector operands. 2027 if (!V.getValueType().isVector()) { 2028 Ops.push_back(V); 2029 continue; 2030 } 2031 2032 // "cast" fixed length vector to a scalable vector. 2033 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 2034 "Only fixed length vectors are supported!"); 2035 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 2036 } 2037 2038 SDLoc DL(Op); 2039 SDValue VL = 2040 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 2041 MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 2042 SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 2043 Ops.push_back(Mask); 2044 Ops.push_back(VL); 2045 2046 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 2047 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 2048 } 2049 2050 // Returns the opcode of the target-specific SDNode that implements the 32-bit 2051 // form of the given Opcode. 2052 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 2053 switch (Opcode) { 2054 default: 2055 llvm_unreachable("Unexpected opcode"); 2056 case ISD::SHL: 2057 return RISCVISD::SLLW; 2058 case ISD::SRA: 2059 return RISCVISD::SRAW; 2060 case ISD::SRL: 2061 return RISCVISD::SRLW; 2062 case ISD::SDIV: 2063 return RISCVISD::DIVW; 2064 case ISD::UDIV: 2065 return RISCVISD::DIVUW; 2066 case ISD::UREM: 2067 return RISCVISD::REMUW; 2068 case ISD::ROTL: 2069 return RISCVISD::ROLW; 2070 case ISD::ROTR: 2071 return RISCVISD::RORW; 2072 case RISCVISD::GREVI: 2073 return RISCVISD::GREVIW; 2074 case RISCVISD::GORCI: 2075 return RISCVISD::GORCIW; 2076 } 2077 } 2078 2079 // Converts the given 32-bit operation to a target-specific SelectionDAG node. 2080 // Because i32 isn't a legal type for RV64, these operations would otherwise 2081 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W 2082 // later one because the fact the operation was originally of type i32 is 2083 // lost. 2084 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 2085 unsigned ExtOpc = ISD::ANY_EXTEND) { 2086 SDLoc DL(N); 2087 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 2088 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 2089 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 2090 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 2091 // ReplaceNodeResults requires we maintain the same type for the return value. 2092 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 2093 } 2094 2095 // Converts the given 32-bit operation to a i64 operation with signed extension 2096 // semantic to reduce the signed extension instructions. 2097 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 2098 SDLoc DL(N); 2099 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 2100 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 2101 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 2102 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 2103 DAG.getValueType(MVT::i32)); 2104 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 2105 } 2106 2107 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 2108 SmallVectorImpl<SDValue> &Results, 2109 SelectionDAG &DAG) const { 2110 SDLoc DL(N); 2111 switch (N->getOpcode()) { 2112 default: 2113 llvm_unreachable("Don't know how to custom type legalize this operation!"); 2114 case ISD::STRICT_FP_TO_SINT: 2115 case ISD::STRICT_FP_TO_UINT: 2116 case ISD::FP_TO_SINT: 2117 case ISD::FP_TO_UINT: { 2118 bool IsStrict = N->isStrictFPOpcode(); 2119 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 2120 "Unexpected custom legalisation"); 2121 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 2122 // If the FP type needs to be softened, emit a library call using the 'si' 2123 // version. If we left it to default legalization we'd end up with 'di'. If 2124 // the FP type doesn't need to be softened just let generic type 2125 // legalization promote the result type. 2126 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 2127 TargetLowering::TypeSoftenFloat) 2128 return; 2129 RTLIB::Libcall LC; 2130 if (N->getOpcode() == ISD::FP_TO_SINT || 2131 N->getOpcode() == ISD::STRICT_FP_TO_SINT) 2132 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 2133 else 2134 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 2135 MakeLibCallOptions CallOptions; 2136 EVT OpVT = Op0.getValueType(); 2137 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 2138 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 2139 SDValue Result; 2140 std::tie(Result, Chain) = 2141 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 2142 Results.push_back(Result); 2143 if (IsStrict) 2144 Results.push_back(Chain); 2145 break; 2146 } 2147 case ISD::READCYCLECOUNTER: { 2148 assert(!Subtarget.is64Bit() && 2149 "READCYCLECOUNTER only has custom type legalization on riscv32"); 2150 2151 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 2152 SDValue RCW = 2153 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 2154 2155 Results.push_back( 2156 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 2157 Results.push_back(RCW.getValue(2)); 2158 break; 2159 } 2160 case ISD::ADD: 2161 case ISD::SUB: 2162 case ISD::MUL: 2163 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 2164 "Unexpected custom legalisation"); 2165 if (N->getOperand(1).getOpcode() == ISD::Constant) 2166 return; 2167 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 2168 break; 2169 case ISD::SHL: 2170 case ISD::SRA: 2171 case ISD::SRL: 2172 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 2173 "Unexpected custom legalisation"); 2174 if (N->getOperand(1).getOpcode() == ISD::Constant) 2175 return; 2176 Results.push_back(customLegalizeToWOp(N, DAG)); 2177 break; 2178 case ISD::ROTL: 2179 case ISD::ROTR: 2180 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 2181 "Unexpected custom legalisation"); 2182 Results.push_back(customLegalizeToWOp(N, DAG)); 2183 break; 2184 case ISD::SDIV: 2185 case ISD::UDIV: 2186 case ISD::UREM: { 2187 MVT VT = N->getSimpleValueType(0); 2188 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 2189 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 2190 "Unexpected custom legalisation"); 2191 if (N->getOperand(0).getOpcode() == ISD::Constant || 2192 N->getOperand(1).getOpcode() == ISD::Constant) 2193 return; 2194 2195 // If the input is i32, use ANY_EXTEND since the W instructions don't read 2196 // the upper 32 bits. For other types we need to sign or zero extend 2197 // based on the opcode. 2198 unsigned ExtOpc = ISD::ANY_EXTEND; 2199 if (VT != MVT::i32) 2200 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 2201 : ISD::ZERO_EXTEND; 2202 2203 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 2204 break; 2205 } 2206 case ISD::BITCAST: { 2207 assert(((N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 2208 Subtarget.hasStdExtF()) || 2209 (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh())) && 2210 "Unexpected custom legalisation"); 2211 SDValue Op0 = N->getOperand(0); 2212 if (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh()) { 2213 if (Op0.getValueType() != MVT::f16) 2214 return; 2215 SDValue FPConv = 2216 DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, Subtarget.getXLenVT(), Op0); 2217 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 2218 } else if (N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 2219 Subtarget.hasStdExtF()) { 2220 if (Op0.getValueType() != MVT::f32) 2221 return; 2222 SDValue FPConv = 2223 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 2224 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 2225 } 2226 break; 2227 } 2228 case RISCVISD::GREVI: 2229 case RISCVISD::GORCI: { 2230 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 2231 "Unexpected custom legalisation"); 2232 // This is similar to customLegalizeToWOp, except that we pass the second 2233 // operand (a TargetConstant) straight through: it is already of type 2234 // XLenVT. 2235 SDLoc DL(N); 2236 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 2237 SDValue NewOp0 = 2238 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 2239 SDValue NewRes = 2240 DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, N->getOperand(1)); 2241 // ReplaceNodeResults requires we maintain the same type for the return 2242 // value. 2243 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 2244 break; 2245 } 2246 case ISD::BSWAP: 2247 case ISD::BITREVERSE: { 2248 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 2249 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 2250 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 2251 N->getOperand(0)); 2252 unsigned Imm = N->getOpcode() == ISD::BITREVERSE ? 31 : 24; 2253 SDValue GREVIW = DAG.getNode(RISCVISD::GREVIW, DL, MVT::i64, NewOp0, 2254 DAG.getTargetConstant(Imm, DL, 2255 Subtarget.getXLenVT())); 2256 // ReplaceNodeResults requires we maintain the same type for the return 2257 // value. 2258 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, GREVIW)); 2259 break; 2260 } 2261 case ISD::FSHL: 2262 case ISD::FSHR: { 2263 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 2264 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 2265 SDValue NewOp0 = 2266 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 2267 SDValue NewOp1 = 2268 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 2269 SDValue NewOp2 = 2270 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 2271 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 2272 // Mask the shift amount to 5 bits. 2273 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 2274 DAG.getConstant(0x1f, DL, MVT::i64)); 2275 unsigned Opc = 2276 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 2277 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 2278 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 2279 break; 2280 } 2281 case ISD::EXTRACT_VECTOR_ELT: { 2282 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 2283 // type is illegal (currently only vXi64 RV32). 2284 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 2285 // transferred to the destination register. We issue two of these from the 2286 // upper- and lower- halves of the SEW-bit vector element, slid down to the 2287 // first element. 2288 SDLoc DL(N); 2289 SDValue Vec = N->getOperand(0); 2290 SDValue Idx = N->getOperand(1); 2291 EVT VecVT = Vec.getValueType(); 2292 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 2293 VecVT.getVectorElementType() == MVT::i64 && 2294 "Unexpected EXTRACT_VECTOR_ELT legalization"); 2295 2296 SDValue Slidedown = Vec; 2297 // Unless the index is known to be 0, we must slide the vector down to get 2298 // the desired element into index 0. 2299 if (!isNullConstant(Idx)) 2300 Slidedown = DAG.getNode(RISCVISD::VSLIDEDOWN, DL, VecVT, 2301 DAG.getUNDEF(VecVT), Vec, Idx); 2302 2303 MVT XLenVT = Subtarget.getXLenVT(); 2304 // Extract the lower XLEN bits of the correct vector element. 2305 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Slidedown, Idx); 2306 2307 // To extract the upper XLEN bits of the vector element, shift the first 2308 // element right by 32 bits and re-extract the lower XLEN bits. 2309 SDValue ThirtyTwoV = 2310 DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, 2311 DAG.getConstant(32, DL, Subtarget.getXLenVT())); 2312 SDValue LShr32 = DAG.getNode(ISD::SRL, DL, VecVT, Slidedown, ThirtyTwoV); 2313 2314 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32, Idx); 2315 2316 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 2317 break; 2318 } 2319 case ISD::INTRINSIC_WO_CHAIN: { 2320 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 2321 switch (IntNo) { 2322 default: 2323 llvm_unreachable( 2324 "Don't know how to custom type legalize this intrinsic!"); 2325 case Intrinsic::riscv_vmv_x_s: { 2326 EVT VT = N->getValueType(0); 2327 assert((VT == MVT::i8 || VT == MVT::i16 || 2328 (Subtarget.is64Bit() && VT == MVT::i32)) && 2329 "Unexpected custom legalisation!"); 2330 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 2331 Subtarget.getXLenVT(), N->getOperand(1)); 2332 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 2333 break; 2334 } 2335 } 2336 break; 2337 } 2338 case ISD::VECREDUCE_ADD: 2339 case ISD::VECREDUCE_AND: 2340 case ISD::VECREDUCE_OR: 2341 case ISD::VECREDUCE_XOR: 2342 case ISD::VECREDUCE_SMAX: 2343 case ISD::VECREDUCE_UMAX: 2344 case ISD::VECREDUCE_SMIN: 2345 case ISD::VECREDUCE_UMIN: 2346 // The custom-lowering for these nodes returns a vector whose first element 2347 // is the result of the reduction. Extract its first element and let the 2348 // legalization for EXTRACT_VECTOR_ELT do the rest of the job. 2349 Results.push_back(lowerVECREDUCE(SDValue(N, 0), DAG)); 2350 break; 2351 } 2352 } 2353 2354 // A structure to hold one of the bit-manipulation patterns below. Together, a 2355 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 2356 // (or (and (shl x, 1), 0xAAAAAAAA), 2357 // (and (srl x, 1), 0x55555555)) 2358 struct RISCVBitmanipPat { 2359 SDValue Op; 2360 unsigned ShAmt; 2361 bool IsSHL; 2362 2363 bool formsPairWith(const RISCVBitmanipPat &Other) const { 2364 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 2365 } 2366 }; 2367 2368 // Matches any of the following bit-manipulation patterns: 2369 // (and (shl x, 1), (0x55555555 << 1)) 2370 // (and (srl x, 1), 0x55555555) 2371 // (shl (and x, 0x55555555), 1) 2372 // (srl (and x, (0x55555555 << 1)), 1) 2373 // where the shift amount and mask may vary thus: 2374 // [1] = 0x55555555 / 0xAAAAAAAA 2375 // [2] = 0x33333333 / 0xCCCCCCCC 2376 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 2377 // [8] = 0x00FF00FF / 0xFF00FF00 2378 // [16] = 0x0000FFFF / 0xFFFFFFFF 2379 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 2380 static Optional<RISCVBitmanipPat> matchRISCVBitmanipPat(SDValue Op) { 2381 Optional<uint64_t> Mask; 2382 // Optionally consume a mask around the shift operation. 2383 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 2384 Mask = Op.getConstantOperandVal(1); 2385 Op = Op.getOperand(0); 2386 } 2387 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 2388 return None; 2389 bool IsSHL = Op.getOpcode() == ISD::SHL; 2390 2391 if (!isa<ConstantSDNode>(Op.getOperand(1))) 2392 return None; 2393 auto ShAmt = Op.getConstantOperandVal(1); 2394 2395 if (!isPowerOf2_64(ShAmt)) 2396 return None; 2397 2398 // These are the unshifted masks which we use to match bit-manipulation 2399 // patterns. They may be shifted left in certain circumstances. 2400 static const uint64_t BitmanipMasks[] = { 2401 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 2402 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL, 2403 }; 2404 2405 unsigned MaskIdx = Log2_64(ShAmt); 2406 if (MaskIdx >= array_lengthof(BitmanipMasks)) 2407 return None; 2408 2409 auto Src = Op.getOperand(0); 2410 2411 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 2412 auto ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 2413 2414 // The expected mask is shifted left when the AND is found around SHL 2415 // patterns. 2416 // ((x >> 1) & 0x55555555) 2417 // ((x << 1) & 0xAAAAAAAA) 2418 bool SHLExpMask = IsSHL; 2419 2420 if (!Mask) { 2421 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 2422 // the mask is all ones: consume that now. 2423 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 2424 Mask = Src.getConstantOperandVal(1); 2425 Src = Src.getOperand(0); 2426 // The expected mask is now in fact shifted left for SRL, so reverse the 2427 // decision. 2428 // ((x & 0xAAAAAAAA) >> 1) 2429 // ((x & 0x55555555) << 1) 2430 SHLExpMask = !SHLExpMask; 2431 } else { 2432 // Use a default shifted mask of all-ones if there's no AND, truncated 2433 // down to the expected width. This simplifies the logic later on. 2434 Mask = maskTrailingOnes<uint64_t>(Width); 2435 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 2436 } 2437 } 2438 2439 if (SHLExpMask) 2440 ExpMask <<= ShAmt; 2441 2442 if (Mask != ExpMask) 2443 return None; 2444 2445 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 2446 } 2447 2448 // Match the following pattern as a GREVI(W) operation 2449 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 2450 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 2451 const RISCVSubtarget &Subtarget) { 2452 EVT VT = Op.getValueType(); 2453 2454 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 2455 auto LHS = matchRISCVBitmanipPat(Op.getOperand(0)); 2456 auto RHS = matchRISCVBitmanipPat(Op.getOperand(1)); 2457 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 2458 SDLoc DL(Op); 2459 return DAG.getNode( 2460 RISCVISD::GREVI, DL, VT, LHS->Op, 2461 DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT())); 2462 } 2463 } 2464 return SDValue(); 2465 } 2466 2467 // Matches any the following pattern as a GORCI(W) operation 2468 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 2469 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 2470 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 2471 // Note that with the variant of 3., 2472 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 2473 // the inner pattern will first be matched as GREVI and then the outer 2474 // pattern will be matched to GORC via the first rule above. 2475 // 4. (or (rotl/rotr x, bitwidth/2), x) 2476 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 2477 const RISCVSubtarget &Subtarget) { 2478 EVT VT = Op.getValueType(); 2479 2480 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 2481 SDLoc DL(Op); 2482 SDValue Op0 = Op.getOperand(0); 2483 SDValue Op1 = Op.getOperand(1); 2484 2485 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 2486 if (Reverse.getOpcode() == RISCVISD::GREVI && Reverse.getOperand(0) == X && 2487 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 2488 return DAG.getNode(RISCVISD::GORCI, DL, VT, X, Reverse.getOperand(1)); 2489 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 2490 if ((Reverse.getOpcode() == ISD::ROTL || 2491 Reverse.getOpcode() == ISD::ROTR) && 2492 Reverse.getOperand(0) == X && 2493 isa<ConstantSDNode>(Reverse.getOperand(1))) { 2494 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 2495 if (RotAmt == (VT.getSizeInBits() / 2)) 2496 return DAG.getNode( 2497 RISCVISD::GORCI, DL, VT, X, 2498 DAG.getTargetConstant(RotAmt, DL, Subtarget.getXLenVT())); 2499 } 2500 return SDValue(); 2501 }; 2502 2503 // Check for either commutable permutation of (or (GREVI x, shamt), x) 2504 if (SDValue V = MatchOROfReverse(Op0, Op1)) 2505 return V; 2506 if (SDValue V = MatchOROfReverse(Op1, Op0)) 2507 return V; 2508 2509 // OR is commutable so canonicalize its OR operand to the left 2510 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 2511 std::swap(Op0, Op1); 2512 if (Op0.getOpcode() != ISD::OR) 2513 return SDValue(); 2514 SDValue OrOp0 = Op0.getOperand(0); 2515 SDValue OrOp1 = Op0.getOperand(1); 2516 auto LHS = matchRISCVBitmanipPat(OrOp0); 2517 // OR is commutable so swap the operands and try again: x might have been 2518 // on the left 2519 if (!LHS) { 2520 std::swap(OrOp0, OrOp1); 2521 LHS = matchRISCVBitmanipPat(OrOp0); 2522 } 2523 auto RHS = matchRISCVBitmanipPat(Op1); 2524 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 2525 return DAG.getNode( 2526 RISCVISD::GORCI, DL, VT, LHS->Op, 2527 DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT())); 2528 } 2529 } 2530 return SDValue(); 2531 } 2532 2533 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 2534 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 2535 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 2536 // not undo itself, but they are redundant. 2537 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 2538 unsigned ShAmt1 = N->getConstantOperandVal(1); 2539 SDValue Src = N->getOperand(0); 2540 2541 if (Src.getOpcode() != N->getOpcode()) 2542 return SDValue(); 2543 2544 unsigned ShAmt2 = Src.getConstantOperandVal(1); 2545 Src = Src.getOperand(0); 2546 2547 unsigned CombinedShAmt; 2548 if (N->getOpcode() == RISCVISD::GORCI || N->getOpcode() == RISCVISD::GORCIW) 2549 CombinedShAmt = ShAmt1 | ShAmt2; 2550 else 2551 CombinedShAmt = ShAmt1 ^ ShAmt2; 2552 2553 if (CombinedShAmt == 0) 2554 return Src; 2555 2556 SDLoc DL(N); 2557 return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), Src, 2558 DAG.getTargetConstant(CombinedShAmt, DL, 2559 N->getOperand(1).getValueType())); 2560 } 2561 2562 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 2563 DAGCombinerInfo &DCI) const { 2564 SelectionDAG &DAG = DCI.DAG; 2565 2566 switch (N->getOpcode()) { 2567 default: 2568 break; 2569 case RISCVISD::SplitF64: { 2570 SDValue Op0 = N->getOperand(0); 2571 // If the input to SplitF64 is just BuildPairF64 then the operation is 2572 // redundant. Instead, use BuildPairF64's operands directly. 2573 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 2574 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 2575 2576 SDLoc DL(N); 2577 2578 // It's cheaper to materialise two 32-bit integers than to load a double 2579 // from the constant pool and transfer it to integer registers through the 2580 // stack. 2581 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 2582 APInt V = C->getValueAPF().bitcastToAPInt(); 2583 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 2584 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 2585 return DCI.CombineTo(N, Lo, Hi); 2586 } 2587 2588 // This is a target-specific version of a DAGCombine performed in 2589 // DAGCombiner::visitBITCAST. It performs the equivalent of: 2590 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 2591 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 2592 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 2593 !Op0.getNode()->hasOneUse()) 2594 break; 2595 SDValue NewSplitF64 = 2596 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 2597 Op0.getOperand(0)); 2598 SDValue Lo = NewSplitF64.getValue(0); 2599 SDValue Hi = NewSplitF64.getValue(1); 2600 APInt SignBit = APInt::getSignMask(32); 2601 if (Op0.getOpcode() == ISD::FNEG) { 2602 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 2603 DAG.getConstant(SignBit, DL, MVT::i32)); 2604 return DCI.CombineTo(N, Lo, NewHi); 2605 } 2606 assert(Op0.getOpcode() == ISD::FABS); 2607 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 2608 DAG.getConstant(~SignBit, DL, MVT::i32)); 2609 return DCI.CombineTo(N, Lo, NewHi); 2610 } 2611 case RISCVISD::SLLW: 2612 case RISCVISD::SRAW: 2613 case RISCVISD::SRLW: 2614 case RISCVISD::ROLW: 2615 case RISCVISD::RORW: { 2616 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 2617 SDValue LHS = N->getOperand(0); 2618 SDValue RHS = N->getOperand(1); 2619 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 2620 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5); 2621 if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) || 2622 SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) { 2623 if (N->getOpcode() != ISD::DELETED_NODE) 2624 DCI.AddToWorklist(N); 2625 return SDValue(N, 0); 2626 } 2627 break; 2628 } 2629 case RISCVISD::FSL: 2630 case RISCVISD::FSR: { 2631 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 2632 SDValue ShAmt = N->getOperand(2); 2633 unsigned BitWidth = ShAmt.getValueSizeInBits(); 2634 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 2635 APInt ShAmtMask(BitWidth, (BitWidth * 2) - 1); 2636 if (SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) { 2637 if (N->getOpcode() != ISD::DELETED_NODE) 2638 DCI.AddToWorklist(N); 2639 return SDValue(N, 0); 2640 } 2641 break; 2642 } 2643 case RISCVISD::FSLW: 2644 case RISCVISD::FSRW: { 2645 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 2646 // read. 2647 SDValue Op0 = N->getOperand(0); 2648 SDValue Op1 = N->getOperand(1); 2649 SDValue ShAmt = N->getOperand(2); 2650 APInt OpMask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32); 2651 APInt ShAmtMask = APInt::getLowBitsSet(ShAmt.getValueSizeInBits(), 6); 2652 if (SimplifyDemandedBits(Op0, OpMask, DCI) || 2653 SimplifyDemandedBits(Op1, OpMask, DCI) || 2654 SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) { 2655 if (N->getOpcode() != ISD::DELETED_NODE) 2656 DCI.AddToWorklist(N); 2657 return SDValue(N, 0); 2658 } 2659 break; 2660 } 2661 case RISCVISD::GREVIW: 2662 case RISCVISD::GORCIW: { 2663 // Only the lower 32 bits of the first operand are read 2664 SDValue Op0 = N->getOperand(0); 2665 APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32); 2666 if (SimplifyDemandedBits(Op0, Mask, DCI)) { 2667 if (N->getOpcode() != ISD::DELETED_NODE) 2668 DCI.AddToWorklist(N); 2669 return SDValue(N, 0); 2670 } 2671 2672 return combineGREVI_GORCI(N, DCI.DAG); 2673 } 2674 case RISCVISD::FMV_X_ANYEXTW_RV64: { 2675 SDLoc DL(N); 2676 SDValue Op0 = N->getOperand(0); 2677 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 2678 // conversion is unnecessary and can be replaced with an ANY_EXTEND 2679 // of the FMV_W_X_RV64 operand. 2680 if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) { 2681 assert(Op0.getOperand(0).getValueType() == MVT::i64 && 2682 "Unexpected value type!"); 2683 return Op0.getOperand(0); 2684 } 2685 2686 // This is a target-specific version of a DAGCombine performed in 2687 // DAGCombiner::visitBITCAST. It performs the equivalent of: 2688 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 2689 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 2690 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 2691 !Op0.getNode()->hasOneUse()) 2692 break; 2693 SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, 2694 Op0.getOperand(0)); 2695 APInt SignBit = APInt::getSignMask(32).sext(64); 2696 if (Op0.getOpcode() == ISD::FNEG) 2697 return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV, 2698 DAG.getConstant(SignBit, DL, MVT::i64)); 2699 2700 assert(Op0.getOpcode() == ISD::FABS); 2701 return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV, 2702 DAG.getConstant(~SignBit, DL, MVT::i64)); 2703 } 2704 case RISCVISD::GREVI: 2705 case RISCVISD::GORCI: 2706 return combineGREVI_GORCI(N, DCI.DAG); 2707 case ISD::OR: 2708 if (auto GREV = combineORToGREV(SDValue(N, 0), DCI.DAG, Subtarget)) 2709 return GREV; 2710 if (auto GORC = combineORToGORC(SDValue(N, 0), DCI.DAG, Subtarget)) 2711 return GORC; 2712 break; 2713 case RISCVISD::SELECT_CC: { 2714 // Transform 2715 // (select_cc (xor X, 1), 0, setne, trueV, falseV) -> 2716 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 2717 // This can occur when legalizing some floating point comparisons. 2718 SDValue LHS = N->getOperand(0); 2719 SDValue RHS = N->getOperand(1); 2720 auto CCVal = static_cast<ISD::CondCode>(N->getConstantOperandVal(2)); 2721 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 2722 if (ISD::isIntEqualitySetCC(CCVal) && isNullConstant(RHS) && 2723 LHS.getOpcode() == ISD::XOR && isOneConstant(LHS.getOperand(1)) && 2724 DAG.MaskedValueIsZero(LHS.getOperand(0), Mask)) { 2725 SDLoc DL(N); 2726 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 2727 SDValue TargetCC = DAG.getConstant(CCVal, DL, Subtarget.getXLenVT()); 2728 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 2729 {LHS.getOperand(0), RHS, TargetCC, N->getOperand(3), 2730 N->getOperand(4)}); 2731 } 2732 break; 2733 } 2734 case ISD::SETCC: { 2735 // (setcc X, 1, setne) -> (setcc X, 0, seteq) if we can prove X is 0/1. 2736 // Comparing with 0 may allow us to fold into bnez/beqz. 2737 SDValue LHS = N->getOperand(0); 2738 SDValue RHS = N->getOperand(1); 2739 if (LHS.getValueType().isScalableVector()) 2740 break; 2741 auto CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 2742 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 2743 if (isOneConstant(RHS) && ISD::isIntEqualitySetCC(CC) && 2744 DAG.MaskedValueIsZero(LHS, Mask)) { 2745 SDLoc DL(N); 2746 SDValue Zero = DAG.getConstant(0, DL, LHS.getValueType()); 2747 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 2748 return DAG.getSetCC(DL, N->getValueType(0), LHS, Zero, CC); 2749 } 2750 break; 2751 } 2752 } 2753 2754 return SDValue(); 2755 } 2756 2757 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 2758 const SDNode *N, CombineLevel Level) const { 2759 // The following folds are only desirable if `(OP _, c1 << c2)` can be 2760 // materialised in fewer instructions than `(OP _, c1)`: 2761 // 2762 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 2763 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 2764 SDValue N0 = N->getOperand(0); 2765 EVT Ty = N0.getValueType(); 2766 if (Ty.isScalarInteger() && 2767 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 2768 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 2769 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2770 if (C1 && C2) { 2771 const APInt &C1Int = C1->getAPIntValue(); 2772 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 2773 2774 // We can materialise `c1 << c2` into an add immediate, so it's "free", 2775 // and the combine should happen, to potentially allow further combines 2776 // later. 2777 if (ShiftedC1Int.getMinSignedBits() <= 64 && 2778 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 2779 return true; 2780 2781 // We can materialise `c1` in an add immediate, so it's "free", and the 2782 // combine should be prevented. 2783 if (C1Int.getMinSignedBits() <= 64 && 2784 isLegalAddImmediate(C1Int.getSExtValue())) 2785 return false; 2786 2787 // Neither constant will fit into an immediate, so find materialisation 2788 // costs. 2789 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 2790 Subtarget.is64Bit()); 2791 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 2792 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit()); 2793 2794 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 2795 // combine should be prevented. 2796 if (C1Cost < ShiftedC1Cost) 2797 return false; 2798 } 2799 } 2800 return true; 2801 } 2802 2803 bool RISCVTargetLowering::targetShrinkDemandedConstant( 2804 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 2805 TargetLoweringOpt &TLO) const { 2806 // Delay this optimization as late as possible. 2807 if (!TLO.LegalOps) 2808 return false; 2809 2810 EVT VT = Op.getValueType(); 2811 if (VT.isVector()) 2812 return false; 2813 2814 // Only handle AND for now. 2815 if (Op.getOpcode() != ISD::AND) 2816 return false; 2817 2818 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 2819 if (!C) 2820 return false; 2821 2822 const APInt &Mask = C->getAPIntValue(); 2823 2824 // Clear all non-demanded bits initially. 2825 APInt ShrunkMask = Mask & DemandedBits; 2826 2827 // If the shrunk mask fits in sign extended 12 bits, let the target 2828 // independent code apply it. 2829 if (ShrunkMask.isSignedIntN(12)) 2830 return false; 2831 2832 // Try to make a smaller immediate by setting undemanded bits. 2833 2834 // We need to be able to make a negative number through a combination of mask 2835 // and undemanded bits. 2836 APInt ExpandedMask = Mask | ~DemandedBits; 2837 if (!ExpandedMask.isNegative()) 2838 return false; 2839 2840 // What is the fewest number of bits we need to represent the negative number. 2841 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 2842 2843 // Try to make a 12 bit negative immediate. If that fails try to make a 32 2844 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 2845 APInt NewMask = ShrunkMask; 2846 if (MinSignedBits <= 12) 2847 NewMask.setBitsFrom(11); 2848 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 2849 NewMask.setBitsFrom(31); 2850 else 2851 return false; 2852 2853 // Sanity check that our new mask is a subset of the demanded mask. 2854 assert(NewMask.isSubsetOf(ExpandedMask)); 2855 2856 // If we aren't changing the mask, just return true to keep it and prevent 2857 // the caller from optimizing. 2858 if (NewMask == Mask) 2859 return true; 2860 2861 // Replace the constant with the new mask. 2862 SDLoc DL(Op); 2863 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 2864 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 2865 return TLO.CombineTo(Op, NewOp); 2866 } 2867 2868 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 2869 KnownBits &Known, 2870 const APInt &DemandedElts, 2871 const SelectionDAG &DAG, 2872 unsigned Depth) const { 2873 unsigned BitWidth = Known.getBitWidth(); 2874 unsigned Opc = Op.getOpcode(); 2875 assert((Opc >= ISD::BUILTIN_OP_END || 2876 Opc == ISD::INTRINSIC_WO_CHAIN || 2877 Opc == ISD::INTRINSIC_W_CHAIN || 2878 Opc == ISD::INTRINSIC_VOID) && 2879 "Should use MaskedValueIsZero if you don't know whether Op" 2880 " is a target node!"); 2881 2882 Known.resetAll(); 2883 switch (Opc) { 2884 default: break; 2885 case RISCVISD::REMUW: { 2886 KnownBits Known2; 2887 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2888 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2889 // We only care about the lower 32 bits. 2890 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 2891 // Restore the original width by sign extending. 2892 Known = Known.sext(BitWidth); 2893 break; 2894 } 2895 case RISCVISD::DIVUW: { 2896 KnownBits Known2; 2897 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2898 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2899 // We only care about the lower 32 bits. 2900 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 2901 // Restore the original width by sign extending. 2902 Known = Known.sext(BitWidth); 2903 break; 2904 } 2905 case RISCVISD::READ_VLENB: 2906 // We assume VLENB is at least 8 bytes. 2907 // FIXME: The 1.0 draft spec defines minimum VLEN as 128 bits. 2908 Known.Zero.setLowBits(3); 2909 break; 2910 } 2911 } 2912 2913 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 2914 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 2915 unsigned Depth) const { 2916 switch (Op.getOpcode()) { 2917 default: 2918 break; 2919 case RISCVISD::SLLW: 2920 case RISCVISD::SRAW: 2921 case RISCVISD::SRLW: 2922 case RISCVISD::DIVW: 2923 case RISCVISD::DIVUW: 2924 case RISCVISD::REMUW: 2925 case RISCVISD::ROLW: 2926 case RISCVISD::RORW: 2927 case RISCVISD::GREVIW: 2928 case RISCVISD::GORCIW: 2929 case RISCVISD::FSLW: 2930 case RISCVISD::FSRW: 2931 // TODO: As the result is sign-extended, this is conservatively correct. A 2932 // more precise answer could be calculated for SRAW depending on known 2933 // bits in the shift amount. 2934 return 33; 2935 case RISCVISD::VMV_X_S: 2936 // The number of sign bits of the scalar result is computed by obtaining the 2937 // element type of the input vector operand, subtracting its width from the 2938 // XLEN, and then adding one (sign bit within the element type). If the 2939 // element type is wider than XLen, the least-significant XLEN bits are 2940 // taken. 2941 if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen()) 2942 return 1; 2943 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 2944 } 2945 2946 return 1; 2947 } 2948 2949 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 2950 MachineBasicBlock *BB) { 2951 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 2952 2953 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 2954 // Should the count have wrapped while it was being read, we need to try 2955 // again. 2956 // ... 2957 // read: 2958 // rdcycleh x3 # load high word of cycle 2959 // rdcycle x2 # load low word of cycle 2960 // rdcycleh x4 # load high word of cycle 2961 // bne x3, x4, read # check if high word reads match, otherwise try again 2962 // ... 2963 2964 MachineFunction &MF = *BB->getParent(); 2965 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 2966 MachineFunction::iterator It = ++BB->getIterator(); 2967 2968 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 2969 MF.insert(It, LoopMBB); 2970 2971 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 2972 MF.insert(It, DoneMBB); 2973 2974 // Transfer the remainder of BB and its successor edges to DoneMBB. 2975 DoneMBB->splice(DoneMBB->begin(), BB, 2976 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 2977 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 2978 2979 BB->addSuccessor(LoopMBB); 2980 2981 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 2982 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 2983 Register LoReg = MI.getOperand(0).getReg(); 2984 Register HiReg = MI.getOperand(1).getReg(); 2985 DebugLoc DL = MI.getDebugLoc(); 2986 2987 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 2988 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 2989 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 2990 .addReg(RISCV::X0); 2991 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 2992 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 2993 .addReg(RISCV::X0); 2994 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 2995 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 2996 .addReg(RISCV::X0); 2997 2998 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 2999 .addReg(HiReg) 3000 .addReg(ReadAgainReg) 3001 .addMBB(LoopMBB); 3002 3003 LoopMBB->addSuccessor(LoopMBB); 3004 LoopMBB->addSuccessor(DoneMBB); 3005 3006 MI.eraseFromParent(); 3007 3008 return DoneMBB; 3009 } 3010 3011 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 3012 MachineBasicBlock *BB) { 3013 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 3014 3015 MachineFunction &MF = *BB->getParent(); 3016 DebugLoc DL = MI.getDebugLoc(); 3017 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 3018 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 3019 Register LoReg = MI.getOperand(0).getReg(); 3020 Register HiReg = MI.getOperand(1).getReg(); 3021 Register SrcReg = MI.getOperand(2).getReg(); 3022 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 3023 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 3024 3025 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 3026 RI); 3027 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 3028 MachineMemOperand *MMOLo = 3029 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 3030 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 3031 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 3032 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 3033 .addFrameIndex(FI) 3034 .addImm(0) 3035 .addMemOperand(MMOLo); 3036 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 3037 .addFrameIndex(FI) 3038 .addImm(4) 3039 .addMemOperand(MMOHi); 3040 MI.eraseFromParent(); // The pseudo instruction is gone now. 3041 return BB; 3042 } 3043 3044 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 3045 MachineBasicBlock *BB) { 3046 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 3047 "Unexpected instruction"); 3048 3049 MachineFunction &MF = *BB->getParent(); 3050 DebugLoc DL = MI.getDebugLoc(); 3051 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 3052 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 3053 Register DstReg = MI.getOperand(0).getReg(); 3054 Register LoReg = MI.getOperand(1).getReg(); 3055 Register HiReg = MI.getOperand(2).getReg(); 3056 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 3057 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 3058 3059 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 3060 MachineMemOperand *MMOLo = 3061 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 3062 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 3063 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 3064 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 3065 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 3066 .addFrameIndex(FI) 3067 .addImm(0) 3068 .addMemOperand(MMOLo); 3069 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 3070 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 3071 .addFrameIndex(FI) 3072 .addImm(4) 3073 .addMemOperand(MMOHi); 3074 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 3075 MI.eraseFromParent(); // The pseudo instruction is gone now. 3076 return BB; 3077 } 3078 3079 static bool isSelectPseudo(MachineInstr &MI) { 3080 switch (MI.getOpcode()) { 3081 default: 3082 return false; 3083 case RISCV::Select_GPR_Using_CC_GPR: 3084 case RISCV::Select_FPR16_Using_CC_GPR: 3085 case RISCV::Select_FPR32_Using_CC_GPR: 3086 case RISCV::Select_FPR64_Using_CC_GPR: 3087 return true; 3088 } 3089 } 3090 3091 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 3092 MachineBasicBlock *BB) { 3093 // To "insert" Select_* instructions, we actually have to insert the triangle 3094 // control-flow pattern. The incoming instructions know the destination vreg 3095 // to set, the condition code register to branch on, the true/false values to 3096 // select between, and the condcode to use to select the appropriate branch. 3097 // 3098 // We produce the following control flow: 3099 // HeadMBB 3100 // | \ 3101 // | IfFalseMBB 3102 // | / 3103 // TailMBB 3104 // 3105 // When we find a sequence of selects we attempt to optimize their emission 3106 // by sharing the control flow. Currently we only handle cases where we have 3107 // multiple selects with the exact same condition (same LHS, RHS and CC). 3108 // The selects may be interleaved with other instructions if the other 3109 // instructions meet some requirements we deem safe: 3110 // - They are debug instructions. Otherwise, 3111 // - They do not have side-effects, do not access memory and their inputs do 3112 // not depend on the results of the select pseudo-instructions. 3113 // The TrueV/FalseV operands of the selects cannot depend on the result of 3114 // previous selects in the sequence. 3115 // These conditions could be further relaxed. See the X86 target for a 3116 // related approach and more information. 3117 Register LHS = MI.getOperand(1).getReg(); 3118 Register RHS = MI.getOperand(2).getReg(); 3119 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm()); 3120 3121 SmallVector<MachineInstr *, 4> SelectDebugValues; 3122 SmallSet<Register, 4> SelectDests; 3123 SelectDests.insert(MI.getOperand(0).getReg()); 3124 3125 MachineInstr *LastSelectPseudo = &MI; 3126 3127 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 3128 SequenceMBBI != E; ++SequenceMBBI) { 3129 if (SequenceMBBI->isDebugInstr()) 3130 continue; 3131 else if (isSelectPseudo(*SequenceMBBI)) { 3132 if (SequenceMBBI->getOperand(1).getReg() != LHS || 3133 SequenceMBBI->getOperand(2).getReg() != RHS || 3134 SequenceMBBI->getOperand(3).getImm() != CC || 3135 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 3136 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 3137 break; 3138 LastSelectPseudo = &*SequenceMBBI; 3139 SequenceMBBI->collectDebugValues(SelectDebugValues); 3140 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 3141 } else { 3142 if (SequenceMBBI->hasUnmodeledSideEffects() || 3143 SequenceMBBI->mayLoadOrStore()) 3144 break; 3145 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 3146 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 3147 })) 3148 break; 3149 } 3150 } 3151 3152 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 3153 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 3154 DebugLoc DL = MI.getDebugLoc(); 3155 MachineFunction::iterator I = ++BB->getIterator(); 3156 3157 MachineBasicBlock *HeadMBB = BB; 3158 MachineFunction *F = BB->getParent(); 3159 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 3160 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 3161 3162 F->insert(I, IfFalseMBB); 3163 F->insert(I, TailMBB); 3164 3165 // Transfer debug instructions associated with the selects to TailMBB. 3166 for (MachineInstr *DebugInstr : SelectDebugValues) { 3167 TailMBB->push_back(DebugInstr->removeFromParent()); 3168 } 3169 3170 // Move all instructions after the sequence to TailMBB. 3171 TailMBB->splice(TailMBB->end(), HeadMBB, 3172 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 3173 // Update machine-CFG edges by transferring all successors of the current 3174 // block to the new block which will contain the Phi nodes for the selects. 3175 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 3176 // Set the successors for HeadMBB. 3177 HeadMBB->addSuccessor(IfFalseMBB); 3178 HeadMBB->addSuccessor(TailMBB); 3179 3180 // Insert appropriate branch. 3181 unsigned Opcode = getBranchOpcodeForIntCondCode(CC); 3182 3183 BuildMI(HeadMBB, DL, TII.get(Opcode)) 3184 .addReg(LHS) 3185 .addReg(RHS) 3186 .addMBB(TailMBB); 3187 3188 // IfFalseMBB just falls through to TailMBB. 3189 IfFalseMBB->addSuccessor(TailMBB); 3190 3191 // Create PHIs for all of the select pseudo-instructions. 3192 auto SelectMBBI = MI.getIterator(); 3193 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 3194 auto InsertionPoint = TailMBB->begin(); 3195 while (SelectMBBI != SelectEnd) { 3196 auto Next = std::next(SelectMBBI); 3197 if (isSelectPseudo(*SelectMBBI)) { 3198 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 3199 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 3200 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 3201 .addReg(SelectMBBI->getOperand(4).getReg()) 3202 .addMBB(HeadMBB) 3203 .addReg(SelectMBBI->getOperand(5).getReg()) 3204 .addMBB(IfFalseMBB); 3205 SelectMBBI->eraseFromParent(); 3206 } 3207 SelectMBBI = Next; 3208 } 3209 3210 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 3211 return TailMBB; 3212 } 3213 3214 static MachineBasicBlock *addVSetVL(MachineInstr &MI, MachineBasicBlock *BB, 3215 int VLIndex, unsigned SEWIndex, 3216 RISCVVLMUL VLMul, bool ForceTailAgnostic) { 3217 MachineFunction &MF = *BB->getParent(); 3218 DebugLoc DL = MI.getDebugLoc(); 3219 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 3220 3221 unsigned SEW = MI.getOperand(SEWIndex).getImm(); 3222 assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW"); 3223 RISCVVSEW ElementWidth = static_cast<RISCVVSEW>(Log2_32(SEW / 8)); 3224 3225 MachineRegisterInfo &MRI = MF.getRegInfo(); 3226 3227 // VL and VTYPE are alive here. 3228 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI)); 3229 3230 if (VLIndex >= 0) { 3231 // Set VL (rs1 != X0). 3232 Register DestReg = MRI.createVirtualRegister(&RISCV::GPRRegClass); 3233 MIB.addReg(DestReg, RegState::Define | RegState::Dead) 3234 .addReg(MI.getOperand(VLIndex).getReg()); 3235 } else 3236 // With no VL operator in the pseudo, do not modify VL (rd = X0, rs1 = X0). 3237 MIB.addReg(RISCV::X0, RegState::Define | RegState::Dead) 3238 .addReg(RISCV::X0, RegState::Kill); 3239 3240 // Default to tail agnostic unless the destination is tied to a source. In 3241 // that case the user would have some control over the tail values. The tail 3242 // policy is also ignored on instructions that only update element 0 like 3243 // vmv.s.x or reductions so use agnostic there to match the common case. 3244 // FIXME: This is conservatively correct, but we might want to detect that 3245 // the input is undefined. 3246 bool TailAgnostic = true; 3247 unsigned UseOpIdx; 3248 if (!ForceTailAgnostic && MI.isRegTiedToUseOperand(0, &UseOpIdx)) { 3249 TailAgnostic = false; 3250 // If the tied operand is an IMPLICIT_DEF we can keep TailAgnostic. 3251 const MachineOperand &UseMO = MI.getOperand(UseOpIdx); 3252 MachineInstr *UseMI = MRI.getVRegDef(UseMO.getReg()); 3253 if (UseMI && UseMI->isImplicitDef()) 3254 TailAgnostic = true; 3255 } 3256 3257 // For simplicity we reuse the vtype representation here. 3258 MIB.addImm(RISCVVType::encodeVTYPE(VLMul, ElementWidth, 3259 /*TailAgnostic*/ TailAgnostic, 3260 /*MaskAgnostic*/ false)); 3261 3262 // Remove (now) redundant operands from pseudo 3263 MI.getOperand(SEWIndex).setImm(-1); 3264 if (VLIndex >= 0) { 3265 MI.getOperand(VLIndex).setReg(RISCV::NoRegister); 3266 MI.getOperand(VLIndex).setIsKill(false); 3267 } 3268 3269 return BB; 3270 } 3271 3272 MachineBasicBlock * 3273 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 3274 MachineBasicBlock *BB) const { 3275 uint64_t TSFlags = MI.getDesc().TSFlags; 3276 3277 if (TSFlags & RISCVII::HasSEWOpMask) { 3278 unsigned NumOperands = MI.getNumExplicitOperands(); 3279 int VLIndex = (TSFlags & RISCVII::HasVLOpMask) ? NumOperands - 2 : -1; 3280 unsigned SEWIndex = NumOperands - 1; 3281 bool ForceTailAgnostic = TSFlags & RISCVII::ForceTailAgnosticMask; 3282 3283 RISCVVLMUL VLMul = static_cast<RISCVVLMUL>((TSFlags & RISCVII::VLMulMask) >> 3284 RISCVII::VLMulShift); 3285 return addVSetVL(MI, BB, VLIndex, SEWIndex, VLMul, ForceTailAgnostic); 3286 } 3287 3288 switch (MI.getOpcode()) { 3289 default: 3290 llvm_unreachable("Unexpected instr type to insert"); 3291 case RISCV::ReadCycleWide: 3292 assert(!Subtarget.is64Bit() && 3293 "ReadCycleWrite is only to be used on riscv32"); 3294 return emitReadCycleWidePseudo(MI, BB); 3295 case RISCV::Select_GPR_Using_CC_GPR: 3296 case RISCV::Select_FPR16_Using_CC_GPR: 3297 case RISCV::Select_FPR32_Using_CC_GPR: 3298 case RISCV::Select_FPR64_Using_CC_GPR: 3299 return emitSelectPseudo(MI, BB); 3300 case RISCV::BuildPairF64Pseudo: 3301 return emitBuildPairF64Pseudo(MI, BB); 3302 case RISCV::SplitF64Pseudo: 3303 return emitSplitF64Pseudo(MI, BB); 3304 } 3305 } 3306 3307 // Calling Convention Implementation. 3308 // The expectations for frontend ABI lowering vary from target to target. 3309 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 3310 // details, but this is a longer term goal. For now, we simply try to keep the 3311 // role of the frontend as simple and well-defined as possible. The rules can 3312 // be summarised as: 3313 // * Never split up large scalar arguments. We handle them here. 3314 // * If a hardfloat calling convention is being used, and the struct may be 3315 // passed in a pair of registers (fp+fp, int+fp), and both registers are 3316 // available, then pass as two separate arguments. If either the GPRs or FPRs 3317 // are exhausted, then pass according to the rule below. 3318 // * If a struct could never be passed in registers or directly in a stack 3319 // slot (as it is larger than 2*XLEN and the floating point rules don't 3320 // apply), then pass it using a pointer with the byval attribute. 3321 // * If a struct is less than 2*XLEN, then coerce to either a two-element 3322 // word-sized array or a 2*XLEN scalar (depending on alignment). 3323 // * The frontend can determine whether a struct is returned by reference or 3324 // not based on its size and fields. If it will be returned by reference, the 3325 // frontend must modify the prototype so a pointer with the sret annotation is 3326 // passed as the first argument. This is not necessary for large scalar 3327 // returns. 3328 // * Struct return values and varargs should be coerced to structs containing 3329 // register-size fields in the same situations they would be for fixed 3330 // arguments. 3331 3332 static const MCPhysReg ArgGPRs[] = { 3333 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 3334 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 3335 }; 3336 static const MCPhysReg ArgFPR16s[] = { 3337 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 3338 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 3339 }; 3340 static const MCPhysReg ArgFPR32s[] = { 3341 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 3342 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 3343 }; 3344 static const MCPhysReg ArgFPR64s[] = { 3345 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 3346 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 3347 }; 3348 // This is an interim calling convention and it may be changed in the future. 3349 static const MCPhysReg ArgVRs[] = { 3350 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 3351 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 3352 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 3353 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 3354 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 3355 RISCV::V20M2, RISCV::V22M2}; 3356 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 3357 RISCV::V20M4}; 3358 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 3359 3360 // Pass a 2*XLEN argument that has been split into two XLEN values through 3361 // registers or the stack as necessary. 3362 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 3363 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 3364 MVT ValVT2, MVT LocVT2, 3365 ISD::ArgFlagsTy ArgFlags2) { 3366 unsigned XLenInBytes = XLen / 8; 3367 if (Register Reg = State.AllocateReg(ArgGPRs)) { 3368 // At least one half can be passed via register. 3369 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 3370 VA1.getLocVT(), CCValAssign::Full)); 3371 } else { 3372 // Both halves must be passed on the stack, with proper alignment. 3373 Align StackAlign = 3374 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 3375 State.addLoc( 3376 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 3377 State.AllocateStack(XLenInBytes, StackAlign), 3378 VA1.getLocVT(), CCValAssign::Full)); 3379 State.addLoc(CCValAssign::getMem( 3380 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 3381 LocVT2, CCValAssign::Full)); 3382 return false; 3383 } 3384 3385 if (Register Reg = State.AllocateReg(ArgGPRs)) { 3386 // The second half can also be passed via register. 3387 State.addLoc( 3388 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 3389 } else { 3390 // The second half is passed via the stack, without additional alignment. 3391 State.addLoc(CCValAssign::getMem( 3392 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 3393 LocVT2, CCValAssign::Full)); 3394 } 3395 3396 return false; 3397 } 3398 3399 // Implements the RISC-V calling convention. Returns true upon failure. 3400 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 3401 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 3402 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 3403 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 3404 Optional<unsigned> FirstMaskArgument) { 3405 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 3406 assert(XLen == 32 || XLen == 64); 3407 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 3408 3409 // Any return value split in to more than two values can't be returned 3410 // directly. 3411 if (IsRet && ValNo > 1) 3412 return true; 3413 3414 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 3415 // variadic argument, or if no F16/F32 argument registers are available. 3416 bool UseGPRForF16_F32 = true; 3417 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 3418 // variadic argument, or if no F64 argument registers are available. 3419 bool UseGPRForF64 = true; 3420 3421 switch (ABI) { 3422 default: 3423 llvm_unreachable("Unexpected ABI"); 3424 case RISCVABI::ABI_ILP32: 3425 case RISCVABI::ABI_LP64: 3426 break; 3427 case RISCVABI::ABI_ILP32F: 3428 case RISCVABI::ABI_LP64F: 3429 UseGPRForF16_F32 = !IsFixed; 3430 break; 3431 case RISCVABI::ABI_ILP32D: 3432 case RISCVABI::ABI_LP64D: 3433 UseGPRForF16_F32 = !IsFixed; 3434 UseGPRForF64 = !IsFixed; 3435 break; 3436 } 3437 3438 // FPR16, FPR32, and FPR64 alias each other. 3439 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 3440 UseGPRForF16_F32 = true; 3441 UseGPRForF64 = true; 3442 } 3443 3444 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 3445 // similar local variables rather than directly checking against the target 3446 // ABI. 3447 3448 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 3449 LocVT = XLenVT; 3450 LocInfo = CCValAssign::BCvt; 3451 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 3452 LocVT = MVT::i64; 3453 LocInfo = CCValAssign::BCvt; 3454 } 3455 3456 // If this is a variadic argument, the RISC-V calling convention requires 3457 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 3458 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 3459 // be used regardless of whether the original argument was split during 3460 // legalisation or not. The argument will not be passed by registers if the 3461 // original type is larger than 2*XLEN, so the register alignment rule does 3462 // not apply. 3463 unsigned TwoXLenInBytes = (2 * XLen) / 8; 3464 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 3465 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 3466 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 3467 // Skip 'odd' register if necessary. 3468 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 3469 State.AllocateReg(ArgGPRs); 3470 } 3471 3472 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 3473 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 3474 State.getPendingArgFlags(); 3475 3476 assert(PendingLocs.size() == PendingArgFlags.size() && 3477 "PendingLocs and PendingArgFlags out of sync"); 3478 3479 // Handle passing f64 on RV32D with a soft float ABI or when floating point 3480 // registers are exhausted. 3481 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 3482 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 3483 "Can't lower f64 if it is split"); 3484 // Depending on available argument GPRS, f64 may be passed in a pair of 3485 // GPRs, split between a GPR and the stack, or passed completely on the 3486 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 3487 // cases. 3488 Register Reg = State.AllocateReg(ArgGPRs); 3489 LocVT = MVT::i32; 3490 if (!Reg) { 3491 unsigned StackOffset = State.AllocateStack(8, Align(8)); 3492 State.addLoc( 3493 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 3494 return false; 3495 } 3496 if (!State.AllocateReg(ArgGPRs)) 3497 State.AllocateStack(4, Align(4)); 3498 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3499 return false; 3500 } 3501 3502 // Split arguments might be passed indirectly, so keep track of the pending 3503 // values. 3504 if (ArgFlags.isSplit() || !PendingLocs.empty()) { 3505 LocVT = XLenVT; 3506 LocInfo = CCValAssign::Indirect; 3507 PendingLocs.push_back( 3508 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 3509 PendingArgFlags.push_back(ArgFlags); 3510 if (!ArgFlags.isSplitEnd()) { 3511 return false; 3512 } 3513 } 3514 3515 // If the split argument only had two elements, it should be passed directly 3516 // in registers or on the stack. 3517 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) { 3518 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 3519 // Apply the normal calling convention rules to the first half of the 3520 // split argument. 3521 CCValAssign VA = PendingLocs[0]; 3522 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 3523 PendingLocs.clear(); 3524 PendingArgFlags.clear(); 3525 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 3526 ArgFlags); 3527 } 3528 3529 // Allocate to a register if possible, or else a stack slot. 3530 Register Reg; 3531 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 3532 Reg = State.AllocateReg(ArgFPR16s); 3533 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 3534 Reg = State.AllocateReg(ArgFPR32s); 3535 else if (ValVT == MVT::f64 && !UseGPRForF64) 3536 Reg = State.AllocateReg(ArgFPR64s); 3537 else if (ValVT.isScalableVector()) { 3538 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 3539 if (RC == &RISCV::VRRegClass) { 3540 // Assign the first mask argument to V0. 3541 // This is an interim calling convention and it may be changed in the 3542 // future. 3543 if (FirstMaskArgument.hasValue() && 3544 ValNo == FirstMaskArgument.getValue()) { 3545 Reg = State.AllocateReg(RISCV::V0); 3546 } else { 3547 Reg = State.AllocateReg(ArgVRs); 3548 } 3549 } else if (RC == &RISCV::VRM2RegClass) { 3550 Reg = State.AllocateReg(ArgVRM2s); 3551 } else if (RC == &RISCV::VRM4RegClass) { 3552 Reg = State.AllocateReg(ArgVRM4s); 3553 } else if (RC == &RISCV::VRM8RegClass) { 3554 Reg = State.AllocateReg(ArgVRM8s); 3555 } else { 3556 llvm_unreachable("Unhandled class register for ValueType"); 3557 } 3558 if (!Reg) { 3559 LocInfo = CCValAssign::Indirect; 3560 // Try using a GPR to pass the address 3561 Reg = State.AllocateReg(ArgGPRs); 3562 LocVT = XLenVT; 3563 } 3564 } else 3565 Reg = State.AllocateReg(ArgGPRs); 3566 unsigned StackOffset = 3567 Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8)); 3568 3569 // If we reach this point and PendingLocs is non-empty, we must be at the 3570 // end of a split argument that must be passed indirectly. 3571 if (!PendingLocs.empty()) { 3572 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 3573 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 3574 3575 for (auto &It : PendingLocs) { 3576 if (Reg) 3577 It.convertToReg(Reg); 3578 else 3579 It.convertToMem(StackOffset); 3580 State.addLoc(It); 3581 } 3582 PendingLocs.clear(); 3583 PendingArgFlags.clear(); 3584 return false; 3585 } 3586 3587 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 3588 (TLI.getSubtarget().hasStdExtV() && ValVT.isScalableVector())) && 3589 "Expected an XLenVT or scalable vector types at this stage"); 3590 3591 if (Reg) { 3592 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3593 return false; 3594 } 3595 3596 // When a floating-point value is passed on the stack, no bit-conversion is 3597 // needed. 3598 if (ValVT.isFloatingPoint()) { 3599 LocVT = ValVT; 3600 LocInfo = CCValAssign::Full; 3601 } 3602 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 3603 return false; 3604 } 3605 3606 template <typename ArgTy> 3607 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 3608 for (const auto &ArgIdx : enumerate(Args)) { 3609 MVT ArgVT = ArgIdx.value().VT; 3610 if (ArgVT.isScalableVector() && 3611 ArgVT.getVectorElementType().SimpleTy == MVT::i1) 3612 return ArgIdx.index(); 3613 } 3614 return None; 3615 } 3616 3617 void RISCVTargetLowering::analyzeInputArgs( 3618 MachineFunction &MF, CCState &CCInfo, 3619 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const { 3620 unsigned NumArgs = Ins.size(); 3621 FunctionType *FType = MF.getFunction().getFunctionType(); 3622 3623 Optional<unsigned> FirstMaskArgument; 3624 if (Subtarget.hasStdExtV()) 3625 FirstMaskArgument = preAssignMask(Ins); 3626 3627 for (unsigned i = 0; i != NumArgs; ++i) { 3628 MVT ArgVT = Ins[i].VT; 3629 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 3630 3631 Type *ArgTy = nullptr; 3632 if (IsRet) 3633 ArgTy = FType->getReturnType(); 3634 else if (Ins[i].isOrigArg()) 3635 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 3636 3637 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 3638 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 3639 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 3640 FirstMaskArgument)) { 3641 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 3642 << EVT(ArgVT).getEVTString() << '\n'); 3643 llvm_unreachable(nullptr); 3644 } 3645 } 3646 } 3647 3648 void RISCVTargetLowering::analyzeOutputArgs( 3649 MachineFunction &MF, CCState &CCInfo, 3650 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 3651 CallLoweringInfo *CLI) const { 3652 unsigned NumArgs = Outs.size(); 3653 3654 Optional<unsigned> FirstMaskArgument; 3655 if (Subtarget.hasStdExtV()) 3656 FirstMaskArgument = preAssignMask(Outs); 3657 3658 for (unsigned i = 0; i != NumArgs; i++) { 3659 MVT ArgVT = Outs[i].VT; 3660 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3661 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 3662 3663 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 3664 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 3665 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 3666 FirstMaskArgument)) { 3667 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 3668 << EVT(ArgVT).getEVTString() << "\n"); 3669 llvm_unreachable(nullptr); 3670 } 3671 } 3672 } 3673 3674 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 3675 // values. 3676 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 3677 const CCValAssign &VA, const SDLoc &DL) { 3678 switch (VA.getLocInfo()) { 3679 default: 3680 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 3681 case CCValAssign::Full: 3682 break; 3683 case CCValAssign::BCvt: 3684 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 3685 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 3686 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 3687 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 3688 else 3689 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3690 break; 3691 } 3692 return Val; 3693 } 3694 3695 // The caller is responsible for loading the full value if the argument is 3696 // passed with CCValAssign::Indirect. 3697 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 3698 const CCValAssign &VA, const SDLoc &DL, 3699 const RISCVTargetLowering &TLI) { 3700 MachineFunction &MF = DAG.getMachineFunction(); 3701 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 3702 EVT LocVT = VA.getLocVT(); 3703 SDValue Val; 3704 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 3705 Register VReg = RegInfo.createVirtualRegister(RC); 3706 RegInfo.addLiveIn(VA.getLocReg(), VReg); 3707 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 3708 3709 if (VA.getLocInfo() == CCValAssign::Indirect) 3710 return Val; 3711 3712 return convertLocVTToValVT(DAG, Val, VA, DL); 3713 } 3714 3715 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 3716 const CCValAssign &VA, const SDLoc &DL) { 3717 EVT LocVT = VA.getLocVT(); 3718 3719 switch (VA.getLocInfo()) { 3720 default: 3721 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 3722 case CCValAssign::Full: 3723 break; 3724 case CCValAssign::BCvt: 3725 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 3726 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 3727 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 3728 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 3729 else 3730 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 3731 break; 3732 } 3733 return Val; 3734 } 3735 3736 // The caller is responsible for loading the full value if the argument is 3737 // passed with CCValAssign::Indirect. 3738 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 3739 const CCValAssign &VA, const SDLoc &DL) { 3740 MachineFunction &MF = DAG.getMachineFunction(); 3741 MachineFrameInfo &MFI = MF.getFrameInfo(); 3742 EVT LocVT = VA.getLocVT(); 3743 EVT ValVT = VA.getValVT(); 3744 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 3745 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8, 3746 VA.getLocMemOffset(), /*Immutable=*/true); 3747 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3748 SDValue Val; 3749 3750 ISD::LoadExtType ExtType; 3751 switch (VA.getLocInfo()) { 3752 default: 3753 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 3754 case CCValAssign::Full: 3755 case CCValAssign::Indirect: 3756 case CCValAssign::BCvt: 3757 ExtType = ISD::NON_EXTLOAD; 3758 break; 3759 } 3760 Val = DAG.getExtLoad( 3761 ExtType, DL, LocVT, Chain, FIN, 3762 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 3763 return Val; 3764 } 3765 3766 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 3767 const CCValAssign &VA, const SDLoc &DL) { 3768 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 3769 "Unexpected VA"); 3770 MachineFunction &MF = DAG.getMachineFunction(); 3771 MachineFrameInfo &MFI = MF.getFrameInfo(); 3772 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 3773 3774 if (VA.isMemLoc()) { 3775 // f64 is passed on the stack. 3776 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 3777 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 3778 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 3779 MachinePointerInfo::getFixedStack(MF, FI)); 3780 } 3781 3782 assert(VA.isRegLoc() && "Expected register VA assignment"); 3783 3784 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 3785 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 3786 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 3787 SDValue Hi; 3788 if (VA.getLocReg() == RISCV::X17) { 3789 // Second half of f64 is passed on the stack. 3790 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 3791 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 3792 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 3793 MachinePointerInfo::getFixedStack(MF, FI)); 3794 } else { 3795 // Second half of f64 is passed in another GPR. 3796 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 3797 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 3798 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 3799 } 3800 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 3801 } 3802 3803 // FastCC has less than 1% performance improvement for some particular 3804 // benchmark. But theoretically, it may has benenfit for some cases. 3805 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT, 3806 CCValAssign::LocInfo LocInfo, 3807 ISD::ArgFlagsTy ArgFlags, CCState &State) { 3808 3809 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 3810 // X5 and X6 might be used for save-restore libcall. 3811 static const MCPhysReg GPRList[] = { 3812 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 3813 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 3814 RISCV::X29, RISCV::X30, RISCV::X31}; 3815 if (unsigned Reg = State.AllocateReg(GPRList)) { 3816 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3817 return false; 3818 } 3819 } 3820 3821 if (LocVT == MVT::f16) { 3822 static const MCPhysReg FPR16List[] = { 3823 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 3824 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 3825 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 3826 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 3827 if (unsigned Reg = State.AllocateReg(FPR16List)) { 3828 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3829 return false; 3830 } 3831 } 3832 3833 if (LocVT == MVT::f32) { 3834 static const MCPhysReg FPR32List[] = { 3835 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 3836 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 3837 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 3838 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 3839 if (unsigned Reg = State.AllocateReg(FPR32List)) { 3840 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3841 return false; 3842 } 3843 } 3844 3845 if (LocVT == MVT::f64) { 3846 static const MCPhysReg FPR64List[] = { 3847 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 3848 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 3849 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 3850 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 3851 if (unsigned Reg = State.AllocateReg(FPR64List)) { 3852 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3853 return false; 3854 } 3855 } 3856 3857 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 3858 unsigned Offset4 = State.AllocateStack(4, Align(4)); 3859 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 3860 return false; 3861 } 3862 3863 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 3864 unsigned Offset5 = State.AllocateStack(8, Align(8)); 3865 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 3866 return false; 3867 } 3868 3869 return true; // CC didn't match. 3870 } 3871 3872 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 3873 CCValAssign::LocInfo LocInfo, 3874 ISD::ArgFlagsTy ArgFlags, CCState &State) { 3875 3876 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 3877 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 3878 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 3879 static const MCPhysReg GPRList[] = { 3880 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 3881 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 3882 if (unsigned Reg = State.AllocateReg(GPRList)) { 3883 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3884 return false; 3885 } 3886 } 3887 3888 if (LocVT == MVT::f32) { 3889 // Pass in STG registers: F1, ..., F6 3890 // fs0 ... fs5 3891 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 3892 RISCV::F18_F, RISCV::F19_F, 3893 RISCV::F20_F, RISCV::F21_F}; 3894 if (unsigned Reg = State.AllocateReg(FPR32List)) { 3895 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3896 return false; 3897 } 3898 } 3899 3900 if (LocVT == MVT::f64) { 3901 // Pass in STG registers: D1, ..., D6 3902 // fs6 ... fs11 3903 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 3904 RISCV::F24_D, RISCV::F25_D, 3905 RISCV::F26_D, RISCV::F27_D}; 3906 if (unsigned Reg = State.AllocateReg(FPR64List)) { 3907 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 3908 return false; 3909 } 3910 } 3911 3912 report_fatal_error("No registers left in GHC calling convention"); 3913 return true; 3914 } 3915 3916 // Transform physical registers into virtual registers. 3917 SDValue RISCVTargetLowering::LowerFormalArguments( 3918 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 3919 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3920 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3921 3922 MachineFunction &MF = DAG.getMachineFunction(); 3923 3924 switch (CallConv) { 3925 default: 3926 report_fatal_error("Unsupported calling convention"); 3927 case CallingConv::C: 3928 case CallingConv::Fast: 3929 break; 3930 case CallingConv::GHC: 3931 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 3932 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 3933 report_fatal_error( 3934 "GHC calling convention requires the F and D instruction set extensions"); 3935 } 3936 3937 const Function &Func = MF.getFunction(); 3938 if (Func.hasFnAttribute("interrupt")) { 3939 if (!Func.arg_empty()) 3940 report_fatal_error( 3941 "Functions with the interrupt attribute cannot have arguments!"); 3942 3943 StringRef Kind = 3944 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 3945 3946 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 3947 report_fatal_error( 3948 "Function interrupt attribute argument not supported!"); 3949 } 3950 3951 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3952 MVT XLenVT = Subtarget.getXLenVT(); 3953 unsigned XLenInBytes = Subtarget.getXLen() / 8; 3954 // Used with vargs to acumulate store chains. 3955 std::vector<SDValue> OutChains; 3956 3957 // Assign locations to all of the incoming arguments. 3958 SmallVector<CCValAssign, 16> ArgLocs; 3959 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3960 3961 if (CallConv == CallingConv::Fast) 3962 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC); 3963 else if (CallConv == CallingConv::GHC) 3964 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 3965 else 3966 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false); 3967 3968 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3969 CCValAssign &VA = ArgLocs[i]; 3970 SDValue ArgValue; 3971 // Passing f64 on RV32D with a soft float ABI must be handled as a special 3972 // case. 3973 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 3974 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 3975 else if (VA.isRegLoc()) 3976 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 3977 else 3978 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 3979 3980 if (VA.getLocInfo() == CCValAssign::Indirect) { 3981 // If the original argument was split and passed by reference (e.g. i128 3982 // on RV32), we need to load all parts of it here (using the same 3983 // address). 3984 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 3985 MachinePointerInfo())); 3986 unsigned ArgIndex = Ins[i].OrigArgIndex; 3987 assert(Ins[i].PartOffset == 0); 3988 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 3989 CCValAssign &PartVA = ArgLocs[i + 1]; 3990 unsigned PartOffset = Ins[i + 1].PartOffset; 3991 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, 3992 DAG.getIntPtrConstant(PartOffset, DL)); 3993 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 3994 MachinePointerInfo())); 3995 ++i; 3996 } 3997 continue; 3998 } 3999 InVals.push_back(ArgValue); 4000 } 4001 4002 if (IsVarArg) { 4003 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 4004 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 4005 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 4006 MachineFrameInfo &MFI = MF.getFrameInfo(); 4007 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4008 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 4009 4010 // Offset of the first variable argument from stack pointer, and size of 4011 // the vararg save area. For now, the varargs save area is either zero or 4012 // large enough to hold a0-a7. 4013 int VaArgOffset, VarArgsSaveSize; 4014 4015 // If all registers are allocated, then all varargs must be passed on the 4016 // stack and we don't need to save any argregs. 4017 if (ArgRegs.size() == Idx) { 4018 VaArgOffset = CCInfo.getNextStackOffset(); 4019 VarArgsSaveSize = 0; 4020 } else { 4021 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 4022 VaArgOffset = -VarArgsSaveSize; 4023 } 4024 4025 // Record the frame index of the first variable argument 4026 // which is a value necessary to VASTART. 4027 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 4028 RVFI->setVarArgsFrameIndex(FI); 4029 4030 // If saving an odd number of registers then create an extra stack slot to 4031 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 4032 // offsets to even-numbered registered remain 2*XLEN-aligned. 4033 if (Idx % 2) { 4034 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 4035 VarArgsSaveSize += XLenInBytes; 4036 } 4037 4038 // Copy the integer registers that may have been used for passing varargs 4039 // to the vararg save area. 4040 for (unsigned I = Idx; I < ArgRegs.size(); 4041 ++I, VaArgOffset += XLenInBytes) { 4042 const Register Reg = RegInfo.createVirtualRegister(RC); 4043 RegInfo.addLiveIn(ArgRegs[I], Reg); 4044 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 4045 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 4046 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4047 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 4048 MachinePointerInfo::getFixedStack(MF, FI)); 4049 cast<StoreSDNode>(Store.getNode()) 4050 ->getMemOperand() 4051 ->setValue((Value *)nullptr); 4052 OutChains.push_back(Store); 4053 } 4054 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 4055 } 4056 4057 // All stores are grouped in one node to allow the matching between 4058 // the size of Ins and InVals. This only happens for vararg functions. 4059 if (!OutChains.empty()) { 4060 OutChains.push_back(Chain); 4061 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 4062 } 4063 4064 return Chain; 4065 } 4066 4067 /// isEligibleForTailCallOptimization - Check whether the call is eligible 4068 /// for tail call optimization. 4069 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 4070 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 4071 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 4072 const SmallVector<CCValAssign, 16> &ArgLocs) const { 4073 4074 auto &Callee = CLI.Callee; 4075 auto CalleeCC = CLI.CallConv; 4076 auto &Outs = CLI.Outs; 4077 auto &Caller = MF.getFunction(); 4078 auto CallerCC = Caller.getCallingConv(); 4079 4080 // Exception-handling functions need a special set of instructions to 4081 // indicate a return to the hardware. Tail-calling another function would 4082 // probably break this. 4083 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 4084 // should be expanded as new function attributes are introduced. 4085 if (Caller.hasFnAttribute("interrupt")) 4086 return false; 4087 4088 // Do not tail call opt if the stack is used to pass parameters. 4089 if (CCInfo.getNextStackOffset() != 0) 4090 return false; 4091 4092 // Do not tail call opt if any parameters need to be passed indirectly. 4093 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 4094 // passed indirectly. So the address of the value will be passed in a 4095 // register, or if not available, then the address is put on the stack. In 4096 // order to pass indirectly, space on the stack often needs to be allocated 4097 // in order to store the value. In this case the CCInfo.getNextStackOffset() 4098 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 4099 // are passed CCValAssign::Indirect. 4100 for (auto &VA : ArgLocs) 4101 if (VA.getLocInfo() == CCValAssign::Indirect) 4102 return false; 4103 4104 // Do not tail call opt if either caller or callee uses struct return 4105 // semantics. 4106 auto IsCallerStructRet = Caller.hasStructRetAttr(); 4107 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 4108 if (IsCallerStructRet || IsCalleeStructRet) 4109 return false; 4110 4111 // Externally-defined functions with weak linkage should not be 4112 // tail-called. The behaviour of branch instructions in this situation (as 4113 // used for tail calls) is implementation-defined, so we cannot rely on the 4114 // linker replacing the tail call with a return. 4115 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4116 const GlobalValue *GV = G->getGlobal(); 4117 if (GV->hasExternalWeakLinkage()) 4118 return false; 4119 } 4120 4121 // The callee has to preserve all registers the caller needs to preserve. 4122 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4123 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 4124 if (CalleeCC != CallerCC) { 4125 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 4126 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 4127 return false; 4128 } 4129 4130 // Byval parameters hand the function a pointer directly into the stack area 4131 // we want to reuse during a tail call. Working around this *is* possible 4132 // but less efficient and uglier in LowerCall. 4133 for (auto &Arg : Outs) 4134 if (Arg.Flags.isByVal()) 4135 return false; 4136 4137 return true; 4138 } 4139 4140 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 4141 // and output parameter nodes. 4142 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 4143 SmallVectorImpl<SDValue> &InVals) const { 4144 SelectionDAG &DAG = CLI.DAG; 4145 SDLoc &DL = CLI.DL; 4146 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 4147 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 4148 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 4149 SDValue Chain = CLI.Chain; 4150 SDValue Callee = CLI.Callee; 4151 bool &IsTailCall = CLI.IsTailCall; 4152 CallingConv::ID CallConv = CLI.CallConv; 4153 bool IsVarArg = CLI.IsVarArg; 4154 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4155 MVT XLenVT = Subtarget.getXLenVT(); 4156 4157 MachineFunction &MF = DAG.getMachineFunction(); 4158 4159 // Analyze the operands of the call, assigning locations to each operand. 4160 SmallVector<CCValAssign, 16> ArgLocs; 4161 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 4162 4163 if (CallConv == CallingConv::Fast) 4164 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC); 4165 else if (CallConv == CallingConv::GHC) 4166 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 4167 else 4168 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI); 4169 4170 // Check if it's really possible to do a tail call. 4171 if (IsTailCall) 4172 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 4173 4174 if (IsTailCall) 4175 ++NumTailCalls; 4176 else if (CLI.CB && CLI.CB->isMustTailCall()) 4177 report_fatal_error("failed to perform tail call elimination on a call " 4178 "site marked musttail"); 4179 4180 // Get a count of how many bytes are to be pushed on the stack. 4181 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 4182 4183 // Create local copies for byval args 4184 SmallVector<SDValue, 8> ByValArgs; 4185 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 4186 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4187 if (!Flags.isByVal()) 4188 continue; 4189 4190 SDValue Arg = OutVals[i]; 4191 unsigned Size = Flags.getByValSize(); 4192 Align Alignment = Flags.getNonZeroByValAlign(); 4193 4194 int FI = 4195 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 4196 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4197 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 4198 4199 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 4200 /*IsVolatile=*/false, 4201 /*AlwaysInline=*/false, IsTailCall, 4202 MachinePointerInfo(), MachinePointerInfo()); 4203 ByValArgs.push_back(FIPtr); 4204 } 4205 4206 if (!IsTailCall) 4207 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 4208 4209 // Copy argument values to their designated locations. 4210 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 4211 SmallVector<SDValue, 8> MemOpChains; 4212 SDValue StackPtr; 4213 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 4214 CCValAssign &VA = ArgLocs[i]; 4215 SDValue ArgValue = OutVals[i]; 4216 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4217 4218 // Handle passing f64 on RV32D with a soft float ABI as a special case. 4219 bool IsF64OnRV32DSoftABI = 4220 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 4221 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 4222 SDValue SplitF64 = DAG.getNode( 4223 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 4224 SDValue Lo = SplitF64.getValue(0); 4225 SDValue Hi = SplitF64.getValue(1); 4226 4227 Register RegLo = VA.getLocReg(); 4228 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 4229 4230 if (RegLo == RISCV::X17) { 4231 // Second half of f64 is passed on the stack. 4232 // Work out the address of the stack slot. 4233 if (!StackPtr.getNode()) 4234 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 4235 // Emit the store. 4236 MemOpChains.push_back( 4237 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 4238 } else { 4239 // Second half of f64 is passed in another GPR. 4240 assert(RegLo < RISCV::X31 && "Invalid register pair"); 4241 Register RegHigh = RegLo + 1; 4242 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 4243 } 4244 continue; 4245 } 4246 4247 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 4248 // as any other MemLoc. 4249 4250 // Promote the value if needed. 4251 // For now, only handle fully promoted and indirect arguments. 4252 if (VA.getLocInfo() == CCValAssign::Indirect) { 4253 // Store the argument in a stack slot and pass its address. 4254 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT); 4255 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 4256 MemOpChains.push_back( 4257 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 4258 MachinePointerInfo::getFixedStack(MF, FI))); 4259 // If the original argument was split (e.g. i128), we need 4260 // to store all parts of it here (and pass just one address). 4261 unsigned ArgIndex = Outs[i].OrigArgIndex; 4262 assert(Outs[i].PartOffset == 0); 4263 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 4264 SDValue PartValue = OutVals[i + 1]; 4265 unsigned PartOffset = Outs[i + 1].PartOffset; 4266 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, 4267 DAG.getIntPtrConstant(PartOffset, DL)); 4268 MemOpChains.push_back( 4269 DAG.getStore(Chain, DL, PartValue, Address, 4270 MachinePointerInfo::getFixedStack(MF, FI))); 4271 ++i; 4272 } 4273 ArgValue = SpillSlot; 4274 } else { 4275 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL); 4276 } 4277 4278 // Use local copy if it is a byval arg. 4279 if (Flags.isByVal()) 4280 ArgValue = ByValArgs[j++]; 4281 4282 if (VA.isRegLoc()) { 4283 // Queue up the argument copies and emit them at the end. 4284 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 4285 } else { 4286 assert(VA.isMemLoc() && "Argument not register or memory"); 4287 assert(!IsTailCall && "Tail call not allowed if stack is used " 4288 "for passing parameters"); 4289 4290 // Work out the address of the stack slot. 4291 if (!StackPtr.getNode()) 4292 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 4293 SDValue Address = 4294 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 4295 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 4296 4297 // Emit the store. 4298 MemOpChains.push_back( 4299 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 4300 } 4301 } 4302 4303 // Join the stores, which are independent of one another. 4304 if (!MemOpChains.empty()) 4305 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 4306 4307 SDValue Glue; 4308 4309 // Build a sequence of copy-to-reg nodes, chained and glued together. 4310 for (auto &Reg : RegsToPass) { 4311 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 4312 Glue = Chain.getValue(1); 4313 } 4314 4315 // Validate that none of the argument registers have been marked as 4316 // reserved, if so report an error. Do the same for the return address if this 4317 // is not a tailcall. 4318 validateCCReservedRegs(RegsToPass, MF); 4319 if (!IsTailCall && 4320 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 4321 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 4322 MF.getFunction(), 4323 "Return address register required, but has been reserved."}); 4324 4325 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 4326 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 4327 // split it and then direct call can be matched by PseudoCALL. 4328 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 4329 const GlobalValue *GV = S->getGlobal(); 4330 4331 unsigned OpFlags = RISCVII::MO_CALL; 4332 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 4333 OpFlags = RISCVII::MO_PLT; 4334 4335 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 4336 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4337 unsigned OpFlags = RISCVII::MO_CALL; 4338 4339 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 4340 nullptr)) 4341 OpFlags = RISCVII::MO_PLT; 4342 4343 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 4344 } 4345 4346 // The first call operand is the chain and the second is the target address. 4347 SmallVector<SDValue, 8> Ops; 4348 Ops.push_back(Chain); 4349 Ops.push_back(Callee); 4350 4351 // Add argument registers to the end of the list so that they are 4352 // known live into the call. 4353 for (auto &Reg : RegsToPass) 4354 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 4355 4356 if (!IsTailCall) { 4357 // Add a register mask operand representing the call-preserved registers. 4358 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4359 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 4360 assert(Mask && "Missing call preserved mask for calling convention"); 4361 Ops.push_back(DAG.getRegisterMask(Mask)); 4362 } 4363 4364 // Glue the call to the argument copies, if any. 4365 if (Glue.getNode()) 4366 Ops.push_back(Glue); 4367 4368 // Emit the call. 4369 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 4370 4371 if (IsTailCall) { 4372 MF.getFrameInfo().setHasTailCall(); 4373 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 4374 } 4375 4376 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 4377 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 4378 Glue = Chain.getValue(1); 4379 4380 // Mark the end of the call, which is glued to the call itself. 4381 Chain = DAG.getCALLSEQ_END(Chain, 4382 DAG.getConstant(NumBytes, DL, PtrVT, true), 4383 DAG.getConstant(0, DL, PtrVT, true), 4384 Glue, DL); 4385 Glue = Chain.getValue(1); 4386 4387 // Assign locations to each value returned by this call. 4388 SmallVector<CCValAssign, 16> RVLocs; 4389 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 4390 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true); 4391 4392 // Copy all of the result registers out of their specified physreg. 4393 for (auto &VA : RVLocs) { 4394 // Copy the value out 4395 SDValue RetValue = 4396 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 4397 // Glue the RetValue to the end of the call sequence 4398 Chain = RetValue.getValue(1); 4399 Glue = RetValue.getValue(2); 4400 4401 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 4402 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 4403 SDValue RetValue2 = 4404 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 4405 Chain = RetValue2.getValue(1); 4406 Glue = RetValue2.getValue(2); 4407 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 4408 RetValue2); 4409 } 4410 4411 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL); 4412 4413 InVals.push_back(RetValue); 4414 } 4415 4416 return Chain; 4417 } 4418 4419 bool RISCVTargetLowering::CanLowerReturn( 4420 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 4421 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 4422 SmallVector<CCValAssign, 16> RVLocs; 4423 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 4424 4425 Optional<unsigned> FirstMaskArgument; 4426 if (Subtarget.hasStdExtV()) 4427 FirstMaskArgument = preAssignMask(Outs); 4428 4429 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 4430 MVT VT = Outs[i].VT; 4431 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4432 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 4433 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 4434 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 4435 *this, FirstMaskArgument)) 4436 return false; 4437 } 4438 return true; 4439 } 4440 4441 SDValue 4442 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 4443 bool IsVarArg, 4444 const SmallVectorImpl<ISD::OutputArg> &Outs, 4445 const SmallVectorImpl<SDValue> &OutVals, 4446 const SDLoc &DL, SelectionDAG &DAG) const { 4447 const MachineFunction &MF = DAG.getMachineFunction(); 4448 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 4449 4450 // Stores the assignment of the return value to a location. 4451 SmallVector<CCValAssign, 16> RVLocs; 4452 4453 // Info about the registers and stack slot. 4454 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 4455 *DAG.getContext()); 4456 4457 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 4458 nullptr); 4459 4460 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 4461 report_fatal_error("GHC functions return void only"); 4462 4463 SDValue Glue; 4464 SmallVector<SDValue, 4> RetOps(1, Chain); 4465 4466 // Copy the result values into the output registers. 4467 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 4468 SDValue Val = OutVals[i]; 4469 CCValAssign &VA = RVLocs[i]; 4470 assert(VA.isRegLoc() && "Can only return in registers!"); 4471 4472 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 4473 // Handle returning f64 on RV32D with a soft float ABI. 4474 assert(VA.isRegLoc() && "Expected return via registers"); 4475 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 4476 DAG.getVTList(MVT::i32, MVT::i32), Val); 4477 SDValue Lo = SplitF64.getValue(0); 4478 SDValue Hi = SplitF64.getValue(1); 4479 Register RegLo = VA.getLocReg(); 4480 assert(RegLo < RISCV::X31 && "Invalid register pair"); 4481 Register RegHi = RegLo + 1; 4482 4483 if (STI.isRegisterReservedByUser(RegLo) || 4484 STI.isRegisterReservedByUser(RegHi)) 4485 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 4486 MF.getFunction(), 4487 "Return value register required, but has been reserved."}); 4488 4489 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 4490 Glue = Chain.getValue(1); 4491 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 4492 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 4493 Glue = Chain.getValue(1); 4494 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 4495 } else { 4496 // Handle a 'normal' return. 4497 Val = convertValVTToLocVT(DAG, Val, VA, DL); 4498 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 4499 4500 if (STI.isRegisterReservedByUser(VA.getLocReg())) 4501 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 4502 MF.getFunction(), 4503 "Return value register required, but has been reserved."}); 4504 4505 // Guarantee that all emitted copies are stuck together. 4506 Glue = Chain.getValue(1); 4507 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 4508 } 4509 } 4510 4511 RetOps[0] = Chain; // Update chain. 4512 4513 // Add the glue node if we have it. 4514 if (Glue.getNode()) { 4515 RetOps.push_back(Glue); 4516 } 4517 4518 // Interrupt service routines use different return instructions. 4519 const Function &Func = DAG.getMachineFunction().getFunction(); 4520 if (Func.hasFnAttribute("interrupt")) { 4521 if (!Func.getReturnType()->isVoidTy()) 4522 report_fatal_error( 4523 "Functions with the interrupt attribute must have void return type!"); 4524 4525 MachineFunction &MF = DAG.getMachineFunction(); 4526 StringRef Kind = 4527 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 4528 4529 unsigned RetOpc; 4530 if (Kind == "user") 4531 RetOpc = RISCVISD::URET_FLAG; 4532 else if (Kind == "supervisor") 4533 RetOpc = RISCVISD::SRET_FLAG; 4534 else 4535 RetOpc = RISCVISD::MRET_FLAG; 4536 4537 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 4538 } 4539 4540 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps); 4541 } 4542 4543 void RISCVTargetLowering::validateCCReservedRegs( 4544 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 4545 MachineFunction &MF) const { 4546 const Function &F = MF.getFunction(); 4547 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 4548 4549 if (llvm::any_of(Regs, [&STI](auto Reg) { 4550 return STI.isRegisterReservedByUser(Reg.first); 4551 })) 4552 F.getContext().diagnose(DiagnosticInfoUnsupported{ 4553 F, "Argument register required, but has been reserved."}); 4554 } 4555 4556 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 4557 return CI->isTailCall(); 4558 } 4559 4560 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 4561 #define NODE_NAME_CASE(NODE) \ 4562 case RISCVISD::NODE: \ 4563 return "RISCVISD::" #NODE; 4564 // clang-format off 4565 switch ((RISCVISD::NodeType)Opcode) { 4566 case RISCVISD::FIRST_NUMBER: 4567 break; 4568 NODE_NAME_CASE(RET_FLAG) 4569 NODE_NAME_CASE(URET_FLAG) 4570 NODE_NAME_CASE(SRET_FLAG) 4571 NODE_NAME_CASE(MRET_FLAG) 4572 NODE_NAME_CASE(CALL) 4573 NODE_NAME_CASE(SELECT_CC) 4574 NODE_NAME_CASE(BuildPairF64) 4575 NODE_NAME_CASE(SplitF64) 4576 NODE_NAME_CASE(TAIL) 4577 NODE_NAME_CASE(SLLW) 4578 NODE_NAME_CASE(SRAW) 4579 NODE_NAME_CASE(SRLW) 4580 NODE_NAME_CASE(DIVW) 4581 NODE_NAME_CASE(DIVUW) 4582 NODE_NAME_CASE(REMUW) 4583 NODE_NAME_CASE(ROLW) 4584 NODE_NAME_CASE(RORW) 4585 NODE_NAME_CASE(FSLW) 4586 NODE_NAME_CASE(FSRW) 4587 NODE_NAME_CASE(FSL) 4588 NODE_NAME_CASE(FSR) 4589 NODE_NAME_CASE(FMV_H_X) 4590 NODE_NAME_CASE(FMV_X_ANYEXTH) 4591 NODE_NAME_CASE(FMV_W_X_RV64) 4592 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 4593 NODE_NAME_CASE(READ_CYCLE_WIDE) 4594 NODE_NAME_CASE(GREVI) 4595 NODE_NAME_CASE(GREVIW) 4596 NODE_NAME_CASE(GORCI) 4597 NODE_NAME_CASE(GORCIW) 4598 NODE_NAME_CASE(VMV_V_X_VL) 4599 NODE_NAME_CASE(VFMV_V_F_VL) 4600 NODE_NAME_CASE(VMV_X_S) 4601 NODE_NAME_CASE(SPLAT_VECTOR_I64) 4602 NODE_NAME_CASE(READ_VLENB) 4603 NODE_NAME_CASE(TRUNCATE_VECTOR) 4604 NODE_NAME_CASE(VLEFF) 4605 NODE_NAME_CASE(VLEFF_MASK) 4606 NODE_NAME_CASE(VSLIDEUP) 4607 NODE_NAME_CASE(VSLIDEDOWN) 4608 NODE_NAME_CASE(VID_VL) 4609 NODE_NAME_CASE(VFNCVT_ROD) 4610 NODE_NAME_CASE(VECREDUCE_ADD) 4611 NODE_NAME_CASE(VECREDUCE_UMAX) 4612 NODE_NAME_CASE(VECREDUCE_SMAX) 4613 NODE_NAME_CASE(VECREDUCE_UMIN) 4614 NODE_NAME_CASE(VECREDUCE_SMIN) 4615 NODE_NAME_CASE(VECREDUCE_AND) 4616 NODE_NAME_CASE(VECREDUCE_OR) 4617 NODE_NAME_CASE(VECREDUCE_XOR) 4618 NODE_NAME_CASE(VECREDUCE_FADD) 4619 NODE_NAME_CASE(VECREDUCE_SEQ_FADD) 4620 NODE_NAME_CASE(ADD_VL) 4621 NODE_NAME_CASE(AND_VL) 4622 NODE_NAME_CASE(MUL_VL) 4623 NODE_NAME_CASE(OR_VL) 4624 NODE_NAME_CASE(SDIV_VL) 4625 NODE_NAME_CASE(SHL_VL) 4626 NODE_NAME_CASE(SREM_VL) 4627 NODE_NAME_CASE(SRA_VL) 4628 NODE_NAME_CASE(SRL_VL) 4629 NODE_NAME_CASE(SUB_VL) 4630 NODE_NAME_CASE(UDIV_VL) 4631 NODE_NAME_CASE(UREM_VL) 4632 NODE_NAME_CASE(XOR_VL) 4633 NODE_NAME_CASE(FADD_VL) 4634 NODE_NAME_CASE(FSUB_VL) 4635 NODE_NAME_CASE(FMUL_VL) 4636 NODE_NAME_CASE(FDIV_VL) 4637 NODE_NAME_CASE(FNEG_VL) 4638 NODE_NAME_CASE(FMA_VL) 4639 NODE_NAME_CASE(VMCLR_VL) 4640 NODE_NAME_CASE(VMSET_VL) 4641 NODE_NAME_CASE(VLE_VL) 4642 NODE_NAME_CASE(VSE_VL) 4643 } 4644 // clang-format on 4645 return nullptr; 4646 #undef NODE_NAME_CASE 4647 } 4648 4649 /// getConstraintType - Given a constraint letter, return the type of 4650 /// constraint it is for this target. 4651 RISCVTargetLowering::ConstraintType 4652 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 4653 if (Constraint.size() == 1) { 4654 switch (Constraint[0]) { 4655 default: 4656 break; 4657 case 'f': 4658 return C_RegisterClass; 4659 case 'I': 4660 case 'J': 4661 case 'K': 4662 return C_Immediate; 4663 case 'A': 4664 return C_Memory; 4665 } 4666 } 4667 return TargetLowering::getConstraintType(Constraint); 4668 } 4669 4670 std::pair<unsigned, const TargetRegisterClass *> 4671 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 4672 StringRef Constraint, 4673 MVT VT) const { 4674 // First, see if this is a constraint that directly corresponds to a 4675 // RISCV register class. 4676 if (Constraint.size() == 1) { 4677 switch (Constraint[0]) { 4678 case 'r': 4679 return std::make_pair(0U, &RISCV::GPRRegClass); 4680 case 'f': 4681 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 4682 return std::make_pair(0U, &RISCV::FPR16RegClass); 4683 if (Subtarget.hasStdExtF() && VT == MVT::f32) 4684 return std::make_pair(0U, &RISCV::FPR32RegClass); 4685 if (Subtarget.hasStdExtD() && VT == MVT::f64) 4686 return std::make_pair(0U, &RISCV::FPR64RegClass); 4687 break; 4688 default: 4689 break; 4690 } 4691 } 4692 4693 // Clang will correctly decode the usage of register name aliases into their 4694 // official names. However, other frontends like `rustc` do not. This allows 4695 // users of these frontends to use the ABI names for registers in LLVM-style 4696 // register constraints. 4697 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 4698 .Case("{zero}", RISCV::X0) 4699 .Case("{ra}", RISCV::X1) 4700 .Case("{sp}", RISCV::X2) 4701 .Case("{gp}", RISCV::X3) 4702 .Case("{tp}", RISCV::X4) 4703 .Case("{t0}", RISCV::X5) 4704 .Case("{t1}", RISCV::X6) 4705 .Case("{t2}", RISCV::X7) 4706 .Cases("{s0}", "{fp}", RISCV::X8) 4707 .Case("{s1}", RISCV::X9) 4708 .Case("{a0}", RISCV::X10) 4709 .Case("{a1}", RISCV::X11) 4710 .Case("{a2}", RISCV::X12) 4711 .Case("{a3}", RISCV::X13) 4712 .Case("{a4}", RISCV::X14) 4713 .Case("{a5}", RISCV::X15) 4714 .Case("{a6}", RISCV::X16) 4715 .Case("{a7}", RISCV::X17) 4716 .Case("{s2}", RISCV::X18) 4717 .Case("{s3}", RISCV::X19) 4718 .Case("{s4}", RISCV::X20) 4719 .Case("{s5}", RISCV::X21) 4720 .Case("{s6}", RISCV::X22) 4721 .Case("{s7}", RISCV::X23) 4722 .Case("{s8}", RISCV::X24) 4723 .Case("{s9}", RISCV::X25) 4724 .Case("{s10}", RISCV::X26) 4725 .Case("{s11}", RISCV::X27) 4726 .Case("{t3}", RISCV::X28) 4727 .Case("{t4}", RISCV::X29) 4728 .Case("{t5}", RISCV::X30) 4729 .Case("{t6}", RISCV::X31) 4730 .Default(RISCV::NoRegister); 4731 if (XRegFromAlias != RISCV::NoRegister) 4732 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 4733 4734 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 4735 // TableGen record rather than the AsmName to choose registers for InlineAsm 4736 // constraints, plus we want to match those names to the widest floating point 4737 // register type available, manually select floating point registers here. 4738 // 4739 // The second case is the ABI name of the register, so that frontends can also 4740 // use the ABI names in register constraint lists. 4741 if (Subtarget.hasStdExtF()) { 4742 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 4743 .Cases("{f0}", "{ft0}", RISCV::F0_F) 4744 .Cases("{f1}", "{ft1}", RISCV::F1_F) 4745 .Cases("{f2}", "{ft2}", RISCV::F2_F) 4746 .Cases("{f3}", "{ft3}", RISCV::F3_F) 4747 .Cases("{f4}", "{ft4}", RISCV::F4_F) 4748 .Cases("{f5}", "{ft5}", RISCV::F5_F) 4749 .Cases("{f6}", "{ft6}", RISCV::F6_F) 4750 .Cases("{f7}", "{ft7}", RISCV::F7_F) 4751 .Cases("{f8}", "{fs0}", RISCV::F8_F) 4752 .Cases("{f9}", "{fs1}", RISCV::F9_F) 4753 .Cases("{f10}", "{fa0}", RISCV::F10_F) 4754 .Cases("{f11}", "{fa1}", RISCV::F11_F) 4755 .Cases("{f12}", "{fa2}", RISCV::F12_F) 4756 .Cases("{f13}", "{fa3}", RISCV::F13_F) 4757 .Cases("{f14}", "{fa4}", RISCV::F14_F) 4758 .Cases("{f15}", "{fa5}", RISCV::F15_F) 4759 .Cases("{f16}", "{fa6}", RISCV::F16_F) 4760 .Cases("{f17}", "{fa7}", RISCV::F17_F) 4761 .Cases("{f18}", "{fs2}", RISCV::F18_F) 4762 .Cases("{f19}", "{fs3}", RISCV::F19_F) 4763 .Cases("{f20}", "{fs4}", RISCV::F20_F) 4764 .Cases("{f21}", "{fs5}", RISCV::F21_F) 4765 .Cases("{f22}", "{fs6}", RISCV::F22_F) 4766 .Cases("{f23}", "{fs7}", RISCV::F23_F) 4767 .Cases("{f24}", "{fs8}", RISCV::F24_F) 4768 .Cases("{f25}", "{fs9}", RISCV::F25_F) 4769 .Cases("{f26}", "{fs10}", RISCV::F26_F) 4770 .Cases("{f27}", "{fs11}", RISCV::F27_F) 4771 .Cases("{f28}", "{ft8}", RISCV::F28_F) 4772 .Cases("{f29}", "{ft9}", RISCV::F29_F) 4773 .Cases("{f30}", "{ft10}", RISCV::F30_F) 4774 .Cases("{f31}", "{ft11}", RISCV::F31_F) 4775 .Default(RISCV::NoRegister); 4776 if (FReg != RISCV::NoRegister) { 4777 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 4778 if (Subtarget.hasStdExtD()) { 4779 unsigned RegNo = FReg - RISCV::F0_F; 4780 unsigned DReg = RISCV::F0_D + RegNo; 4781 return std::make_pair(DReg, &RISCV::FPR64RegClass); 4782 } 4783 return std::make_pair(FReg, &RISCV::FPR32RegClass); 4784 } 4785 } 4786 4787 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4788 } 4789 4790 unsigned 4791 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 4792 // Currently only support length 1 constraints. 4793 if (ConstraintCode.size() == 1) { 4794 switch (ConstraintCode[0]) { 4795 case 'A': 4796 return InlineAsm::Constraint_A; 4797 default: 4798 break; 4799 } 4800 } 4801 4802 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 4803 } 4804 4805 void RISCVTargetLowering::LowerAsmOperandForConstraint( 4806 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 4807 SelectionDAG &DAG) const { 4808 // Currently only support length 1 constraints. 4809 if (Constraint.length() == 1) { 4810 switch (Constraint[0]) { 4811 case 'I': 4812 // Validate & create a 12-bit signed immediate operand. 4813 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 4814 uint64_t CVal = C->getSExtValue(); 4815 if (isInt<12>(CVal)) 4816 Ops.push_back( 4817 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 4818 } 4819 return; 4820 case 'J': 4821 // Validate & create an integer zero operand. 4822 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 4823 if (C->getZExtValue() == 0) 4824 Ops.push_back( 4825 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 4826 return; 4827 case 'K': 4828 // Validate & create a 5-bit unsigned immediate operand. 4829 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 4830 uint64_t CVal = C->getZExtValue(); 4831 if (isUInt<5>(CVal)) 4832 Ops.push_back( 4833 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 4834 } 4835 return; 4836 default: 4837 break; 4838 } 4839 } 4840 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 4841 } 4842 4843 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 4844 Instruction *Inst, 4845 AtomicOrdering Ord) const { 4846 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 4847 return Builder.CreateFence(Ord); 4848 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 4849 return Builder.CreateFence(AtomicOrdering::Release); 4850 return nullptr; 4851 } 4852 4853 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 4854 Instruction *Inst, 4855 AtomicOrdering Ord) const { 4856 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 4857 return Builder.CreateFence(AtomicOrdering::Acquire); 4858 return nullptr; 4859 } 4860 4861 TargetLowering::AtomicExpansionKind 4862 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 4863 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 4864 // point operations can't be used in an lr/sc sequence without breaking the 4865 // forward-progress guarantee. 4866 if (AI->isFloatingPointOperation()) 4867 return AtomicExpansionKind::CmpXChg; 4868 4869 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 4870 if (Size == 8 || Size == 16) 4871 return AtomicExpansionKind::MaskedIntrinsic; 4872 return AtomicExpansionKind::None; 4873 } 4874 4875 static Intrinsic::ID 4876 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 4877 if (XLen == 32) { 4878 switch (BinOp) { 4879 default: 4880 llvm_unreachable("Unexpected AtomicRMW BinOp"); 4881 case AtomicRMWInst::Xchg: 4882 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 4883 case AtomicRMWInst::Add: 4884 return Intrinsic::riscv_masked_atomicrmw_add_i32; 4885 case AtomicRMWInst::Sub: 4886 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 4887 case AtomicRMWInst::Nand: 4888 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 4889 case AtomicRMWInst::Max: 4890 return Intrinsic::riscv_masked_atomicrmw_max_i32; 4891 case AtomicRMWInst::Min: 4892 return Intrinsic::riscv_masked_atomicrmw_min_i32; 4893 case AtomicRMWInst::UMax: 4894 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 4895 case AtomicRMWInst::UMin: 4896 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 4897 } 4898 } 4899 4900 if (XLen == 64) { 4901 switch (BinOp) { 4902 default: 4903 llvm_unreachable("Unexpected AtomicRMW BinOp"); 4904 case AtomicRMWInst::Xchg: 4905 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 4906 case AtomicRMWInst::Add: 4907 return Intrinsic::riscv_masked_atomicrmw_add_i64; 4908 case AtomicRMWInst::Sub: 4909 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 4910 case AtomicRMWInst::Nand: 4911 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 4912 case AtomicRMWInst::Max: 4913 return Intrinsic::riscv_masked_atomicrmw_max_i64; 4914 case AtomicRMWInst::Min: 4915 return Intrinsic::riscv_masked_atomicrmw_min_i64; 4916 case AtomicRMWInst::UMax: 4917 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 4918 case AtomicRMWInst::UMin: 4919 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 4920 } 4921 } 4922 4923 llvm_unreachable("Unexpected XLen\n"); 4924 } 4925 4926 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 4927 IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 4928 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 4929 unsigned XLen = Subtarget.getXLen(); 4930 Value *Ordering = 4931 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 4932 Type *Tys[] = {AlignedAddr->getType()}; 4933 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 4934 AI->getModule(), 4935 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 4936 4937 if (XLen == 64) { 4938 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 4939 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 4940 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 4941 } 4942 4943 Value *Result; 4944 4945 // Must pass the shift amount needed to sign extend the loaded value prior 4946 // to performing a signed comparison for min/max. ShiftAmt is the number of 4947 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 4948 // is the number of bits to left+right shift the value in order to 4949 // sign-extend. 4950 if (AI->getOperation() == AtomicRMWInst::Min || 4951 AI->getOperation() == AtomicRMWInst::Max) { 4952 const DataLayout &DL = AI->getModule()->getDataLayout(); 4953 unsigned ValWidth = 4954 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 4955 Value *SextShamt = 4956 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 4957 Result = Builder.CreateCall(LrwOpScwLoop, 4958 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 4959 } else { 4960 Result = 4961 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 4962 } 4963 4964 if (XLen == 64) 4965 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 4966 return Result; 4967 } 4968 4969 TargetLowering::AtomicExpansionKind 4970 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 4971 AtomicCmpXchgInst *CI) const { 4972 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 4973 if (Size == 8 || Size == 16) 4974 return AtomicExpansionKind::MaskedIntrinsic; 4975 return AtomicExpansionKind::None; 4976 } 4977 4978 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 4979 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 4980 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 4981 unsigned XLen = Subtarget.getXLen(); 4982 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 4983 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 4984 if (XLen == 64) { 4985 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 4986 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 4987 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 4988 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 4989 } 4990 Type *Tys[] = {AlignedAddr->getType()}; 4991 Function *MaskedCmpXchg = 4992 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 4993 Value *Result = Builder.CreateCall( 4994 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 4995 if (XLen == 64) 4996 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 4997 return Result; 4998 } 4999 5000 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 5001 EVT VT) const { 5002 VT = VT.getScalarType(); 5003 5004 if (!VT.isSimple()) 5005 return false; 5006 5007 switch (VT.getSimpleVT().SimpleTy) { 5008 case MVT::f16: 5009 return Subtarget.hasStdExtZfh(); 5010 case MVT::f32: 5011 return Subtarget.hasStdExtF(); 5012 case MVT::f64: 5013 return Subtarget.hasStdExtD(); 5014 default: 5015 break; 5016 } 5017 5018 return false; 5019 } 5020 5021 Register RISCVTargetLowering::getExceptionPointerRegister( 5022 const Constant *PersonalityFn) const { 5023 return RISCV::X10; 5024 } 5025 5026 Register RISCVTargetLowering::getExceptionSelectorRegister( 5027 const Constant *PersonalityFn) const { 5028 return RISCV::X11; 5029 } 5030 5031 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 5032 // Return false to suppress the unnecessary extensions if the LibCall 5033 // arguments or return value is f32 type for LP64 ABI. 5034 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 5035 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 5036 return false; 5037 5038 return true; 5039 } 5040 5041 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 5042 if (Subtarget.is64Bit() && Type == MVT::i32) 5043 return true; 5044 5045 return IsSigned; 5046 } 5047 5048 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 5049 SDValue C) const { 5050 // Check integral scalar types. 5051 if (VT.isScalarInteger()) { 5052 // Omit the optimization if the sub target has the M extension and the data 5053 // size exceeds XLen. 5054 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 5055 return false; 5056 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 5057 // Break the MUL to a SLLI and an ADD/SUB. 5058 const APInt &Imm = ConstNode->getAPIntValue(); 5059 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 5060 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 5061 return true; 5062 // Omit the following optimization if the sub target has the M extension 5063 // and the data size >= XLen. 5064 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 5065 return false; 5066 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 5067 // a pair of LUI/ADDI. 5068 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 5069 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 5070 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 5071 (1 - ImmS).isPowerOf2()) 5072 return true; 5073 } 5074 } 5075 } 5076 5077 return false; 5078 } 5079 5080 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 5081 if (!Subtarget.useRVVForFixedLengthVectors()) 5082 return false; 5083 5084 if (!VT.isFixedLengthVector()) 5085 return false; 5086 5087 // Don't use RVV for vectors we cannot scalarize if required. 5088 switch (VT.getVectorElementType().SimpleTy) { 5089 default: 5090 return false; 5091 case MVT::i1: 5092 case MVT::i8: 5093 case MVT::i16: 5094 case MVT::i32: 5095 case MVT::i64: 5096 break; 5097 case MVT::f16: 5098 if (!Subtarget.hasStdExtZfh()) 5099 return false; 5100 break; 5101 case MVT::f32: 5102 if (!Subtarget.hasStdExtF()) 5103 return false; 5104 break; 5105 case MVT::f64: 5106 if (!Subtarget.hasStdExtD()) 5107 return false; 5108 break; 5109 } 5110 5111 unsigned LMul = Subtarget.getLMULForFixedLengthVector(VT); 5112 // Don't use RVV for types that don't fit. 5113 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 5114 return false; 5115 5116 // TODO: Perhaps an artificial restriction, but worth having whilst getting 5117 // the base fixed length RVV support in place. 5118 if (!VT.isPow2VectorType()) 5119 return false; 5120 5121 return true; 5122 } 5123 5124 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 5125 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 5126 bool *Fast) const { 5127 if (!VT.isScalableVector()) 5128 return false; 5129 5130 EVT ElemVT = VT.getVectorElementType(); 5131 if (Alignment >= ElemVT.getStoreSize()) { 5132 if (Fast) 5133 *Fast = true; 5134 return true; 5135 } 5136 5137 return false; 5138 } 5139 5140 #define GET_REGISTER_MATCHER 5141 #include "RISCVGenAsmMatcher.inc" 5142 5143 Register 5144 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 5145 const MachineFunction &MF) const { 5146 Register Reg = MatchRegisterAltName(RegName); 5147 if (Reg == RISCV::NoRegister) 5148 Reg = MatchRegisterName(RegName); 5149 if (Reg == RISCV::NoRegister) 5150 report_fatal_error( 5151 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 5152 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 5153 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 5154 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 5155 StringRef(RegName) + "\".")); 5156 return Reg; 5157 } 5158 5159 namespace llvm { 5160 namespace RISCVVIntrinsicsTable { 5161 5162 #define GET_RISCVVIntrinsicsTable_IMPL 5163 #include "RISCVGenSearchableTables.inc" 5164 5165 } // namespace RISCVVIntrinsicsTable 5166 5167 namespace RISCVZvlssegTable { 5168 5169 #define GET_RISCVZvlssegTable_IMPL 5170 #include "RISCVGenSearchableTables.inc" 5171 5172 } // namespace RISCVZvlssegTable 5173 } // namespace llvm 5174