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 "RISCV.h" 16 #include "RISCVMachineFunctionInfo.h" 17 #include "RISCVRegisterInfo.h" 18 #include "RISCVSubtarget.h" 19 #include "RISCVTargetMachine.h" 20 #include "Utils/RISCVMatInt.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/MathExtras.h" 36 #include "llvm/Support/raw_ostream.h" 37 38 using namespace llvm; 39 40 #define DEBUG_TYPE "riscv-lower" 41 42 STATISTIC(NumTailCalls, "Number of tail calls"); 43 44 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 45 const RISCVSubtarget &STI) 46 : TargetLowering(TM), Subtarget(STI) { 47 48 if (Subtarget.isRV32E()) 49 report_fatal_error("Codegen not yet implemented for RV32E"); 50 51 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 52 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 53 54 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 55 !Subtarget.hasStdExtF()) { 56 errs() << "Hard-float 'f' ABI can't be used for a target that " 57 "doesn't support the F instruction set extension (ignoring " 58 "target-abi)\n"; 59 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 60 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 61 !Subtarget.hasStdExtD()) { 62 errs() << "Hard-float 'd' ABI can't be used for a target that " 63 "doesn't support the D instruction set extension (ignoring " 64 "target-abi)\n"; 65 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 66 } 67 68 switch (ABI) { 69 default: 70 report_fatal_error("Don't know how to lower this ABI"); 71 case RISCVABI::ABI_ILP32: 72 case RISCVABI::ABI_ILP32F: 73 case RISCVABI::ABI_ILP32D: 74 case RISCVABI::ABI_LP64: 75 case RISCVABI::ABI_LP64F: 76 case RISCVABI::ABI_LP64D: 77 break; 78 } 79 80 MVT XLenVT = Subtarget.getXLenVT(); 81 82 // Set up the register classes. 83 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 84 85 if (Subtarget.hasStdExtZfh()) 86 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 87 if (Subtarget.hasStdExtF()) 88 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 89 if (Subtarget.hasStdExtD()) 90 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 91 92 if (Subtarget.hasStdExtV()) { 93 addRegisterClass(RISCVVMVTs::vbool64_t, &RISCV::VRRegClass); 94 addRegisterClass(RISCVVMVTs::vbool32_t, &RISCV::VRRegClass); 95 addRegisterClass(RISCVVMVTs::vbool16_t, &RISCV::VRRegClass); 96 addRegisterClass(RISCVVMVTs::vbool8_t, &RISCV::VRRegClass); 97 addRegisterClass(RISCVVMVTs::vbool4_t, &RISCV::VRRegClass); 98 addRegisterClass(RISCVVMVTs::vbool2_t, &RISCV::VRRegClass); 99 addRegisterClass(RISCVVMVTs::vbool1_t, &RISCV::VRRegClass); 100 101 addRegisterClass(RISCVVMVTs::vint8mf8_t, &RISCV::VRRegClass); 102 addRegisterClass(RISCVVMVTs::vint8mf4_t, &RISCV::VRRegClass); 103 addRegisterClass(RISCVVMVTs::vint8mf2_t, &RISCV::VRRegClass); 104 addRegisterClass(RISCVVMVTs::vint8m1_t, &RISCV::VRRegClass); 105 addRegisterClass(RISCVVMVTs::vint8m2_t, &RISCV::VRM2RegClass); 106 addRegisterClass(RISCVVMVTs::vint8m4_t, &RISCV::VRM4RegClass); 107 addRegisterClass(RISCVVMVTs::vint8m8_t, &RISCV::VRM8RegClass); 108 109 addRegisterClass(RISCVVMVTs::vint16mf4_t, &RISCV::VRRegClass); 110 addRegisterClass(RISCVVMVTs::vint16mf2_t, &RISCV::VRRegClass); 111 addRegisterClass(RISCVVMVTs::vint16m1_t, &RISCV::VRRegClass); 112 addRegisterClass(RISCVVMVTs::vint16m2_t, &RISCV::VRM2RegClass); 113 addRegisterClass(RISCVVMVTs::vint16m4_t, &RISCV::VRM4RegClass); 114 addRegisterClass(RISCVVMVTs::vint16m8_t, &RISCV::VRM8RegClass); 115 116 addRegisterClass(RISCVVMVTs::vint32mf2_t, &RISCV::VRRegClass); 117 addRegisterClass(RISCVVMVTs::vint32m1_t, &RISCV::VRRegClass); 118 addRegisterClass(RISCVVMVTs::vint32m2_t, &RISCV::VRM2RegClass); 119 addRegisterClass(RISCVVMVTs::vint32m4_t, &RISCV::VRM4RegClass); 120 addRegisterClass(RISCVVMVTs::vint32m8_t, &RISCV::VRM8RegClass); 121 122 addRegisterClass(RISCVVMVTs::vint64m1_t, &RISCV::VRRegClass); 123 addRegisterClass(RISCVVMVTs::vint64m2_t, &RISCV::VRM2RegClass); 124 addRegisterClass(RISCVVMVTs::vint64m4_t, &RISCV::VRM4RegClass); 125 addRegisterClass(RISCVVMVTs::vint64m8_t, &RISCV::VRM8RegClass); 126 127 if (Subtarget.hasStdExtZfh()) { 128 addRegisterClass(RISCVVMVTs::vfloat16mf4_t, &RISCV::VRRegClass); 129 addRegisterClass(RISCVVMVTs::vfloat16mf2_t, &RISCV::VRRegClass); 130 addRegisterClass(RISCVVMVTs::vfloat16m1_t, &RISCV::VRRegClass); 131 addRegisterClass(RISCVVMVTs::vfloat16m2_t, &RISCV::VRM2RegClass); 132 addRegisterClass(RISCVVMVTs::vfloat16m4_t, &RISCV::VRM4RegClass); 133 addRegisterClass(RISCVVMVTs::vfloat16m8_t, &RISCV::VRM8RegClass); 134 } 135 136 if (Subtarget.hasStdExtF()) { 137 addRegisterClass(RISCVVMVTs::vfloat32mf2_t, &RISCV::VRRegClass); 138 addRegisterClass(RISCVVMVTs::vfloat32m1_t, &RISCV::VRRegClass); 139 addRegisterClass(RISCVVMVTs::vfloat32m2_t, &RISCV::VRM2RegClass); 140 addRegisterClass(RISCVVMVTs::vfloat32m4_t, &RISCV::VRM4RegClass); 141 addRegisterClass(RISCVVMVTs::vfloat32m8_t, &RISCV::VRM8RegClass); 142 } 143 144 if (Subtarget.hasStdExtD()) { 145 addRegisterClass(RISCVVMVTs::vfloat64m1_t, &RISCV::VRRegClass); 146 addRegisterClass(RISCVVMVTs::vfloat64m2_t, &RISCV::VRM2RegClass); 147 addRegisterClass(RISCVVMVTs::vfloat64m4_t, &RISCV::VRM4RegClass); 148 addRegisterClass(RISCVVMVTs::vfloat64m8_t, &RISCV::VRM8RegClass); 149 } 150 } 151 152 // Compute derived properties from the register classes. 153 computeRegisterProperties(STI.getRegisterInfo()); 154 155 setStackPointerRegisterToSaveRestore(RISCV::X2); 156 157 for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) 158 setLoadExtAction(N, XLenVT, MVT::i1, Promote); 159 160 // TODO: add all necessary setOperationAction calls. 161 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 162 163 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 164 setOperationAction(ISD::BR_CC, XLenVT, Expand); 165 setOperationAction(ISD::SELECT, XLenVT, Custom); 166 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 167 168 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 169 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 170 171 setOperationAction(ISD::VASTART, MVT::Other, Custom); 172 setOperationAction(ISD::VAARG, MVT::Other, Expand); 173 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 174 setOperationAction(ISD::VAEND, MVT::Other, Expand); 175 176 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 177 if (!Subtarget.hasStdExtZbb()) { 178 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 179 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 180 } 181 182 if (Subtarget.is64Bit()) { 183 setOperationAction(ISD::ADD, MVT::i32, Custom); 184 setOperationAction(ISD::SUB, MVT::i32, Custom); 185 setOperationAction(ISD::SHL, MVT::i32, Custom); 186 setOperationAction(ISD::SRA, MVT::i32, Custom); 187 setOperationAction(ISD::SRL, MVT::i32, Custom); 188 } 189 190 if (!Subtarget.hasStdExtM()) { 191 setOperationAction(ISD::MUL, XLenVT, Expand); 192 setOperationAction(ISD::MULHS, XLenVT, Expand); 193 setOperationAction(ISD::MULHU, XLenVT, Expand); 194 setOperationAction(ISD::SDIV, XLenVT, Expand); 195 setOperationAction(ISD::UDIV, XLenVT, Expand); 196 setOperationAction(ISD::SREM, XLenVT, Expand); 197 setOperationAction(ISD::UREM, XLenVT, Expand); 198 } 199 200 if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) { 201 setOperationAction(ISD::MUL, MVT::i32, Custom); 202 setOperationAction(ISD::SDIV, MVT::i32, Custom); 203 setOperationAction(ISD::UDIV, MVT::i32, Custom); 204 setOperationAction(ISD::UREM, MVT::i32, Custom); 205 } 206 207 setOperationAction(ISD::SDIVREM, XLenVT, Expand); 208 setOperationAction(ISD::UDIVREM, XLenVT, Expand); 209 setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand); 210 setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand); 211 212 setOperationAction(ISD::SHL_PARTS, XLenVT, Custom); 213 setOperationAction(ISD::SRL_PARTS, XLenVT, Custom); 214 setOperationAction(ISD::SRA_PARTS, XLenVT, Custom); 215 216 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 217 if (Subtarget.is64Bit()) { 218 setOperationAction(ISD::ROTL, MVT::i32, Custom); 219 setOperationAction(ISD::ROTR, MVT::i32, Custom); 220 } 221 } else { 222 setOperationAction(ISD::ROTL, XLenVT, Expand); 223 setOperationAction(ISD::ROTR, XLenVT, Expand); 224 } 225 226 if (Subtarget.hasStdExtZbp()) { 227 setOperationAction(ISD::BITREVERSE, XLenVT, Custom); 228 setOperationAction(ISD::BSWAP, XLenVT, Custom); 229 230 if (Subtarget.is64Bit()) { 231 setOperationAction(ISD::BITREVERSE, MVT::i32, Custom); 232 setOperationAction(ISD::BSWAP, MVT::i32, Custom); 233 } 234 } else { 235 setOperationAction(ISD::BSWAP, XLenVT, Expand); 236 } 237 238 if (Subtarget.hasStdExtZbb()) { 239 setOperationAction(ISD::SMIN, XLenVT, Legal); 240 setOperationAction(ISD::SMAX, XLenVT, Legal); 241 setOperationAction(ISD::UMIN, XLenVT, Legal); 242 setOperationAction(ISD::UMAX, XLenVT, Legal); 243 } else { 244 setOperationAction(ISD::CTTZ, XLenVT, Expand); 245 setOperationAction(ISD::CTLZ, XLenVT, Expand); 246 setOperationAction(ISD::CTPOP, XLenVT, Expand); 247 } 248 249 if (Subtarget.hasStdExtZbt()) { 250 setOperationAction(ISD::FSHL, XLenVT, Legal); 251 setOperationAction(ISD::FSHR, XLenVT, Legal); 252 253 if (Subtarget.is64Bit()) { 254 setOperationAction(ISD::FSHL, MVT::i32, Custom); 255 setOperationAction(ISD::FSHR, MVT::i32, Custom); 256 } 257 } 258 259 ISD::CondCode FPCCToExpand[] = { 260 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 261 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 262 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 263 264 ISD::NodeType FPOpToExpand[] = { 265 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP, 266 ISD::FP_TO_FP16}; 267 268 if (Subtarget.hasStdExtZfh()) 269 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 270 271 if (Subtarget.hasStdExtZfh()) { 272 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 273 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 274 for (auto CC : FPCCToExpand) 275 setCondCodeAction(CC, MVT::f16, Expand); 276 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 277 setOperationAction(ISD::SELECT, MVT::f16, Custom); 278 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 279 for (auto Op : FPOpToExpand) 280 setOperationAction(Op, MVT::f16, Expand); 281 } 282 283 if (Subtarget.hasStdExtF()) { 284 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 285 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 286 for (auto CC : FPCCToExpand) 287 setCondCodeAction(CC, MVT::f32, Expand); 288 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 289 setOperationAction(ISD::SELECT, MVT::f32, Custom); 290 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 291 for (auto Op : FPOpToExpand) 292 setOperationAction(Op, MVT::f32, Expand); 293 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 294 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 295 } 296 297 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 298 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 299 300 if (Subtarget.hasStdExtD()) { 301 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 302 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 303 for (auto CC : FPCCToExpand) 304 setCondCodeAction(CC, MVT::f64, Expand); 305 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 306 setOperationAction(ISD::SELECT, MVT::f64, Custom); 307 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 308 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 309 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 310 for (auto Op : FPOpToExpand) 311 setOperationAction(Op, MVT::f64, Expand); 312 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 313 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 314 } 315 316 if (Subtarget.is64Bit()) { 317 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 318 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 319 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 320 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 321 } 322 323 setOperationAction(ISD::GlobalAddress, XLenVT, Custom); 324 setOperationAction(ISD::BlockAddress, XLenVT, Custom); 325 setOperationAction(ISD::ConstantPool, XLenVT, Custom); 326 setOperationAction(ISD::JumpTable, XLenVT, Custom); 327 328 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 329 330 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 331 // Unfortunately this can't be determined just from the ISA naming string. 332 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 333 Subtarget.is64Bit() ? Legal : Custom); 334 335 setOperationAction(ISD::TRAP, MVT::Other, Legal); 336 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 337 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 338 339 if (Subtarget.hasStdExtA()) { 340 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 341 setMinCmpXchgSizeInBits(32); 342 } else { 343 setMaxAtomicSizeInBitsSupported(0); 344 } 345 346 setBooleanContents(ZeroOrOneBooleanContent); 347 348 if (Subtarget.hasStdExtV()) { 349 setBooleanVectorContents(ZeroOrOneBooleanContent); 350 351 // RVV intrinsics may have illegal operands. 352 // We also need to custom legalize vmv.x.s. 353 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 354 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 355 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 356 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 357 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 358 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 359 360 if (Subtarget.is64Bit()) { 361 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 362 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom); 363 } 364 365 for (auto VT : MVT::integer_scalable_vector_valuetypes()) 366 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 367 368 // We must custom-lower SPLAT_VECTOR vXi64 on RV32 369 if (!Subtarget.is64Bit()) 370 setOperationAction(ISD::SPLAT_VECTOR, MVT::i64, Custom); 371 } 372 373 // Function alignments. 374 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 375 setMinFunctionAlignment(FunctionAlignment); 376 setPrefFunctionAlignment(FunctionAlignment); 377 378 setMinimumJumpTableEntries(5); 379 380 // Jumps are expensive, compared to logic 381 setJumpIsExpensive(); 382 383 // We can use any register for comparisons 384 setHasMultipleConditionRegisters(); 385 386 if (Subtarget.hasStdExtZbp()) { 387 setTargetDAGCombine(ISD::OR); 388 } 389 } 390 391 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 392 EVT VT) const { 393 if (!VT.isVector()) 394 return getPointerTy(DL); 395 return VT.changeVectorElementTypeToInteger(); 396 } 397 398 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 399 const CallInst &I, 400 MachineFunction &MF, 401 unsigned Intrinsic) const { 402 switch (Intrinsic) { 403 default: 404 return false; 405 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 406 case Intrinsic::riscv_masked_atomicrmw_add_i32: 407 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 408 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 409 case Intrinsic::riscv_masked_atomicrmw_max_i32: 410 case Intrinsic::riscv_masked_atomicrmw_min_i32: 411 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 412 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 413 case Intrinsic::riscv_masked_cmpxchg_i32: 414 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 415 Info.opc = ISD::INTRINSIC_W_CHAIN; 416 Info.memVT = MVT::getVT(PtrTy->getElementType()); 417 Info.ptrVal = I.getArgOperand(0); 418 Info.offset = 0; 419 Info.align = Align(4); 420 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 421 MachineMemOperand::MOVolatile; 422 return true; 423 } 424 } 425 426 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 427 const AddrMode &AM, Type *Ty, 428 unsigned AS, 429 Instruction *I) const { 430 // No global is ever allowed as a base. 431 if (AM.BaseGV) 432 return false; 433 434 // Require a 12-bit signed offset. 435 if (!isInt<12>(AM.BaseOffs)) 436 return false; 437 438 switch (AM.Scale) { 439 case 0: // "r+i" or just "i", depending on HasBaseReg. 440 break; 441 case 1: 442 if (!AM.HasBaseReg) // allow "r+i". 443 break; 444 return false; // disallow "r+r" or "r+r+i". 445 default: 446 return false; 447 } 448 449 return true; 450 } 451 452 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 453 return isInt<12>(Imm); 454 } 455 456 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 457 return isInt<12>(Imm); 458 } 459 460 // On RV32, 64-bit integers are split into their high and low parts and held 461 // in two different registers, so the trunc is free since the low register can 462 // just be used. 463 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 464 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 465 return false; 466 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 467 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 468 return (SrcBits == 64 && DestBits == 32); 469 } 470 471 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 472 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 473 !SrcVT.isInteger() || !DstVT.isInteger()) 474 return false; 475 unsigned SrcBits = SrcVT.getSizeInBits(); 476 unsigned DestBits = DstVT.getSizeInBits(); 477 return (SrcBits == 64 && DestBits == 32); 478 } 479 480 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 481 // Zexts are free if they can be combined with a load. 482 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 483 EVT MemVT = LD->getMemoryVT(); 484 if ((MemVT == MVT::i8 || MemVT == MVT::i16 || 485 (Subtarget.is64Bit() && MemVT == MVT::i32)) && 486 (LD->getExtensionType() == ISD::NON_EXTLOAD || 487 LD->getExtensionType() == ISD::ZEXTLOAD)) 488 return true; 489 } 490 491 return TargetLowering::isZExtFree(Val, VT2); 492 } 493 494 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 495 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 496 } 497 498 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 499 return Subtarget.hasStdExtZbb(); 500 } 501 502 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 503 return Subtarget.hasStdExtZbb(); 504 } 505 506 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 507 bool ForCodeSize) const { 508 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 509 return false; 510 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 511 return false; 512 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 513 return false; 514 if (Imm.isNegZero()) 515 return false; 516 return Imm.isZero(); 517 } 518 519 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 520 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 521 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 522 (VT == MVT::f64 && Subtarget.hasStdExtD()); 523 } 524 525 // Changes the condition code and swaps operands if necessary, so the SetCC 526 // operation matches one of the comparisons supported directly in the RISC-V 527 // ISA. 528 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) { 529 switch (CC) { 530 default: 531 break; 532 case ISD::SETGT: 533 case ISD::SETLE: 534 case ISD::SETUGT: 535 case ISD::SETULE: 536 CC = ISD::getSetCCSwappedOperands(CC); 537 std::swap(LHS, RHS); 538 break; 539 } 540 } 541 542 // Return the RISC-V branch opcode that matches the given DAG integer 543 // condition code. The CondCode must be one of those supported by the RISC-V 544 // ISA (see normaliseSetCC). 545 static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC) { 546 switch (CC) { 547 default: 548 llvm_unreachable("Unsupported CondCode"); 549 case ISD::SETEQ: 550 return RISCV::BEQ; 551 case ISD::SETNE: 552 return RISCV::BNE; 553 case ISD::SETLT: 554 return RISCV::BLT; 555 case ISD::SETGE: 556 return RISCV::BGE; 557 case ISD::SETULT: 558 return RISCV::BLTU; 559 case ISD::SETUGE: 560 return RISCV::BGEU; 561 } 562 } 563 564 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 565 SelectionDAG &DAG) const { 566 switch (Op.getOpcode()) { 567 default: 568 report_fatal_error("unimplemented operand"); 569 case ISD::GlobalAddress: 570 return lowerGlobalAddress(Op, DAG); 571 case ISD::BlockAddress: 572 return lowerBlockAddress(Op, DAG); 573 case ISD::ConstantPool: 574 return lowerConstantPool(Op, DAG); 575 case ISD::JumpTable: 576 return lowerJumpTable(Op, DAG); 577 case ISD::GlobalTLSAddress: 578 return lowerGlobalTLSAddress(Op, DAG); 579 case ISD::SELECT: 580 return lowerSELECT(Op, DAG); 581 case ISD::VASTART: 582 return lowerVASTART(Op, DAG); 583 case ISD::FRAMEADDR: 584 return lowerFRAMEADDR(Op, DAG); 585 case ISD::RETURNADDR: 586 return lowerRETURNADDR(Op, DAG); 587 case ISD::SHL_PARTS: 588 return lowerShiftLeftParts(Op, DAG); 589 case ISD::SRA_PARTS: 590 return lowerShiftRightParts(Op, DAG, true); 591 case ISD::SRL_PARTS: 592 return lowerShiftRightParts(Op, DAG, false); 593 case ISD::BITCAST: { 594 assert(((Subtarget.is64Bit() && Subtarget.hasStdExtF()) || 595 Subtarget.hasStdExtZfh()) && 596 "Unexpected custom legalisation"); 597 SDLoc DL(Op); 598 SDValue Op0 = Op.getOperand(0); 599 if (Op.getValueType() == MVT::f16 && Subtarget.hasStdExtZfh()) { 600 if (Op0.getValueType() != MVT::i16) 601 return SDValue(); 602 SDValue NewOp0 = 603 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getXLenVT(), Op0); 604 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 605 return FPConv; 606 } else if (Op.getValueType() == MVT::f32 && Subtarget.is64Bit() && 607 Subtarget.hasStdExtF()) { 608 if (Op0.getValueType() != MVT::i32) 609 return SDValue(); 610 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 611 SDValue FPConv = 612 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 613 return FPConv; 614 } 615 return SDValue(); 616 } 617 case ISD::INTRINSIC_WO_CHAIN: 618 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 619 case ISD::INTRINSIC_W_CHAIN: 620 return LowerINTRINSIC_W_CHAIN(Op, DAG); 621 case ISD::BSWAP: 622 case ISD::BITREVERSE: { 623 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 624 assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 625 MVT VT = Op.getSimpleValueType(); 626 SDLoc DL(Op); 627 // Start with the maximum immediate value which is the bitwidth - 1. 628 unsigned Imm = VT.getSizeInBits() - 1; 629 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 630 if (Op.getOpcode() == ISD::BSWAP) 631 Imm &= ~0x7U; 632 return DAG.getNode(RISCVISD::GREVI, DL, VT, Op.getOperand(0), 633 DAG.getTargetConstant(Imm, DL, Subtarget.getXLenVT())); 634 } 635 case ISD::SPLAT_VECTOR: 636 return lowerSPLATVECTOR(Op, DAG); 637 } 638 } 639 640 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 641 SelectionDAG &DAG, unsigned Flags) { 642 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 643 } 644 645 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 646 SelectionDAG &DAG, unsigned Flags) { 647 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 648 Flags); 649 } 650 651 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 652 SelectionDAG &DAG, unsigned Flags) { 653 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 654 N->getOffset(), Flags); 655 } 656 657 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 658 SelectionDAG &DAG, unsigned Flags) { 659 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 660 } 661 662 template <class NodeTy> 663 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 664 bool IsLocal) const { 665 SDLoc DL(N); 666 EVT Ty = getPointerTy(DAG.getDataLayout()); 667 668 if (isPositionIndependent()) { 669 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 670 if (IsLocal) 671 // Use PC-relative addressing to access the symbol. This generates the 672 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 673 // %pcrel_lo(auipc)). 674 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 675 676 // Use PC-relative addressing to access the GOT for this symbol, then load 677 // the address from the GOT. This generates the pattern (PseudoLA sym), 678 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 679 return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 680 } 681 682 switch (getTargetMachine().getCodeModel()) { 683 default: 684 report_fatal_error("Unsupported code model for lowering"); 685 case CodeModel::Small: { 686 // Generate a sequence for accessing addresses within the first 2 GiB of 687 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 688 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 689 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 690 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 691 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 692 } 693 case CodeModel::Medium: { 694 // Generate a sequence for accessing addresses within any 2GiB range within 695 // the address space. This generates the pattern (PseudoLLA sym), which 696 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 697 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 698 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 699 } 700 } 701 } 702 703 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 704 SelectionDAG &DAG) const { 705 SDLoc DL(Op); 706 EVT Ty = Op.getValueType(); 707 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 708 int64_t Offset = N->getOffset(); 709 MVT XLenVT = Subtarget.getXLenVT(); 710 711 const GlobalValue *GV = N->getGlobal(); 712 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 713 SDValue Addr = getAddr(N, DAG, IsLocal); 714 715 // In order to maximise the opportunity for common subexpression elimination, 716 // emit a separate ADD node for the global address offset instead of folding 717 // it in the global address node. Later peephole optimisations may choose to 718 // fold it back in when profitable. 719 if (Offset != 0) 720 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 721 DAG.getConstant(Offset, DL, XLenVT)); 722 return Addr; 723 } 724 725 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 726 SelectionDAG &DAG) const { 727 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 728 729 return getAddr(N, DAG); 730 } 731 732 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 733 SelectionDAG &DAG) const { 734 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 735 736 return getAddr(N, DAG); 737 } 738 739 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 740 SelectionDAG &DAG) const { 741 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 742 743 return getAddr(N, DAG); 744 } 745 746 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 747 SelectionDAG &DAG, 748 bool UseGOT) const { 749 SDLoc DL(N); 750 EVT Ty = getPointerTy(DAG.getDataLayout()); 751 const GlobalValue *GV = N->getGlobal(); 752 MVT XLenVT = Subtarget.getXLenVT(); 753 754 if (UseGOT) { 755 // Use PC-relative addressing to access the GOT for this TLS symbol, then 756 // load the address from the GOT and add the thread pointer. This generates 757 // the pattern (PseudoLA_TLS_IE sym), which expands to 758 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 759 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 760 SDValue Load = 761 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 762 763 // Add the thread pointer. 764 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 765 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 766 } 767 768 // Generate a sequence for accessing the address relative to the thread 769 // pointer, with the appropriate adjustment for the thread pointer offset. 770 // This generates the pattern 771 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 772 SDValue AddrHi = 773 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 774 SDValue AddrAdd = 775 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 776 SDValue AddrLo = 777 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 778 779 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 780 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 781 SDValue MNAdd = SDValue( 782 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 783 0); 784 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 785 } 786 787 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 788 SelectionDAG &DAG) const { 789 SDLoc DL(N); 790 EVT Ty = getPointerTy(DAG.getDataLayout()); 791 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 792 const GlobalValue *GV = N->getGlobal(); 793 794 // Use a PC-relative addressing mode to access the global dynamic GOT address. 795 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 796 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 797 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 798 SDValue Load = 799 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 800 801 // Prepare argument list to generate call. 802 ArgListTy Args; 803 ArgListEntry Entry; 804 Entry.Node = Load; 805 Entry.Ty = CallTy; 806 Args.push_back(Entry); 807 808 // Setup call to __tls_get_addr. 809 TargetLowering::CallLoweringInfo CLI(DAG); 810 CLI.setDebugLoc(DL) 811 .setChain(DAG.getEntryNode()) 812 .setLibCallee(CallingConv::C, CallTy, 813 DAG.getExternalSymbol("__tls_get_addr", Ty), 814 std::move(Args)); 815 816 return LowerCallTo(CLI).first; 817 } 818 819 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 820 SelectionDAG &DAG) const { 821 SDLoc DL(Op); 822 EVT Ty = Op.getValueType(); 823 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 824 int64_t Offset = N->getOffset(); 825 MVT XLenVT = Subtarget.getXLenVT(); 826 827 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 828 829 if (DAG.getMachineFunction().getFunction().getCallingConv() == 830 CallingConv::GHC) 831 report_fatal_error("In GHC calling convention TLS is not supported"); 832 833 SDValue Addr; 834 switch (Model) { 835 case TLSModel::LocalExec: 836 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 837 break; 838 case TLSModel::InitialExec: 839 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 840 break; 841 case TLSModel::LocalDynamic: 842 case TLSModel::GeneralDynamic: 843 Addr = getDynamicTLSAddr(N, DAG); 844 break; 845 } 846 847 // In order to maximise the opportunity for common subexpression elimination, 848 // emit a separate ADD node for the global address offset instead of folding 849 // it in the global address node. Later peephole optimisations may choose to 850 // fold it back in when profitable. 851 if (Offset != 0) 852 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 853 DAG.getConstant(Offset, DL, XLenVT)); 854 return Addr; 855 } 856 857 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 858 SDValue CondV = Op.getOperand(0); 859 SDValue TrueV = Op.getOperand(1); 860 SDValue FalseV = Op.getOperand(2); 861 SDLoc DL(Op); 862 MVT XLenVT = Subtarget.getXLenVT(); 863 864 // If the result type is XLenVT and CondV is the output of a SETCC node 865 // which also operated on XLenVT inputs, then merge the SETCC node into the 866 // lowered RISCVISD::SELECT_CC to take advantage of the integer 867 // compare+branch instructions. i.e.: 868 // (select (setcc lhs, rhs, cc), truev, falsev) 869 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 870 if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC && 871 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 872 SDValue LHS = CondV.getOperand(0); 873 SDValue RHS = CondV.getOperand(1); 874 auto CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 875 ISD::CondCode CCVal = CC->get(); 876 877 normaliseSetCC(LHS, RHS, CCVal); 878 879 SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT); 880 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 881 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 882 } 883 884 // Otherwise: 885 // (select condv, truev, falsev) 886 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 887 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 888 SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT); 889 890 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 891 892 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 893 } 894 895 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 896 MachineFunction &MF = DAG.getMachineFunction(); 897 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 898 899 SDLoc DL(Op); 900 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 901 getPointerTy(MF.getDataLayout())); 902 903 // vastart just stores the address of the VarArgsFrameIndex slot into the 904 // memory location argument. 905 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 906 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 907 MachinePointerInfo(SV)); 908 } 909 910 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 911 SelectionDAG &DAG) const { 912 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 913 MachineFunction &MF = DAG.getMachineFunction(); 914 MachineFrameInfo &MFI = MF.getFrameInfo(); 915 MFI.setFrameAddressIsTaken(true); 916 Register FrameReg = RI.getFrameRegister(MF); 917 int XLenInBytes = Subtarget.getXLen() / 8; 918 919 EVT VT = Op.getValueType(); 920 SDLoc DL(Op); 921 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 922 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 923 while (Depth--) { 924 int Offset = -(XLenInBytes * 2); 925 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 926 DAG.getIntPtrConstant(Offset, DL)); 927 FrameAddr = 928 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 929 } 930 return FrameAddr; 931 } 932 933 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 934 SelectionDAG &DAG) const { 935 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 936 MachineFunction &MF = DAG.getMachineFunction(); 937 MachineFrameInfo &MFI = MF.getFrameInfo(); 938 MFI.setReturnAddressIsTaken(true); 939 MVT XLenVT = Subtarget.getXLenVT(); 940 int XLenInBytes = Subtarget.getXLen() / 8; 941 942 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 943 return SDValue(); 944 945 EVT VT = Op.getValueType(); 946 SDLoc DL(Op); 947 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 948 if (Depth) { 949 int Off = -XLenInBytes; 950 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 951 SDValue Offset = DAG.getConstant(Off, DL, VT); 952 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 953 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 954 MachinePointerInfo()); 955 } 956 957 // Return the value of the return address register, marking it an implicit 958 // live-in. 959 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 960 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 961 } 962 963 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 964 SelectionDAG &DAG) const { 965 SDLoc DL(Op); 966 SDValue Lo = Op.getOperand(0); 967 SDValue Hi = Op.getOperand(1); 968 SDValue Shamt = Op.getOperand(2); 969 EVT VT = Lo.getValueType(); 970 971 // if Shamt-XLEN < 0: // Shamt < XLEN 972 // Lo = Lo << Shamt 973 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt)) 974 // else: 975 // Lo = 0 976 // Hi = Lo << (Shamt-XLEN) 977 978 SDValue Zero = DAG.getConstant(0, DL, VT); 979 SDValue One = DAG.getConstant(1, DL, VT); 980 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 981 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 982 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 983 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 984 985 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 986 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 987 SDValue ShiftRightLo = 988 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 989 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 990 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 991 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 992 993 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 994 995 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 996 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 997 998 SDValue Parts[2] = {Lo, Hi}; 999 return DAG.getMergeValues(Parts, DL); 1000 } 1001 1002 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 1003 bool IsSRA) const { 1004 SDLoc DL(Op); 1005 SDValue Lo = Op.getOperand(0); 1006 SDValue Hi = Op.getOperand(1); 1007 SDValue Shamt = Op.getOperand(2); 1008 EVT VT = Lo.getValueType(); 1009 1010 // SRA expansion: 1011 // if Shamt-XLEN < 0: // Shamt < XLEN 1012 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 1013 // Hi = Hi >>s Shamt 1014 // else: 1015 // Lo = Hi >>s (Shamt-XLEN); 1016 // Hi = Hi >>s (XLEN-1) 1017 // 1018 // SRL expansion: 1019 // if Shamt-XLEN < 0: // Shamt < XLEN 1020 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt)) 1021 // Hi = Hi >>u Shamt 1022 // else: 1023 // Lo = Hi >>u (Shamt-XLEN); 1024 // Hi = 0; 1025 1026 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 1027 1028 SDValue Zero = DAG.getConstant(0, DL, VT); 1029 SDValue One = DAG.getConstant(1, DL, VT); 1030 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 1031 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 1032 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 1033 SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt); 1034 1035 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 1036 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 1037 SDValue ShiftLeftHi = 1038 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 1039 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 1040 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 1041 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 1042 SDValue HiFalse = 1043 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 1044 1045 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 1046 1047 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 1048 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 1049 1050 SDValue Parts[2] = {Lo, Hi}; 1051 return DAG.getMergeValues(Parts, DL); 1052 } 1053 1054 // Custom-lower a SPLAT_VECTOR where XLEN<SEW, as the SEW element type is 1055 // illegal (currently only vXi64 RV32). 1056 // FIXME: We could also catch non-constant sign-extended i32 values and lower 1057 // them to SPLAT_VECTOR_I64 1058 SDValue RISCVTargetLowering::lowerSPLATVECTOR(SDValue Op, 1059 SelectionDAG &DAG) const { 1060 SDLoc DL(Op); 1061 EVT VecVT = Op.getValueType(); 1062 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 1063 "Unexpected SPLAT_VECTOR lowering"); 1064 SDValue SplatVal = Op.getOperand(0); 1065 1066 // If we can prove that the value is a sign-extended 32-bit value, lower this 1067 // as a custom node in order to try and match RVV vector/scalar instructions. 1068 if (auto *CVal = dyn_cast<ConstantSDNode>(SplatVal)) { 1069 if (isInt<32>(CVal->getSExtValue())) 1070 return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, 1071 DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32)); 1072 } 1073 1074 // Else, on RV32 we lower an i64-element SPLAT_VECTOR thus, being careful not 1075 // to accidentally sign-extend the 32-bit halves to the e64 SEW: 1076 // vmv.v.x vX, hi 1077 // vsll.vx vX, vX, /*32*/ 1078 // vmv.v.x vY, lo 1079 // vsll.vx vY, vY, /*32*/ 1080 // vsrl.vx vY, vY, /*32*/ 1081 // vor.vv vX, vX, vY 1082 SDValue One = DAG.getConstant(1, DL, MVT::i32); 1083 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 1084 SDValue ThirtyTwoV = DAG.getConstant(32, DL, VecVT); 1085 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, Zero); 1086 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, SplatVal, One); 1087 1088 Lo = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo); 1089 Lo = DAG.getNode(ISD::SHL, DL, VecVT, Lo, ThirtyTwoV); 1090 Lo = DAG.getNode(ISD::SRL, DL, VecVT, Lo, ThirtyTwoV); 1091 1092 if (isNullConstant(Hi)) 1093 return Lo; 1094 1095 Hi = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Hi); 1096 Hi = DAG.getNode(ISD::SHL, DL, VecVT, Hi, ThirtyTwoV); 1097 1098 return DAG.getNode(ISD::OR, DL, VecVT, Lo, Hi); 1099 } 1100 1101 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 1102 SelectionDAG &DAG) const { 1103 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1104 SDLoc DL(Op); 1105 1106 if (Subtarget.hasStdExtV()) { 1107 // Some RVV intrinsics may claim that they want an integer operand to be 1108 // extended. 1109 if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1110 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) { 1111 if (II->ExtendedOperand) { 1112 assert(II->ExtendedOperand < Op.getNumOperands()); 1113 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 1114 SDValue &ScalarOp = Operands[II->ExtendedOperand]; 1115 EVT OpVT = ScalarOp.getValueType(); 1116 if (OpVT == MVT::i8 || OpVT == MVT::i16 || 1117 (OpVT == MVT::i32 && Subtarget.is64Bit())) { 1118 // If the operand is a constant, sign extend to increase our chances 1119 // of being able to use a .vi instruction. ANY_EXTEND would become a 1120 // a zero extend and the simm5 check in isel would fail. 1121 // FIXME: Should we ignore the upper bits in isel instead? 1122 unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND 1123 : ISD::ANY_EXTEND; 1124 ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp); 1125 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 1126 Operands); 1127 } 1128 } 1129 } 1130 } 1131 1132 switch (IntNo) { 1133 default: 1134 return SDValue(); // Don't custom lower most intrinsics. 1135 case Intrinsic::thread_pointer: { 1136 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 1137 return DAG.getRegister(RISCV::X4, PtrVT); 1138 } 1139 case Intrinsic::riscv_vmv_x_s: 1140 assert(Op.getValueType() == Subtarget.getXLenVT() && "Unexpected VT!"); 1141 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 1142 Op.getOperand(1)); 1143 } 1144 } 1145 1146 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 1147 SelectionDAG &DAG) const { 1148 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 1149 SDLoc DL(Op); 1150 1151 if (Subtarget.hasStdExtV()) { 1152 // Some RVV intrinsics may claim that they want an integer operand to be 1153 // extended. 1154 if (const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1155 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo)) { 1156 if (II->ExtendedOperand) { 1157 // The operands start from the second argument in INTRINSIC_W_CHAIN. 1158 unsigned ExtendOp = II->ExtendedOperand + 1; 1159 assert(ExtendOp < Op.getNumOperands()); 1160 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 1161 SDValue &ScalarOp = Operands[ExtendOp]; 1162 EVT OpVT = ScalarOp.getValueType(); 1163 if (OpVT == MVT::i8 || OpVT == MVT::i16 || 1164 (OpVT == MVT::i32 && Subtarget.is64Bit())) { 1165 // If the operand is a constant, sign extend to increase our chances 1166 // of being able to use a .vi instruction. ANY_EXTEND would become a 1167 // a zero extend and the simm5 check in isel would fail. 1168 // FIXME: Should we ignore the upper bits in isel instead? 1169 unsigned ExtOpc = isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND 1170 : ISD::ANY_EXTEND; 1171 ScalarOp = DAG.getNode(ExtOpc, DL, Subtarget.getXLenVT(), ScalarOp); 1172 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, Op->getVTList(), 1173 Operands); 1174 } 1175 } 1176 } 1177 } 1178 1179 return SDValue(); 1180 } 1181 1182 // Returns the opcode of the target-specific SDNode that implements the 32-bit 1183 // form of the given Opcode. 1184 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 1185 switch (Opcode) { 1186 default: 1187 llvm_unreachable("Unexpected opcode"); 1188 case ISD::SHL: 1189 return RISCVISD::SLLW; 1190 case ISD::SRA: 1191 return RISCVISD::SRAW; 1192 case ISD::SRL: 1193 return RISCVISD::SRLW; 1194 case ISD::SDIV: 1195 return RISCVISD::DIVW; 1196 case ISD::UDIV: 1197 return RISCVISD::DIVUW; 1198 case ISD::UREM: 1199 return RISCVISD::REMUW; 1200 case ISD::ROTL: 1201 return RISCVISD::ROLW; 1202 case ISD::ROTR: 1203 return RISCVISD::RORW; 1204 case RISCVISD::GREVI: 1205 return RISCVISD::GREVIW; 1206 case RISCVISD::GORCI: 1207 return RISCVISD::GORCIW; 1208 } 1209 } 1210 1211 // Converts the given 32-bit operation to a target-specific SelectionDAG node. 1212 // Because i32 isn't a legal type for RV64, these operations would otherwise 1213 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W 1214 // later one because the fact the operation was originally of type i32 is 1215 // lost. 1216 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG) { 1217 SDLoc DL(N); 1218 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 1219 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 1220 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 1221 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 1222 // ReplaceNodeResults requires we maintain the same type for the return value. 1223 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 1224 } 1225 1226 // Converts the given 32-bit operation to a i64 operation with signed extension 1227 // semantic to reduce the signed extension instructions. 1228 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 1229 SDLoc DL(N); 1230 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 1231 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 1232 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 1233 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 1234 DAG.getValueType(MVT::i32)); 1235 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 1236 } 1237 1238 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 1239 SmallVectorImpl<SDValue> &Results, 1240 SelectionDAG &DAG) const { 1241 SDLoc DL(N); 1242 switch (N->getOpcode()) { 1243 default: 1244 llvm_unreachable("Don't know how to custom type legalize this operation!"); 1245 case ISD::STRICT_FP_TO_SINT: 1246 case ISD::STRICT_FP_TO_UINT: 1247 case ISD::FP_TO_SINT: 1248 case ISD::FP_TO_UINT: { 1249 bool IsStrict = N->isStrictFPOpcode(); 1250 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1251 "Unexpected custom legalisation"); 1252 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 1253 // If the FP type needs to be softened, emit a library call using the 'si' 1254 // version. If we left it to default legalization we'd end up with 'di'. If 1255 // the FP type doesn't need to be softened just let generic type 1256 // legalization promote the result type. 1257 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 1258 TargetLowering::TypeSoftenFloat) 1259 return; 1260 RTLIB::Libcall LC; 1261 if (N->getOpcode() == ISD::FP_TO_SINT || 1262 N->getOpcode() == ISD::STRICT_FP_TO_SINT) 1263 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 1264 else 1265 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 1266 MakeLibCallOptions CallOptions; 1267 EVT OpVT = Op0.getValueType(); 1268 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 1269 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 1270 SDValue Result; 1271 std::tie(Result, Chain) = 1272 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 1273 Results.push_back(Result); 1274 if (IsStrict) 1275 Results.push_back(Chain); 1276 break; 1277 } 1278 case ISD::READCYCLECOUNTER: { 1279 assert(!Subtarget.is64Bit() && 1280 "READCYCLECOUNTER only has custom type legalization on riscv32"); 1281 1282 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 1283 SDValue RCW = 1284 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 1285 1286 Results.push_back( 1287 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 1288 Results.push_back(RCW.getValue(2)); 1289 break; 1290 } 1291 case ISD::ADD: 1292 case ISD::SUB: 1293 case ISD::MUL: 1294 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1295 "Unexpected custom legalisation"); 1296 if (N->getOperand(1).getOpcode() == ISD::Constant) 1297 return; 1298 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 1299 break; 1300 case ISD::SHL: 1301 case ISD::SRA: 1302 case ISD::SRL: 1303 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1304 "Unexpected custom legalisation"); 1305 if (N->getOperand(1).getOpcode() == ISD::Constant) 1306 return; 1307 Results.push_back(customLegalizeToWOp(N, DAG)); 1308 break; 1309 case ISD::ROTL: 1310 case ISD::ROTR: 1311 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1312 "Unexpected custom legalisation"); 1313 Results.push_back(customLegalizeToWOp(N, DAG)); 1314 break; 1315 case ISD::SDIV: 1316 case ISD::UDIV: 1317 case ISD::UREM: 1318 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1319 Subtarget.hasStdExtM() && "Unexpected custom legalisation"); 1320 if (N->getOperand(0).getOpcode() == ISD::Constant || 1321 N->getOperand(1).getOpcode() == ISD::Constant) 1322 return; 1323 Results.push_back(customLegalizeToWOp(N, DAG)); 1324 break; 1325 case ISD::BITCAST: { 1326 assert(((N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1327 Subtarget.hasStdExtF()) || 1328 (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh())) && 1329 "Unexpected custom legalisation"); 1330 SDValue Op0 = N->getOperand(0); 1331 if (N->getValueType(0) == MVT::i16 && Subtarget.hasStdExtZfh()) { 1332 if (Op0.getValueType() != MVT::f16) 1333 return; 1334 SDValue FPConv = 1335 DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, Subtarget.getXLenVT(), Op0); 1336 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 1337 } else if (N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1338 Subtarget.hasStdExtF()) { 1339 if (Op0.getValueType() != MVT::f32) 1340 return; 1341 SDValue FPConv = 1342 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 1343 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 1344 } 1345 break; 1346 } 1347 case RISCVISD::GREVI: 1348 case RISCVISD::GORCI: { 1349 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1350 "Unexpected custom legalisation"); 1351 // This is similar to customLegalizeToWOp, except that we pass the second 1352 // operand (a TargetConstant) straight through: it is already of type 1353 // XLenVT. 1354 SDLoc DL(N); 1355 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 1356 SDValue NewOp0 = 1357 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 1358 SDValue NewRes = 1359 DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, N->getOperand(1)); 1360 // ReplaceNodeResults requires we maintain the same type for the return 1361 // value. 1362 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 1363 break; 1364 } 1365 case ISD::BSWAP: 1366 case ISD::BITREVERSE: { 1367 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1368 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 1369 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 1370 N->getOperand(0)); 1371 unsigned Imm = N->getOpcode() == ISD::BITREVERSE ? 31 : 24; 1372 SDValue GREVIW = DAG.getNode(RISCVISD::GREVIW, DL, MVT::i64, NewOp0, 1373 DAG.getTargetConstant(Imm, DL, 1374 Subtarget.getXLenVT())); 1375 // ReplaceNodeResults requires we maintain the same type for the return 1376 // value. 1377 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, GREVIW)); 1378 break; 1379 } 1380 case ISD::FSHL: 1381 case ISD::FSHR: { 1382 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 1383 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 1384 SDValue NewOp0 = 1385 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 1386 SDValue NewOp1 = 1387 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 1388 SDValue NewOp2 = 1389 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 1390 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 1391 // Mask the shift amount to 5 bits. 1392 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 1393 DAG.getConstant(0x1f, DL, MVT::i64)); 1394 unsigned Opc = 1395 N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW; 1396 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2); 1397 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 1398 break; 1399 } 1400 case ISD::INTRINSIC_WO_CHAIN: { 1401 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 1402 switch (IntNo) { 1403 default: 1404 llvm_unreachable( 1405 "Don't know how to custom type legalize this intrinsic!"); 1406 case Intrinsic::riscv_vmv_x_s: { 1407 EVT VT = N->getValueType(0); 1408 assert((VT == MVT::i8 || VT == MVT::i16 || 1409 (Subtarget.is64Bit() && VT == MVT::i32)) && 1410 "Unexpected custom legalisation!"); 1411 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 1412 Subtarget.getXLenVT(), N->getOperand(1)); 1413 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 1414 break; 1415 } 1416 } 1417 break; 1418 } 1419 } 1420 } 1421 1422 // A structure to hold one of the bit-manipulation patterns below. Together, a 1423 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 1424 // (or (and (shl x, 1), 0xAAAAAAAA), 1425 // (and (srl x, 1), 0x55555555)) 1426 struct RISCVBitmanipPat { 1427 SDValue Op; 1428 unsigned ShAmt; 1429 bool IsSHL; 1430 1431 bool formsPairWith(const RISCVBitmanipPat &Other) const { 1432 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 1433 } 1434 }; 1435 1436 // Matches any of the following bit-manipulation patterns: 1437 // (and (shl x, 1), (0x55555555 << 1)) 1438 // (and (srl x, 1), 0x55555555) 1439 // (shl (and x, 0x55555555), 1) 1440 // (srl (and x, (0x55555555 << 1)), 1) 1441 // where the shift amount and mask may vary thus: 1442 // [1] = 0x55555555 / 0xAAAAAAAA 1443 // [2] = 0x33333333 / 0xCCCCCCCC 1444 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 1445 // [8] = 0x00FF00FF / 0xFF00FF00 1446 // [16] = 0x0000FFFF / 0xFFFFFFFF 1447 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 1448 static Optional<RISCVBitmanipPat> matchRISCVBitmanipPat(SDValue Op) { 1449 Optional<uint64_t> Mask; 1450 // Optionally consume a mask around the shift operation. 1451 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 1452 Mask = Op.getConstantOperandVal(1); 1453 Op = Op.getOperand(0); 1454 } 1455 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 1456 return None; 1457 bool IsSHL = Op.getOpcode() == ISD::SHL; 1458 1459 if (!isa<ConstantSDNode>(Op.getOperand(1))) 1460 return None; 1461 auto ShAmt = Op.getConstantOperandVal(1); 1462 1463 if (!isPowerOf2_64(ShAmt)) 1464 return None; 1465 1466 // These are the unshifted masks which we use to match bit-manipulation 1467 // patterns. They may be shifted left in certain circumstances. 1468 static const uint64_t BitmanipMasks[] = { 1469 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 1470 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL, 1471 }; 1472 1473 unsigned MaskIdx = Log2_64(ShAmt); 1474 if (MaskIdx >= array_lengthof(BitmanipMasks)) 1475 return None; 1476 1477 auto Src = Op.getOperand(0); 1478 1479 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 1480 auto ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 1481 1482 // The expected mask is shifted left when the AND is found around SHL 1483 // patterns. 1484 // ((x >> 1) & 0x55555555) 1485 // ((x << 1) & 0xAAAAAAAA) 1486 bool SHLExpMask = IsSHL; 1487 1488 if (!Mask) { 1489 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 1490 // the mask is all ones: consume that now. 1491 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 1492 Mask = Src.getConstantOperandVal(1); 1493 Src = Src.getOperand(0); 1494 // The expected mask is now in fact shifted left for SRL, so reverse the 1495 // decision. 1496 // ((x & 0xAAAAAAAA) >> 1) 1497 // ((x & 0x55555555) << 1) 1498 SHLExpMask = !SHLExpMask; 1499 } else { 1500 // Use a default shifted mask of all-ones if there's no AND, truncated 1501 // down to the expected width. This simplifies the logic later on. 1502 Mask = maskTrailingOnes<uint64_t>(Width); 1503 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 1504 } 1505 } 1506 1507 if (SHLExpMask) 1508 ExpMask <<= ShAmt; 1509 1510 if (Mask != ExpMask) 1511 return None; 1512 1513 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 1514 } 1515 1516 // Match the following pattern as a GREVI(W) operation 1517 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 1518 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 1519 const RISCVSubtarget &Subtarget) { 1520 EVT VT = Op.getValueType(); 1521 1522 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 1523 auto LHS = matchRISCVBitmanipPat(Op.getOperand(0)); 1524 auto RHS = matchRISCVBitmanipPat(Op.getOperand(1)); 1525 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 1526 SDLoc DL(Op); 1527 return DAG.getNode( 1528 RISCVISD::GREVI, DL, VT, LHS->Op, 1529 DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT())); 1530 } 1531 } 1532 return SDValue(); 1533 } 1534 1535 // Matches any the following pattern as a GORCI(W) operation 1536 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 1537 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 1538 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 1539 // Note that with the variant of 3., 1540 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 1541 // the inner pattern will first be matched as GREVI and then the outer 1542 // pattern will be matched to GORC via the first rule above. 1543 // 4. (or (rotl/rotr x, bitwidth/2), x) 1544 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 1545 const RISCVSubtarget &Subtarget) { 1546 EVT VT = Op.getValueType(); 1547 1548 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 1549 SDLoc DL(Op); 1550 SDValue Op0 = Op.getOperand(0); 1551 SDValue Op1 = Op.getOperand(1); 1552 1553 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 1554 if (Reverse.getOpcode() == RISCVISD::GREVI && Reverse.getOperand(0) == X && 1555 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 1556 return DAG.getNode(RISCVISD::GORCI, DL, VT, X, Reverse.getOperand(1)); 1557 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 1558 if ((Reverse.getOpcode() == ISD::ROTL || 1559 Reverse.getOpcode() == ISD::ROTR) && 1560 Reverse.getOperand(0) == X && 1561 isa<ConstantSDNode>(Reverse.getOperand(1))) { 1562 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 1563 if (RotAmt == (VT.getSizeInBits() / 2)) 1564 return DAG.getNode( 1565 RISCVISD::GORCI, DL, VT, X, 1566 DAG.getTargetConstant(RotAmt, DL, Subtarget.getXLenVT())); 1567 } 1568 return SDValue(); 1569 }; 1570 1571 // Check for either commutable permutation of (or (GREVI x, shamt), x) 1572 if (SDValue V = MatchOROfReverse(Op0, Op1)) 1573 return V; 1574 if (SDValue V = MatchOROfReverse(Op1, Op0)) 1575 return V; 1576 1577 // OR is commutable so canonicalize its OR operand to the left 1578 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 1579 std::swap(Op0, Op1); 1580 if (Op0.getOpcode() != ISD::OR) 1581 return SDValue(); 1582 SDValue OrOp0 = Op0.getOperand(0); 1583 SDValue OrOp1 = Op0.getOperand(1); 1584 auto LHS = matchRISCVBitmanipPat(OrOp0); 1585 // OR is commutable so swap the operands and try again: x might have been 1586 // on the left 1587 if (!LHS) { 1588 std::swap(OrOp0, OrOp1); 1589 LHS = matchRISCVBitmanipPat(OrOp0); 1590 } 1591 auto RHS = matchRISCVBitmanipPat(Op1); 1592 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 1593 return DAG.getNode( 1594 RISCVISD::GORCI, DL, VT, LHS->Op, 1595 DAG.getTargetConstant(LHS->ShAmt, DL, Subtarget.getXLenVT())); 1596 } 1597 } 1598 return SDValue(); 1599 } 1600 1601 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 1602 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 1603 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 1604 // not undo itself, but they are redundant. 1605 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 1606 unsigned ShAmt1 = N->getConstantOperandVal(1); 1607 SDValue Src = N->getOperand(0); 1608 1609 if (Src.getOpcode() != N->getOpcode()) 1610 return SDValue(); 1611 1612 unsigned ShAmt2 = Src.getConstantOperandVal(1); 1613 Src = Src.getOperand(0); 1614 1615 unsigned CombinedShAmt; 1616 if (N->getOpcode() == RISCVISD::GORCI || N->getOpcode() == RISCVISD::GORCIW) 1617 CombinedShAmt = ShAmt1 | ShAmt2; 1618 else 1619 CombinedShAmt = ShAmt1 ^ ShAmt2; 1620 1621 if (CombinedShAmt == 0) 1622 return Src; 1623 1624 SDLoc DL(N); 1625 return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), Src, 1626 DAG.getTargetConstant(CombinedShAmt, DL, 1627 N->getOperand(1).getValueType())); 1628 } 1629 1630 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 1631 DAGCombinerInfo &DCI) const { 1632 SelectionDAG &DAG = DCI.DAG; 1633 1634 switch (N->getOpcode()) { 1635 default: 1636 break; 1637 case RISCVISD::SplitF64: { 1638 SDValue Op0 = N->getOperand(0); 1639 // If the input to SplitF64 is just BuildPairF64 then the operation is 1640 // redundant. Instead, use BuildPairF64's operands directly. 1641 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 1642 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 1643 1644 SDLoc DL(N); 1645 1646 // It's cheaper to materialise two 32-bit integers than to load a double 1647 // from the constant pool and transfer it to integer registers through the 1648 // stack. 1649 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 1650 APInt V = C->getValueAPF().bitcastToAPInt(); 1651 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 1652 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 1653 return DCI.CombineTo(N, Lo, Hi); 1654 } 1655 1656 // This is a target-specific version of a DAGCombine performed in 1657 // DAGCombiner::visitBITCAST. It performs the equivalent of: 1658 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 1659 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 1660 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 1661 !Op0.getNode()->hasOneUse()) 1662 break; 1663 SDValue NewSplitF64 = 1664 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 1665 Op0.getOperand(0)); 1666 SDValue Lo = NewSplitF64.getValue(0); 1667 SDValue Hi = NewSplitF64.getValue(1); 1668 APInt SignBit = APInt::getSignMask(32); 1669 if (Op0.getOpcode() == ISD::FNEG) { 1670 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 1671 DAG.getConstant(SignBit, DL, MVT::i32)); 1672 return DCI.CombineTo(N, Lo, NewHi); 1673 } 1674 assert(Op0.getOpcode() == ISD::FABS); 1675 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 1676 DAG.getConstant(~SignBit, DL, MVT::i32)); 1677 return DCI.CombineTo(N, Lo, NewHi); 1678 } 1679 case RISCVISD::SLLW: 1680 case RISCVISD::SRAW: 1681 case RISCVISD::SRLW: 1682 case RISCVISD::ROLW: 1683 case RISCVISD::RORW: { 1684 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 1685 SDValue LHS = N->getOperand(0); 1686 SDValue RHS = N->getOperand(1); 1687 APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32); 1688 APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5); 1689 if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) || 1690 SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) { 1691 if (N->getOpcode() != ISD::DELETED_NODE) 1692 DCI.AddToWorklist(N); 1693 return SDValue(N, 0); 1694 } 1695 break; 1696 } 1697 case RISCVISD::FSLW: 1698 case RISCVISD::FSRW: { 1699 // Only the lower 32 bits of Values and lower 6 bits of shift amount are 1700 // read. 1701 SDValue Op0 = N->getOperand(0); 1702 SDValue Op1 = N->getOperand(1); 1703 SDValue ShAmt = N->getOperand(2); 1704 APInt OpMask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32); 1705 APInt ShAmtMask = APInt::getLowBitsSet(ShAmt.getValueSizeInBits(), 6); 1706 if (SimplifyDemandedBits(Op0, OpMask, DCI) || 1707 SimplifyDemandedBits(Op1, OpMask, DCI) || 1708 SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) { 1709 if (N->getOpcode() != ISD::DELETED_NODE) 1710 DCI.AddToWorklist(N); 1711 return SDValue(N, 0); 1712 } 1713 break; 1714 } 1715 case RISCVISD::GREVIW: 1716 case RISCVISD::GORCIW: { 1717 // Only the lower 32 bits of the first operand are read 1718 SDValue Op0 = N->getOperand(0); 1719 APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32); 1720 if (SimplifyDemandedBits(Op0, Mask, DCI)) { 1721 if (N->getOpcode() != ISD::DELETED_NODE) 1722 DCI.AddToWorklist(N); 1723 return SDValue(N, 0); 1724 } 1725 1726 return combineGREVI_GORCI(N, DCI.DAG); 1727 } 1728 case RISCVISD::FMV_X_ANYEXTW_RV64: { 1729 SDLoc DL(N); 1730 SDValue Op0 = N->getOperand(0); 1731 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 1732 // conversion is unnecessary and can be replaced with an ANY_EXTEND 1733 // of the FMV_W_X_RV64 operand. 1734 if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) { 1735 assert(Op0.getOperand(0).getValueType() == MVT::i64 && 1736 "Unexpected value type!"); 1737 return Op0.getOperand(0); 1738 } 1739 1740 // This is a target-specific version of a DAGCombine performed in 1741 // DAGCombiner::visitBITCAST. It performs the equivalent of: 1742 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 1743 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 1744 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 1745 !Op0.getNode()->hasOneUse()) 1746 break; 1747 SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, 1748 Op0.getOperand(0)); 1749 APInt SignBit = APInt::getSignMask(32).sext(64); 1750 if (Op0.getOpcode() == ISD::FNEG) 1751 return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV, 1752 DAG.getConstant(SignBit, DL, MVT::i64)); 1753 1754 assert(Op0.getOpcode() == ISD::FABS); 1755 return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV, 1756 DAG.getConstant(~SignBit, DL, MVT::i64)); 1757 } 1758 case RISCVISD::GREVI: 1759 case RISCVISD::GORCI: 1760 return combineGREVI_GORCI(N, DCI.DAG); 1761 case ISD::OR: 1762 if (auto GREV = combineORToGREV(SDValue(N, 0), DCI.DAG, Subtarget)) 1763 return GREV; 1764 if (auto GORC = combineORToGORC(SDValue(N, 0), DCI.DAG, Subtarget)) 1765 return GORC; 1766 break; 1767 } 1768 1769 return SDValue(); 1770 } 1771 1772 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 1773 const SDNode *N, CombineLevel Level) const { 1774 // The following folds are only desirable if `(OP _, c1 << c2)` can be 1775 // materialised in fewer instructions than `(OP _, c1)`: 1776 // 1777 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 1778 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 1779 SDValue N0 = N->getOperand(0); 1780 EVT Ty = N0.getValueType(); 1781 if (Ty.isScalarInteger() && 1782 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 1783 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 1784 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 1785 if (C1 && C2) { 1786 APInt C1Int = C1->getAPIntValue(); 1787 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 1788 1789 // We can materialise `c1 << c2` into an add immediate, so it's "free", 1790 // and the combine should happen, to potentially allow further combines 1791 // later. 1792 if (ShiftedC1Int.getMinSignedBits() <= 64 && 1793 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 1794 return true; 1795 1796 // We can materialise `c1` in an add immediate, so it's "free", and the 1797 // combine should be prevented. 1798 if (C1Int.getMinSignedBits() <= 64 && 1799 isLegalAddImmediate(C1Int.getSExtValue())) 1800 return false; 1801 1802 // Neither constant will fit into an immediate, so find materialisation 1803 // costs. 1804 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 1805 Subtarget.is64Bit()); 1806 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 1807 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit()); 1808 1809 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 1810 // combine should be prevented. 1811 if (C1Cost < ShiftedC1Cost) 1812 return false; 1813 } 1814 } 1815 return true; 1816 } 1817 1818 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 1819 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 1820 unsigned Depth) const { 1821 switch (Op.getOpcode()) { 1822 default: 1823 break; 1824 case RISCVISD::SLLW: 1825 case RISCVISD::SRAW: 1826 case RISCVISD::SRLW: 1827 case RISCVISD::DIVW: 1828 case RISCVISD::DIVUW: 1829 case RISCVISD::REMUW: 1830 case RISCVISD::ROLW: 1831 case RISCVISD::RORW: 1832 case RISCVISD::GREVIW: 1833 case RISCVISD::GORCIW: 1834 case RISCVISD::FSLW: 1835 case RISCVISD::FSRW: 1836 // TODO: As the result is sign-extended, this is conservatively correct. A 1837 // more precise answer could be calculated for SRAW depending on known 1838 // bits in the shift amount. 1839 return 33; 1840 case RISCVISD::VMV_X_S: 1841 // The number of sign bits of the scalar result is computed by obtaining the 1842 // element type of the input vector operand, substracting its width from the 1843 // XLEN, and then adding one (sign bit within the element type). 1844 return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1; 1845 } 1846 1847 return 1; 1848 } 1849 1850 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 1851 MachineBasicBlock *BB) { 1852 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 1853 1854 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 1855 // Should the count have wrapped while it was being read, we need to try 1856 // again. 1857 // ... 1858 // read: 1859 // rdcycleh x3 # load high word of cycle 1860 // rdcycle x2 # load low word of cycle 1861 // rdcycleh x4 # load high word of cycle 1862 // bne x3, x4, read # check if high word reads match, otherwise try again 1863 // ... 1864 1865 MachineFunction &MF = *BB->getParent(); 1866 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 1867 MachineFunction::iterator It = ++BB->getIterator(); 1868 1869 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 1870 MF.insert(It, LoopMBB); 1871 1872 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 1873 MF.insert(It, DoneMBB); 1874 1875 // Transfer the remainder of BB and its successor edges to DoneMBB. 1876 DoneMBB->splice(DoneMBB->begin(), BB, 1877 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 1878 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 1879 1880 BB->addSuccessor(LoopMBB); 1881 1882 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 1883 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 1884 Register LoReg = MI.getOperand(0).getReg(); 1885 Register HiReg = MI.getOperand(1).getReg(); 1886 DebugLoc DL = MI.getDebugLoc(); 1887 1888 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 1889 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 1890 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 1891 .addReg(RISCV::X0); 1892 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 1893 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 1894 .addReg(RISCV::X0); 1895 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 1896 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 1897 .addReg(RISCV::X0); 1898 1899 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 1900 .addReg(HiReg) 1901 .addReg(ReadAgainReg) 1902 .addMBB(LoopMBB); 1903 1904 LoopMBB->addSuccessor(LoopMBB); 1905 LoopMBB->addSuccessor(DoneMBB); 1906 1907 MI.eraseFromParent(); 1908 1909 return DoneMBB; 1910 } 1911 1912 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 1913 MachineBasicBlock *BB) { 1914 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 1915 1916 MachineFunction &MF = *BB->getParent(); 1917 DebugLoc DL = MI.getDebugLoc(); 1918 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1919 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 1920 Register LoReg = MI.getOperand(0).getReg(); 1921 Register HiReg = MI.getOperand(1).getReg(); 1922 Register SrcReg = MI.getOperand(2).getReg(); 1923 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 1924 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 1925 1926 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 1927 RI); 1928 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 1929 MachineMemOperand *MMOLo = 1930 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 1931 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 1932 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 1933 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 1934 .addFrameIndex(FI) 1935 .addImm(0) 1936 .addMemOperand(MMOLo); 1937 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 1938 .addFrameIndex(FI) 1939 .addImm(4) 1940 .addMemOperand(MMOHi); 1941 MI.eraseFromParent(); // The pseudo instruction is gone now. 1942 return BB; 1943 } 1944 1945 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 1946 MachineBasicBlock *BB) { 1947 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 1948 "Unexpected instruction"); 1949 1950 MachineFunction &MF = *BB->getParent(); 1951 DebugLoc DL = MI.getDebugLoc(); 1952 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1953 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 1954 Register DstReg = MI.getOperand(0).getReg(); 1955 Register LoReg = MI.getOperand(1).getReg(); 1956 Register HiReg = MI.getOperand(2).getReg(); 1957 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 1958 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 1959 1960 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 1961 MachineMemOperand *MMOLo = 1962 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 1963 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 1964 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 1965 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 1966 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 1967 .addFrameIndex(FI) 1968 .addImm(0) 1969 .addMemOperand(MMOLo); 1970 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 1971 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 1972 .addFrameIndex(FI) 1973 .addImm(4) 1974 .addMemOperand(MMOHi); 1975 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 1976 MI.eraseFromParent(); // The pseudo instruction is gone now. 1977 return BB; 1978 } 1979 1980 static bool isSelectPseudo(MachineInstr &MI) { 1981 switch (MI.getOpcode()) { 1982 default: 1983 return false; 1984 case RISCV::Select_GPR_Using_CC_GPR: 1985 case RISCV::Select_FPR16_Using_CC_GPR: 1986 case RISCV::Select_FPR32_Using_CC_GPR: 1987 case RISCV::Select_FPR64_Using_CC_GPR: 1988 return true; 1989 } 1990 } 1991 1992 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 1993 MachineBasicBlock *BB) { 1994 // To "insert" Select_* instructions, we actually have to insert the triangle 1995 // control-flow pattern. The incoming instructions know the destination vreg 1996 // to set, the condition code register to branch on, the true/false values to 1997 // select between, and the condcode to use to select the appropriate branch. 1998 // 1999 // We produce the following control flow: 2000 // HeadMBB 2001 // | \ 2002 // | IfFalseMBB 2003 // | / 2004 // TailMBB 2005 // 2006 // When we find a sequence of selects we attempt to optimize their emission 2007 // by sharing the control flow. Currently we only handle cases where we have 2008 // multiple selects with the exact same condition (same LHS, RHS and CC). 2009 // The selects may be interleaved with other instructions if the other 2010 // instructions meet some requirements we deem safe: 2011 // - They are debug instructions. Otherwise, 2012 // - They do not have side-effects, do not access memory and their inputs do 2013 // not depend on the results of the select pseudo-instructions. 2014 // The TrueV/FalseV operands of the selects cannot depend on the result of 2015 // previous selects in the sequence. 2016 // These conditions could be further relaxed. See the X86 target for a 2017 // related approach and more information. 2018 Register LHS = MI.getOperand(1).getReg(); 2019 Register RHS = MI.getOperand(2).getReg(); 2020 auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm()); 2021 2022 SmallVector<MachineInstr *, 4> SelectDebugValues; 2023 SmallSet<Register, 4> SelectDests; 2024 SelectDests.insert(MI.getOperand(0).getReg()); 2025 2026 MachineInstr *LastSelectPseudo = &MI; 2027 2028 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 2029 SequenceMBBI != E; ++SequenceMBBI) { 2030 if (SequenceMBBI->isDebugInstr()) 2031 continue; 2032 else if (isSelectPseudo(*SequenceMBBI)) { 2033 if (SequenceMBBI->getOperand(1).getReg() != LHS || 2034 SequenceMBBI->getOperand(2).getReg() != RHS || 2035 SequenceMBBI->getOperand(3).getImm() != CC || 2036 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 2037 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 2038 break; 2039 LastSelectPseudo = &*SequenceMBBI; 2040 SequenceMBBI->collectDebugValues(SelectDebugValues); 2041 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 2042 } else { 2043 if (SequenceMBBI->hasUnmodeledSideEffects() || 2044 SequenceMBBI->mayLoadOrStore()) 2045 break; 2046 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 2047 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 2048 })) 2049 break; 2050 } 2051 } 2052 2053 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 2054 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 2055 DebugLoc DL = MI.getDebugLoc(); 2056 MachineFunction::iterator I = ++BB->getIterator(); 2057 2058 MachineBasicBlock *HeadMBB = BB; 2059 MachineFunction *F = BB->getParent(); 2060 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 2061 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 2062 2063 F->insert(I, IfFalseMBB); 2064 F->insert(I, TailMBB); 2065 2066 // Transfer debug instructions associated with the selects to TailMBB. 2067 for (MachineInstr *DebugInstr : SelectDebugValues) { 2068 TailMBB->push_back(DebugInstr->removeFromParent()); 2069 } 2070 2071 // Move all instructions after the sequence to TailMBB. 2072 TailMBB->splice(TailMBB->end(), HeadMBB, 2073 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 2074 // Update machine-CFG edges by transferring all successors of the current 2075 // block to the new block which will contain the Phi nodes for the selects. 2076 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 2077 // Set the successors for HeadMBB. 2078 HeadMBB->addSuccessor(IfFalseMBB); 2079 HeadMBB->addSuccessor(TailMBB); 2080 2081 // Insert appropriate branch. 2082 unsigned Opcode = getBranchOpcodeForIntCondCode(CC); 2083 2084 BuildMI(HeadMBB, DL, TII.get(Opcode)) 2085 .addReg(LHS) 2086 .addReg(RHS) 2087 .addMBB(TailMBB); 2088 2089 // IfFalseMBB just falls through to TailMBB. 2090 IfFalseMBB->addSuccessor(TailMBB); 2091 2092 // Create PHIs for all of the select pseudo-instructions. 2093 auto SelectMBBI = MI.getIterator(); 2094 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 2095 auto InsertionPoint = TailMBB->begin(); 2096 while (SelectMBBI != SelectEnd) { 2097 auto Next = std::next(SelectMBBI); 2098 if (isSelectPseudo(*SelectMBBI)) { 2099 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 2100 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 2101 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 2102 .addReg(SelectMBBI->getOperand(4).getReg()) 2103 .addMBB(HeadMBB) 2104 .addReg(SelectMBBI->getOperand(5).getReg()) 2105 .addMBB(IfFalseMBB); 2106 SelectMBBI->eraseFromParent(); 2107 } 2108 SelectMBBI = Next; 2109 } 2110 2111 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 2112 return TailMBB; 2113 } 2114 2115 static MachineBasicBlock *addVSetVL(MachineInstr &MI, MachineBasicBlock *BB, 2116 int VLIndex, unsigned SEWIndex, 2117 unsigned VLMul) { 2118 MachineFunction &MF = *BB->getParent(); 2119 DebugLoc DL = MI.getDebugLoc(); 2120 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 2121 2122 unsigned SEW = MI.getOperand(SEWIndex).getImm(); 2123 assert(RISCVVType::isValidSEW(SEW) && "Unexpected SEW"); 2124 RISCVVSEW ElementWidth = static_cast<RISCVVSEW>(Log2_32(SEW / 8)); 2125 2126 // LMUL should already be encoded correctly. 2127 RISCVVLMUL Multiplier = static_cast<RISCVVLMUL>(VLMul); 2128 2129 MachineRegisterInfo &MRI = MF.getRegInfo(); 2130 2131 // VL and VTYPE are alive here. 2132 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII.get(RISCV::PseudoVSETVLI)); 2133 2134 if (VLIndex >= 0) { 2135 // Set VL (rs1 != X0). 2136 Register DestReg = MRI.createVirtualRegister(&RISCV::GPRRegClass); 2137 MIB.addReg(DestReg, RegState::Define | RegState::Dead) 2138 .addReg(MI.getOperand(VLIndex).getReg()); 2139 } else 2140 // With no VL operator in the pseudo, do not modify VL (rd = X0, rs1 = X0). 2141 MIB.addReg(RISCV::X0, RegState::Define | RegState::Dead) 2142 .addReg(RISCV::X0, RegState::Kill); 2143 2144 // For simplicity we reuse the vtype representation here. 2145 MIB.addImm(RISCVVType::encodeVTYPE(Multiplier, ElementWidth, 2146 /*TailAgnostic*/ true, 2147 /*MaskAgnostic*/ false)); 2148 2149 // Remove (now) redundant operands from pseudo 2150 MI.getOperand(SEWIndex).setImm(-1); 2151 if (VLIndex >= 0) { 2152 MI.getOperand(VLIndex).setReg(RISCV::NoRegister); 2153 MI.getOperand(VLIndex).setIsKill(false); 2154 } 2155 2156 return BB; 2157 } 2158 2159 MachineBasicBlock * 2160 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 2161 MachineBasicBlock *BB) const { 2162 2163 if (const RISCVVPseudosTable::PseudoInfo *RVV = 2164 RISCVVPseudosTable::getPseudoInfo(MI.getOpcode())) { 2165 int VLIndex = RVV->getVLIndex(); 2166 int SEWIndex = RVV->getSEWIndex(); 2167 2168 assert(SEWIndex >= 0 && "SEWIndex must be >= 0"); 2169 return addVSetVL(MI, BB, VLIndex, SEWIndex, RVV->VLMul); 2170 } 2171 2172 switch (MI.getOpcode()) { 2173 default: 2174 llvm_unreachable("Unexpected instr type to insert"); 2175 case RISCV::ReadCycleWide: 2176 assert(!Subtarget.is64Bit() && 2177 "ReadCycleWrite is only to be used on riscv32"); 2178 return emitReadCycleWidePseudo(MI, BB); 2179 case RISCV::Select_GPR_Using_CC_GPR: 2180 case RISCV::Select_FPR16_Using_CC_GPR: 2181 case RISCV::Select_FPR32_Using_CC_GPR: 2182 case RISCV::Select_FPR64_Using_CC_GPR: 2183 return emitSelectPseudo(MI, BB); 2184 case RISCV::BuildPairF64Pseudo: 2185 return emitBuildPairF64Pseudo(MI, BB); 2186 case RISCV::SplitF64Pseudo: 2187 return emitSplitF64Pseudo(MI, BB); 2188 } 2189 } 2190 2191 // Calling Convention Implementation. 2192 // The expectations for frontend ABI lowering vary from target to target. 2193 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 2194 // details, but this is a longer term goal. For now, we simply try to keep the 2195 // role of the frontend as simple and well-defined as possible. The rules can 2196 // be summarised as: 2197 // * Never split up large scalar arguments. We handle them here. 2198 // * If a hardfloat calling convention is being used, and the struct may be 2199 // passed in a pair of registers (fp+fp, int+fp), and both registers are 2200 // available, then pass as two separate arguments. If either the GPRs or FPRs 2201 // are exhausted, then pass according to the rule below. 2202 // * If a struct could never be passed in registers or directly in a stack 2203 // slot (as it is larger than 2*XLEN and the floating point rules don't 2204 // apply), then pass it using a pointer with the byval attribute. 2205 // * If a struct is less than 2*XLEN, then coerce to either a two-element 2206 // word-sized array or a 2*XLEN scalar (depending on alignment). 2207 // * The frontend can determine whether a struct is returned by reference or 2208 // not based on its size and fields. If it will be returned by reference, the 2209 // frontend must modify the prototype so a pointer with the sret annotation is 2210 // passed as the first argument. This is not necessary for large scalar 2211 // returns. 2212 // * Struct return values and varargs should be coerced to structs containing 2213 // register-size fields in the same situations they would be for fixed 2214 // arguments. 2215 2216 static const MCPhysReg ArgGPRs[] = { 2217 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 2218 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 2219 }; 2220 static const MCPhysReg ArgFPR16s[] = { 2221 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 2222 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 2223 }; 2224 static const MCPhysReg ArgFPR32s[] = { 2225 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 2226 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 2227 }; 2228 static const MCPhysReg ArgFPR64s[] = { 2229 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 2230 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 2231 }; 2232 // This is an interim calling convention and it may be changed in the future. 2233 static const MCPhysReg ArgVRs[] = { 2234 RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, RISCV::V20, 2235 RISCV::V21, RISCV::V22, RISCV::V23 2236 }; 2237 static const MCPhysReg ArgVRM2s[] = { 2238 RISCV::V16M2, RISCV::V18M2, RISCV::V20M2, RISCV::V22M2 2239 }; 2240 static const MCPhysReg ArgVRM4s[] = {RISCV::V16M4, RISCV::V20M4}; 2241 static const MCPhysReg ArgVRM8s[] = {RISCV::V16M8}; 2242 2243 // Pass a 2*XLEN argument that has been split into two XLEN values through 2244 // registers or the stack as necessary. 2245 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 2246 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 2247 MVT ValVT2, MVT LocVT2, 2248 ISD::ArgFlagsTy ArgFlags2) { 2249 unsigned XLenInBytes = XLen / 8; 2250 if (Register Reg = State.AllocateReg(ArgGPRs)) { 2251 // At least one half can be passed via register. 2252 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 2253 VA1.getLocVT(), CCValAssign::Full)); 2254 } else { 2255 // Both halves must be passed on the stack, with proper alignment. 2256 Align StackAlign = 2257 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 2258 State.addLoc( 2259 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 2260 State.AllocateStack(XLenInBytes, StackAlign), 2261 VA1.getLocVT(), CCValAssign::Full)); 2262 State.addLoc(CCValAssign::getMem( 2263 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 2264 LocVT2, CCValAssign::Full)); 2265 return false; 2266 } 2267 2268 if (Register Reg = State.AllocateReg(ArgGPRs)) { 2269 // The second half can also be passed via register. 2270 State.addLoc( 2271 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 2272 } else { 2273 // The second half is passed via the stack, without additional alignment. 2274 State.addLoc(CCValAssign::getMem( 2275 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 2276 LocVT2, CCValAssign::Full)); 2277 } 2278 2279 return false; 2280 } 2281 2282 // Implements the RISC-V calling convention. Returns true upon failure. 2283 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 2284 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 2285 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 2286 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 2287 Optional<unsigned> FirstMaskArgument) { 2288 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 2289 assert(XLen == 32 || XLen == 64); 2290 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 2291 2292 // Any return value split in to more than two values can't be returned 2293 // directly. 2294 if (IsRet && ValNo > 1) 2295 return true; 2296 2297 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 2298 // variadic argument, or if no F16/F32 argument registers are available. 2299 bool UseGPRForF16_F32 = true; 2300 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 2301 // variadic argument, or if no F64 argument registers are available. 2302 bool UseGPRForF64 = true; 2303 2304 switch (ABI) { 2305 default: 2306 llvm_unreachable("Unexpected ABI"); 2307 case RISCVABI::ABI_ILP32: 2308 case RISCVABI::ABI_LP64: 2309 break; 2310 case RISCVABI::ABI_ILP32F: 2311 case RISCVABI::ABI_LP64F: 2312 UseGPRForF16_F32 = !IsFixed; 2313 break; 2314 case RISCVABI::ABI_ILP32D: 2315 case RISCVABI::ABI_LP64D: 2316 UseGPRForF16_F32 = !IsFixed; 2317 UseGPRForF64 = !IsFixed; 2318 break; 2319 } 2320 2321 // FPR16, FPR32, and FPR64 alias each other. 2322 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 2323 UseGPRForF16_F32 = true; 2324 UseGPRForF64 = true; 2325 } 2326 2327 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 2328 // similar local variables rather than directly checking against the target 2329 // ABI. 2330 2331 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 2332 LocVT = XLenVT; 2333 LocInfo = CCValAssign::BCvt; 2334 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 2335 LocVT = MVT::i64; 2336 LocInfo = CCValAssign::BCvt; 2337 } 2338 2339 // If this is a variadic argument, the RISC-V calling convention requires 2340 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 2341 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 2342 // be used regardless of whether the original argument was split during 2343 // legalisation or not. The argument will not be passed by registers if the 2344 // original type is larger than 2*XLEN, so the register alignment rule does 2345 // not apply. 2346 unsigned TwoXLenInBytes = (2 * XLen) / 8; 2347 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 2348 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 2349 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 2350 // Skip 'odd' register if necessary. 2351 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 2352 State.AllocateReg(ArgGPRs); 2353 } 2354 2355 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 2356 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 2357 State.getPendingArgFlags(); 2358 2359 assert(PendingLocs.size() == PendingArgFlags.size() && 2360 "PendingLocs and PendingArgFlags out of sync"); 2361 2362 // Handle passing f64 on RV32D with a soft float ABI or when floating point 2363 // registers are exhausted. 2364 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 2365 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 2366 "Can't lower f64 if it is split"); 2367 // Depending on available argument GPRS, f64 may be passed in a pair of 2368 // GPRs, split between a GPR and the stack, or passed completely on the 2369 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 2370 // cases. 2371 Register Reg = State.AllocateReg(ArgGPRs); 2372 LocVT = MVT::i32; 2373 if (!Reg) { 2374 unsigned StackOffset = State.AllocateStack(8, Align(8)); 2375 State.addLoc( 2376 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 2377 return false; 2378 } 2379 if (!State.AllocateReg(ArgGPRs)) 2380 State.AllocateStack(4, Align(4)); 2381 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2382 return false; 2383 } 2384 2385 // Split arguments might be passed indirectly, so keep track of the pending 2386 // values. 2387 if (ArgFlags.isSplit() || !PendingLocs.empty()) { 2388 LocVT = XLenVT; 2389 LocInfo = CCValAssign::Indirect; 2390 PendingLocs.push_back( 2391 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 2392 PendingArgFlags.push_back(ArgFlags); 2393 if (!ArgFlags.isSplitEnd()) { 2394 return false; 2395 } 2396 } 2397 2398 // If the split argument only had two elements, it should be passed directly 2399 // in registers or on the stack. 2400 if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) { 2401 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 2402 // Apply the normal calling convention rules to the first half of the 2403 // split argument. 2404 CCValAssign VA = PendingLocs[0]; 2405 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 2406 PendingLocs.clear(); 2407 PendingArgFlags.clear(); 2408 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 2409 ArgFlags); 2410 } 2411 2412 // Allocate to a register if possible, or else a stack slot. 2413 Register Reg; 2414 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 2415 Reg = State.AllocateReg(ArgFPR16s); 2416 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 2417 Reg = State.AllocateReg(ArgFPR32s); 2418 else if (ValVT == MVT::f64 && !UseGPRForF64) 2419 Reg = State.AllocateReg(ArgFPR64s); 2420 else if (ValVT.isScalableVector()) { 2421 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 2422 if (RC == &RISCV::VRRegClass) { 2423 // Assign the first mask argument to V0. 2424 // This is an interim calling convention and it may be changed in the 2425 // future. 2426 if (FirstMaskArgument.hasValue() && 2427 ValNo == FirstMaskArgument.getValue()) { 2428 Reg = State.AllocateReg(RISCV::V0); 2429 } else { 2430 Reg = State.AllocateReg(ArgVRs); 2431 } 2432 } else if (RC == &RISCV::VRM2RegClass) { 2433 Reg = State.AllocateReg(ArgVRM2s); 2434 } else if (RC == &RISCV::VRM4RegClass) { 2435 Reg = State.AllocateReg(ArgVRM4s); 2436 } else if (RC == &RISCV::VRM8RegClass) { 2437 Reg = State.AllocateReg(ArgVRM8s); 2438 } else { 2439 llvm_unreachable("Unhandled class register for ValueType"); 2440 } 2441 if (!Reg) { 2442 LocInfo = CCValAssign::Indirect; 2443 // Try using a GPR to pass the address 2444 Reg = State.AllocateReg(ArgGPRs); 2445 LocVT = XLenVT; 2446 } 2447 } else 2448 Reg = State.AllocateReg(ArgGPRs); 2449 unsigned StackOffset = 2450 Reg ? 0 : State.AllocateStack(XLen / 8, Align(XLen / 8)); 2451 2452 // If we reach this point and PendingLocs is non-empty, we must be at the 2453 // end of a split argument that must be passed indirectly. 2454 if (!PendingLocs.empty()) { 2455 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 2456 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 2457 2458 for (auto &It : PendingLocs) { 2459 if (Reg) 2460 It.convertToReg(Reg); 2461 else 2462 It.convertToMem(StackOffset); 2463 State.addLoc(It); 2464 } 2465 PendingLocs.clear(); 2466 PendingArgFlags.clear(); 2467 return false; 2468 } 2469 2470 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 2471 (TLI.getSubtarget().hasStdExtV() && ValVT.isScalableVector())) && 2472 "Expected an XLenVT or scalable vector types at this stage"); 2473 2474 if (Reg) { 2475 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2476 return false; 2477 } 2478 2479 // When a floating-point value is passed on the stack, no bit-conversion is 2480 // needed. 2481 if (ValVT.isFloatingPoint()) { 2482 LocVT = ValVT; 2483 LocInfo = CCValAssign::Full; 2484 } 2485 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 2486 return false; 2487 } 2488 2489 template <typename ArgTy> 2490 static void preAssignMask(const ArgTy &Args, 2491 Optional<unsigned> &FirstMaskArgument, 2492 CCState &CCInfo) { 2493 unsigned NumArgs = Args.size(); 2494 for (unsigned I = 0; I != NumArgs; ++I) { 2495 MVT ArgVT = Args[I].VT; 2496 if (!ArgVT.isScalableVector() || 2497 ArgVT.getVectorElementType().SimpleTy != MVT::i1) 2498 continue; 2499 2500 FirstMaskArgument = I; 2501 break; 2502 } 2503 } 2504 2505 void RISCVTargetLowering::analyzeInputArgs( 2506 MachineFunction &MF, CCState &CCInfo, 2507 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const { 2508 unsigned NumArgs = Ins.size(); 2509 FunctionType *FType = MF.getFunction().getFunctionType(); 2510 2511 Optional<unsigned> FirstMaskArgument; 2512 if (Subtarget.hasStdExtV()) 2513 preAssignMask(Ins, FirstMaskArgument, CCInfo); 2514 2515 for (unsigned i = 0; i != NumArgs; ++i) { 2516 MVT ArgVT = Ins[i].VT; 2517 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 2518 2519 Type *ArgTy = nullptr; 2520 if (IsRet) 2521 ArgTy = FType->getReturnType(); 2522 else if (Ins[i].isOrigArg()) 2523 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 2524 2525 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 2526 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 2527 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 2528 FirstMaskArgument)) { 2529 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 2530 << EVT(ArgVT).getEVTString() << '\n'); 2531 llvm_unreachable(nullptr); 2532 } 2533 } 2534 } 2535 2536 void RISCVTargetLowering::analyzeOutputArgs( 2537 MachineFunction &MF, CCState &CCInfo, 2538 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 2539 CallLoweringInfo *CLI) const { 2540 unsigned NumArgs = Outs.size(); 2541 2542 Optional<unsigned> FirstMaskArgument; 2543 if (Subtarget.hasStdExtV()) 2544 preAssignMask(Outs, FirstMaskArgument, CCInfo); 2545 2546 for (unsigned i = 0; i != NumArgs; i++) { 2547 MVT ArgVT = Outs[i].VT; 2548 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 2549 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 2550 2551 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 2552 if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 2553 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 2554 FirstMaskArgument)) { 2555 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 2556 << EVT(ArgVT).getEVTString() << "\n"); 2557 llvm_unreachable(nullptr); 2558 } 2559 } 2560 } 2561 2562 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 2563 // values. 2564 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 2565 const CCValAssign &VA, const SDLoc &DL) { 2566 switch (VA.getLocInfo()) { 2567 default: 2568 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 2569 case CCValAssign::Full: 2570 break; 2571 case CCValAssign::BCvt: 2572 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 2573 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 2574 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 2575 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 2576 else 2577 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2578 break; 2579 } 2580 return Val; 2581 } 2582 2583 // The caller is responsible for loading the full value if the argument is 2584 // passed with CCValAssign::Indirect. 2585 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 2586 const CCValAssign &VA, const SDLoc &DL, 2587 const RISCVTargetLowering &TLI) { 2588 MachineFunction &MF = DAG.getMachineFunction(); 2589 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 2590 EVT LocVT = VA.getLocVT(); 2591 SDValue Val; 2592 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 2593 Register VReg = RegInfo.createVirtualRegister(RC); 2594 RegInfo.addLiveIn(VA.getLocReg(), VReg); 2595 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 2596 2597 if (VA.getLocInfo() == CCValAssign::Indirect) 2598 return Val; 2599 2600 return convertLocVTToValVT(DAG, Val, VA, DL); 2601 } 2602 2603 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 2604 const CCValAssign &VA, const SDLoc &DL) { 2605 EVT LocVT = VA.getLocVT(); 2606 2607 switch (VA.getLocInfo()) { 2608 default: 2609 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 2610 case CCValAssign::Full: 2611 break; 2612 case CCValAssign::BCvt: 2613 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 2614 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 2615 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 2616 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 2617 else 2618 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 2619 break; 2620 } 2621 return Val; 2622 } 2623 2624 // The caller is responsible for loading the full value if the argument is 2625 // passed with CCValAssign::Indirect. 2626 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 2627 const CCValAssign &VA, const SDLoc &DL) { 2628 MachineFunction &MF = DAG.getMachineFunction(); 2629 MachineFrameInfo &MFI = MF.getFrameInfo(); 2630 EVT LocVT = VA.getLocVT(); 2631 EVT ValVT = VA.getValVT(); 2632 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 2633 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8, 2634 VA.getLocMemOffset(), /*Immutable=*/true); 2635 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2636 SDValue Val; 2637 2638 ISD::LoadExtType ExtType; 2639 switch (VA.getLocInfo()) { 2640 default: 2641 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 2642 case CCValAssign::Full: 2643 case CCValAssign::Indirect: 2644 case CCValAssign::BCvt: 2645 ExtType = ISD::NON_EXTLOAD; 2646 break; 2647 } 2648 Val = DAG.getExtLoad( 2649 ExtType, DL, LocVT, Chain, FIN, 2650 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 2651 return Val; 2652 } 2653 2654 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 2655 const CCValAssign &VA, const SDLoc &DL) { 2656 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 2657 "Unexpected VA"); 2658 MachineFunction &MF = DAG.getMachineFunction(); 2659 MachineFrameInfo &MFI = MF.getFrameInfo(); 2660 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 2661 2662 if (VA.isMemLoc()) { 2663 // f64 is passed on the stack. 2664 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true); 2665 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 2666 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 2667 MachinePointerInfo::getFixedStack(MF, FI)); 2668 } 2669 2670 assert(VA.isRegLoc() && "Expected register VA assignment"); 2671 2672 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 2673 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 2674 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 2675 SDValue Hi; 2676 if (VA.getLocReg() == RISCV::X17) { 2677 // Second half of f64 is passed on the stack. 2678 int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true); 2679 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 2680 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 2681 MachinePointerInfo::getFixedStack(MF, FI)); 2682 } else { 2683 // Second half of f64 is passed in another GPR. 2684 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 2685 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 2686 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 2687 } 2688 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 2689 } 2690 2691 // FastCC has less than 1% performance improvement for some particular 2692 // benchmark. But theoretically, it may has benenfit for some cases. 2693 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT, 2694 CCValAssign::LocInfo LocInfo, 2695 ISD::ArgFlagsTy ArgFlags, CCState &State) { 2696 2697 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 2698 // X5 and X6 might be used for save-restore libcall. 2699 static const MCPhysReg GPRList[] = { 2700 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 2701 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 2702 RISCV::X29, RISCV::X30, RISCV::X31}; 2703 if (unsigned Reg = State.AllocateReg(GPRList)) { 2704 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2705 return false; 2706 } 2707 } 2708 2709 if (LocVT == MVT::f16) { 2710 static const MCPhysReg FPR16List[] = { 2711 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 2712 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 2713 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 2714 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 2715 if (unsigned Reg = State.AllocateReg(FPR16List)) { 2716 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2717 return false; 2718 } 2719 } 2720 2721 if (LocVT == MVT::f32) { 2722 static const MCPhysReg FPR32List[] = { 2723 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 2724 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 2725 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 2726 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 2727 if (unsigned Reg = State.AllocateReg(FPR32List)) { 2728 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2729 return false; 2730 } 2731 } 2732 2733 if (LocVT == MVT::f64) { 2734 static const MCPhysReg FPR64List[] = { 2735 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 2736 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 2737 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 2738 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 2739 if (unsigned Reg = State.AllocateReg(FPR64List)) { 2740 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2741 return false; 2742 } 2743 } 2744 2745 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 2746 unsigned Offset4 = State.AllocateStack(4, Align(4)); 2747 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 2748 return false; 2749 } 2750 2751 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 2752 unsigned Offset5 = State.AllocateStack(8, Align(8)); 2753 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 2754 return false; 2755 } 2756 2757 return true; // CC didn't match. 2758 } 2759 2760 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 2761 CCValAssign::LocInfo LocInfo, 2762 ISD::ArgFlagsTy ArgFlags, CCState &State) { 2763 2764 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 2765 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 2766 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 2767 static const MCPhysReg GPRList[] = { 2768 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 2769 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 2770 if (unsigned Reg = State.AllocateReg(GPRList)) { 2771 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2772 return false; 2773 } 2774 } 2775 2776 if (LocVT == MVT::f32) { 2777 // Pass in STG registers: F1, ..., F6 2778 // fs0 ... fs5 2779 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 2780 RISCV::F18_F, RISCV::F19_F, 2781 RISCV::F20_F, RISCV::F21_F}; 2782 if (unsigned Reg = State.AllocateReg(FPR32List)) { 2783 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2784 return false; 2785 } 2786 } 2787 2788 if (LocVT == MVT::f64) { 2789 // Pass in STG registers: D1, ..., D6 2790 // fs6 ... fs11 2791 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 2792 RISCV::F24_D, RISCV::F25_D, 2793 RISCV::F26_D, RISCV::F27_D}; 2794 if (unsigned Reg = State.AllocateReg(FPR64List)) { 2795 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 2796 return false; 2797 } 2798 } 2799 2800 report_fatal_error("No registers left in GHC calling convention"); 2801 return true; 2802 } 2803 2804 // Transform physical registers into virtual registers. 2805 SDValue RISCVTargetLowering::LowerFormalArguments( 2806 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 2807 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2808 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2809 2810 MachineFunction &MF = DAG.getMachineFunction(); 2811 2812 switch (CallConv) { 2813 default: 2814 report_fatal_error("Unsupported calling convention"); 2815 case CallingConv::C: 2816 case CallingConv::Fast: 2817 break; 2818 case CallingConv::GHC: 2819 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 2820 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 2821 report_fatal_error( 2822 "GHC calling convention requires the F and D instruction set extensions"); 2823 } 2824 2825 const Function &Func = MF.getFunction(); 2826 if (Func.hasFnAttribute("interrupt")) { 2827 if (!Func.arg_empty()) 2828 report_fatal_error( 2829 "Functions with the interrupt attribute cannot have arguments!"); 2830 2831 StringRef Kind = 2832 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 2833 2834 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 2835 report_fatal_error( 2836 "Function interrupt attribute argument not supported!"); 2837 } 2838 2839 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2840 MVT XLenVT = Subtarget.getXLenVT(); 2841 unsigned XLenInBytes = Subtarget.getXLen() / 8; 2842 // Used with vargs to acumulate store chains. 2843 std::vector<SDValue> OutChains; 2844 2845 // Assign locations to all of the incoming arguments. 2846 SmallVector<CCValAssign, 16> ArgLocs; 2847 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2848 2849 if (CallConv == CallingConv::Fast) 2850 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_FastCC); 2851 else if (CallConv == CallingConv::GHC) 2852 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 2853 else 2854 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false); 2855 2856 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2857 CCValAssign &VA = ArgLocs[i]; 2858 SDValue ArgValue; 2859 // Passing f64 on RV32D with a soft float ABI must be handled as a special 2860 // case. 2861 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 2862 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 2863 else if (VA.isRegLoc()) 2864 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 2865 else 2866 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 2867 2868 if (VA.getLocInfo() == CCValAssign::Indirect) { 2869 // If the original argument was split and passed by reference (e.g. i128 2870 // on RV32), we need to load all parts of it here (using the same 2871 // address). 2872 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 2873 MachinePointerInfo())); 2874 unsigned ArgIndex = Ins[i].OrigArgIndex; 2875 assert(Ins[i].PartOffset == 0); 2876 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 2877 CCValAssign &PartVA = ArgLocs[i + 1]; 2878 unsigned PartOffset = Ins[i + 1].PartOffset; 2879 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, 2880 DAG.getIntPtrConstant(PartOffset, DL)); 2881 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 2882 MachinePointerInfo())); 2883 ++i; 2884 } 2885 continue; 2886 } 2887 InVals.push_back(ArgValue); 2888 } 2889 2890 if (IsVarArg) { 2891 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 2892 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 2893 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 2894 MachineFrameInfo &MFI = MF.getFrameInfo(); 2895 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 2896 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 2897 2898 // Offset of the first variable argument from stack pointer, and size of 2899 // the vararg save area. For now, the varargs save area is either zero or 2900 // large enough to hold a0-a7. 2901 int VaArgOffset, VarArgsSaveSize; 2902 2903 // If all registers are allocated, then all varargs must be passed on the 2904 // stack and we don't need to save any argregs. 2905 if (ArgRegs.size() == Idx) { 2906 VaArgOffset = CCInfo.getNextStackOffset(); 2907 VarArgsSaveSize = 0; 2908 } else { 2909 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 2910 VaArgOffset = -VarArgsSaveSize; 2911 } 2912 2913 // Record the frame index of the first variable argument 2914 // which is a value necessary to VASTART. 2915 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 2916 RVFI->setVarArgsFrameIndex(FI); 2917 2918 // If saving an odd number of registers then create an extra stack slot to 2919 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 2920 // offsets to even-numbered registered remain 2*XLEN-aligned. 2921 if (Idx % 2) { 2922 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 2923 VarArgsSaveSize += XLenInBytes; 2924 } 2925 2926 // Copy the integer registers that may have been used for passing varargs 2927 // to the vararg save area. 2928 for (unsigned I = Idx; I < ArgRegs.size(); 2929 ++I, VaArgOffset += XLenInBytes) { 2930 const Register Reg = RegInfo.createVirtualRegister(RC); 2931 RegInfo.addLiveIn(ArgRegs[I], Reg); 2932 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 2933 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 2934 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2935 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 2936 MachinePointerInfo::getFixedStack(MF, FI)); 2937 cast<StoreSDNode>(Store.getNode()) 2938 ->getMemOperand() 2939 ->setValue((Value *)nullptr); 2940 OutChains.push_back(Store); 2941 } 2942 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 2943 } 2944 2945 // All stores are grouped in one node to allow the matching between 2946 // the size of Ins and InVals. This only happens for vararg functions. 2947 if (!OutChains.empty()) { 2948 OutChains.push_back(Chain); 2949 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 2950 } 2951 2952 return Chain; 2953 } 2954 2955 /// isEligibleForTailCallOptimization - Check whether the call is eligible 2956 /// for tail call optimization. 2957 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 2958 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 2959 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 2960 const SmallVector<CCValAssign, 16> &ArgLocs) const { 2961 2962 auto &Callee = CLI.Callee; 2963 auto CalleeCC = CLI.CallConv; 2964 auto &Outs = CLI.Outs; 2965 auto &Caller = MF.getFunction(); 2966 auto CallerCC = Caller.getCallingConv(); 2967 2968 // Exception-handling functions need a special set of instructions to 2969 // indicate a return to the hardware. Tail-calling another function would 2970 // probably break this. 2971 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 2972 // should be expanded as new function attributes are introduced. 2973 if (Caller.hasFnAttribute("interrupt")) 2974 return false; 2975 2976 // Do not tail call opt if the stack is used to pass parameters. 2977 if (CCInfo.getNextStackOffset() != 0) 2978 return false; 2979 2980 // Do not tail call opt if any parameters need to be passed indirectly. 2981 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 2982 // passed indirectly. So the address of the value will be passed in a 2983 // register, or if not available, then the address is put on the stack. In 2984 // order to pass indirectly, space on the stack often needs to be allocated 2985 // in order to store the value. In this case the CCInfo.getNextStackOffset() 2986 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 2987 // are passed CCValAssign::Indirect. 2988 for (auto &VA : ArgLocs) 2989 if (VA.getLocInfo() == CCValAssign::Indirect) 2990 return false; 2991 2992 // Do not tail call opt if either caller or callee uses struct return 2993 // semantics. 2994 auto IsCallerStructRet = Caller.hasStructRetAttr(); 2995 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 2996 if (IsCallerStructRet || IsCalleeStructRet) 2997 return false; 2998 2999 // Externally-defined functions with weak linkage should not be 3000 // tail-called. The behaviour of branch instructions in this situation (as 3001 // used for tail calls) is implementation-defined, so we cannot rely on the 3002 // linker replacing the tail call with a return. 3003 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3004 const GlobalValue *GV = G->getGlobal(); 3005 if (GV->hasExternalWeakLinkage()) 3006 return false; 3007 } 3008 3009 // The callee has to preserve all registers the caller needs to preserve. 3010 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 3011 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3012 if (CalleeCC != CallerCC) { 3013 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3014 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3015 return false; 3016 } 3017 3018 // Byval parameters hand the function a pointer directly into the stack area 3019 // we want to reuse during a tail call. Working around this *is* possible 3020 // but less efficient and uglier in LowerCall. 3021 for (auto &Arg : Outs) 3022 if (Arg.Flags.isByVal()) 3023 return false; 3024 3025 return true; 3026 } 3027 3028 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 3029 // and output parameter nodes. 3030 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 3031 SmallVectorImpl<SDValue> &InVals) const { 3032 SelectionDAG &DAG = CLI.DAG; 3033 SDLoc &DL = CLI.DL; 3034 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 3035 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 3036 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 3037 SDValue Chain = CLI.Chain; 3038 SDValue Callee = CLI.Callee; 3039 bool &IsTailCall = CLI.IsTailCall; 3040 CallingConv::ID CallConv = CLI.CallConv; 3041 bool IsVarArg = CLI.IsVarArg; 3042 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3043 MVT XLenVT = Subtarget.getXLenVT(); 3044 3045 MachineFunction &MF = DAG.getMachineFunction(); 3046 3047 // Analyze the operands of the call, assigning locations to each operand. 3048 SmallVector<CCValAssign, 16> ArgLocs; 3049 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3050 3051 if (CallConv == CallingConv::Fast) 3052 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC); 3053 else if (CallConv == CallingConv::GHC) 3054 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 3055 else 3056 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI); 3057 3058 // Check if it's really possible to do a tail call. 3059 if (IsTailCall) 3060 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 3061 3062 if (IsTailCall) 3063 ++NumTailCalls; 3064 else if (CLI.CB && CLI.CB->isMustTailCall()) 3065 report_fatal_error("failed to perform tail call elimination on a call " 3066 "site marked musttail"); 3067 3068 // Get a count of how many bytes are to be pushed on the stack. 3069 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 3070 3071 // Create local copies for byval args 3072 SmallVector<SDValue, 8> ByValArgs; 3073 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 3074 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3075 if (!Flags.isByVal()) 3076 continue; 3077 3078 SDValue Arg = OutVals[i]; 3079 unsigned Size = Flags.getByValSize(); 3080 Align Alignment = Flags.getNonZeroByValAlign(); 3081 3082 int FI = 3083 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 3084 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3085 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 3086 3087 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 3088 /*IsVolatile=*/false, 3089 /*AlwaysInline=*/false, IsTailCall, 3090 MachinePointerInfo(), MachinePointerInfo()); 3091 ByValArgs.push_back(FIPtr); 3092 } 3093 3094 if (!IsTailCall) 3095 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 3096 3097 // Copy argument values to their designated locations. 3098 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 3099 SmallVector<SDValue, 8> MemOpChains; 3100 SDValue StackPtr; 3101 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 3102 CCValAssign &VA = ArgLocs[i]; 3103 SDValue ArgValue = OutVals[i]; 3104 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3105 3106 // Handle passing f64 on RV32D with a soft float ABI as a special case. 3107 bool IsF64OnRV32DSoftABI = 3108 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 3109 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 3110 SDValue SplitF64 = DAG.getNode( 3111 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 3112 SDValue Lo = SplitF64.getValue(0); 3113 SDValue Hi = SplitF64.getValue(1); 3114 3115 Register RegLo = VA.getLocReg(); 3116 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 3117 3118 if (RegLo == RISCV::X17) { 3119 // Second half of f64 is passed on the stack. 3120 // Work out the address of the stack slot. 3121 if (!StackPtr.getNode()) 3122 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 3123 // Emit the store. 3124 MemOpChains.push_back( 3125 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 3126 } else { 3127 // Second half of f64 is passed in another GPR. 3128 assert(RegLo < RISCV::X31 && "Invalid register pair"); 3129 Register RegHigh = RegLo + 1; 3130 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 3131 } 3132 continue; 3133 } 3134 3135 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 3136 // as any other MemLoc. 3137 3138 // Promote the value if needed. 3139 // For now, only handle fully promoted and indirect arguments. 3140 if (VA.getLocInfo() == CCValAssign::Indirect) { 3141 // Store the argument in a stack slot and pass its address. 3142 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT); 3143 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 3144 MemOpChains.push_back( 3145 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 3146 MachinePointerInfo::getFixedStack(MF, FI))); 3147 // If the original argument was split (e.g. i128), we need 3148 // to store all parts of it here (and pass just one address). 3149 unsigned ArgIndex = Outs[i].OrigArgIndex; 3150 assert(Outs[i].PartOffset == 0); 3151 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 3152 SDValue PartValue = OutVals[i + 1]; 3153 unsigned PartOffset = Outs[i + 1].PartOffset; 3154 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, 3155 DAG.getIntPtrConstant(PartOffset, DL)); 3156 MemOpChains.push_back( 3157 DAG.getStore(Chain, DL, PartValue, Address, 3158 MachinePointerInfo::getFixedStack(MF, FI))); 3159 ++i; 3160 } 3161 ArgValue = SpillSlot; 3162 } else { 3163 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL); 3164 } 3165 3166 // Use local copy if it is a byval arg. 3167 if (Flags.isByVal()) 3168 ArgValue = ByValArgs[j++]; 3169 3170 if (VA.isRegLoc()) { 3171 // Queue up the argument copies and emit them at the end. 3172 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 3173 } else { 3174 assert(VA.isMemLoc() && "Argument not register or memory"); 3175 assert(!IsTailCall && "Tail call not allowed if stack is used " 3176 "for passing parameters"); 3177 3178 // Work out the address of the stack slot. 3179 if (!StackPtr.getNode()) 3180 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 3181 SDValue Address = 3182 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 3183 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 3184 3185 // Emit the store. 3186 MemOpChains.push_back( 3187 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 3188 } 3189 } 3190 3191 // Join the stores, which are independent of one another. 3192 if (!MemOpChains.empty()) 3193 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3194 3195 SDValue Glue; 3196 3197 // Build a sequence of copy-to-reg nodes, chained and glued together. 3198 for (auto &Reg : RegsToPass) { 3199 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 3200 Glue = Chain.getValue(1); 3201 } 3202 3203 // Validate that none of the argument registers have been marked as 3204 // reserved, if so report an error. Do the same for the return address if this 3205 // is not a tailcall. 3206 validateCCReservedRegs(RegsToPass, MF); 3207 if (!IsTailCall && 3208 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 3209 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 3210 MF.getFunction(), 3211 "Return address register required, but has been reserved."}); 3212 3213 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 3214 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 3215 // split it and then direct call can be matched by PseudoCALL. 3216 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 3217 const GlobalValue *GV = S->getGlobal(); 3218 3219 unsigned OpFlags = RISCVII::MO_CALL; 3220 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 3221 OpFlags = RISCVII::MO_PLT; 3222 3223 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 3224 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3225 unsigned OpFlags = RISCVII::MO_CALL; 3226 3227 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 3228 nullptr)) 3229 OpFlags = RISCVII::MO_PLT; 3230 3231 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 3232 } 3233 3234 // The first call operand is the chain and the second is the target address. 3235 SmallVector<SDValue, 8> Ops; 3236 Ops.push_back(Chain); 3237 Ops.push_back(Callee); 3238 3239 // Add argument registers to the end of the list so that they are 3240 // known live into the call. 3241 for (auto &Reg : RegsToPass) 3242 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 3243 3244 if (!IsTailCall) { 3245 // Add a register mask operand representing the call-preserved registers. 3246 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 3247 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3248 assert(Mask && "Missing call preserved mask for calling convention"); 3249 Ops.push_back(DAG.getRegisterMask(Mask)); 3250 } 3251 3252 // Glue the call to the argument copies, if any. 3253 if (Glue.getNode()) 3254 Ops.push_back(Glue); 3255 3256 // Emit the call. 3257 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3258 3259 if (IsTailCall) { 3260 MF.getFrameInfo().setHasTailCall(); 3261 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 3262 } 3263 3264 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 3265 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 3266 Glue = Chain.getValue(1); 3267 3268 // Mark the end of the call, which is glued to the call itself. 3269 Chain = DAG.getCALLSEQ_END(Chain, 3270 DAG.getConstant(NumBytes, DL, PtrVT, true), 3271 DAG.getConstant(0, DL, PtrVT, true), 3272 Glue, DL); 3273 Glue = Chain.getValue(1); 3274 3275 // Assign locations to each value returned by this call. 3276 SmallVector<CCValAssign, 16> RVLocs; 3277 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 3278 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true); 3279 3280 // Copy all of the result registers out of their specified physreg. 3281 for (auto &VA : RVLocs) { 3282 // Copy the value out 3283 SDValue RetValue = 3284 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 3285 // Glue the RetValue to the end of the call sequence 3286 Chain = RetValue.getValue(1); 3287 Glue = RetValue.getValue(2); 3288 3289 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 3290 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 3291 SDValue RetValue2 = 3292 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 3293 Chain = RetValue2.getValue(1); 3294 Glue = RetValue2.getValue(2); 3295 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 3296 RetValue2); 3297 } 3298 3299 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL); 3300 3301 InVals.push_back(RetValue); 3302 } 3303 3304 return Chain; 3305 } 3306 3307 bool RISCVTargetLowering::CanLowerReturn( 3308 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 3309 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3310 SmallVector<CCValAssign, 16> RVLocs; 3311 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 3312 3313 Optional<unsigned> FirstMaskArgument; 3314 if (Subtarget.hasStdExtV()) 3315 preAssignMask(Outs, FirstMaskArgument, CCInfo); 3316 3317 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 3318 MVT VT = Outs[i].VT; 3319 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3320 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 3321 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 3322 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 3323 *this, FirstMaskArgument)) 3324 return false; 3325 } 3326 return true; 3327 } 3328 3329 SDValue 3330 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3331 bool IsVarArg, 3332 const SmallVectorImpl<ISD::OutputArg> &Outs, 3333 const SmallVectorImpl<SDValue> &OutVals, 3334 const SDLoc &DL, SelectionDAG &DAG) const { 3335 const MachineFunction &MF = DAG.getMachineFunction(); 3336 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 3337 3338 // Stores the assignment of the return value to a location. 3339 SmallVector<CCValAssign, 16> RVLocs; 3340 3341 // Info about the registers and stack slot. 3342 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 3343 *DAG.getContext()); 3344 3345 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 3346 nullptr); 3347 3348 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 3349 report_fatal_error("GHC functions return void only"); 3350 3351 SDValue Glue; 3352 SmallVector<SDValue, 4> RetOps(1, Chain); 3353 3354 // Copy the result values into the output registers. 3355 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 3356 SDValue Val = OutVals[i]; 3357 CCValAssign &VA = RVLocs[i]; 3358 assert(VA.isRegLoc() && "Can only return in registers!"); 3359 3360 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 3361 // Handle returning f64 on RV32D with a soft float ABI. 3362 assert(VA.isRegLoc() && "Expected return via registers"); 3363 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 3364 DAG.getVTList(MVT::i32, MVT::i32), Val); 3365 SDValue Lo = SplitF64.getValue(0); 3366 SDValue Hi = SplitF64.getValue(1); 3367 Register RegLo = VA.getLocReg(); 3368 assert(RegLo < RISCV::X31 && "Invalid register pair"); 3369 Register RegHi = RegLo + 1; 3370 3371 if (STI.isRegisterReservedByUser(RegLo) || 3372 STI.isRegisterReservedByUser(RegHi)) 3373 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 3374 MF.getFunction(), 3375 "Return value register required, but has been reserved."}); 3376 3377 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 3378 Glue = Chain.getValue(1); 3379 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 3380 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 3381 Glue = Chain.getValue(1); 3382 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 3383 } else { 3384 // Handle a 'normal' return. 3385 Val = convertValVTToLocVT(DAG, Val, VA, DL); 3386 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 3387 3388 if (STI.isRegisterReservedByUser(VA.getLocReg())) 3389 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 3390 MF.getFunction(), 3391 "Return value register required, but has been reserved."}); 3392 3393 // Guarantee that all emitted copies are stuck together. 3394 Glue = Chain.getValue(1); 3395 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3396 } 3397 } 3398 3399 RetOps[0] = Chain; // Update chain. 3400 3401 // Add the glue node if we have it. 3402 if (Glue.getNode()) { 3403 RetOps.push_back(Glue); 3404 } 3405 3406 // Interrupt service routines use different return instructions. 3407 const Function &Func = DAG.getMachineFunction().getFunction(); 3408 if (Func.hasFnAttribute("interrupt")) { 3409 if (!Func.getReturnType()->isVoidTy()) 3410 report_fatal_error( 3411 "Functions with the interrupt attribute must have void return type!"); 3412 3413 MachineFunction &MF = DAG.getMachineFunction(); 3414 StringRef Kind = 3415 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 3416 3417 unsigned RetOpc; 3418 if (Kind == "user") 3419 RetOpc = RISCVISD::URET_FLAG; 3420 else if (Kind == "supervisor") 3421 RetOpc = RISCVISD::SRET_FLAG; 3422 else 3423 RetOpc = RISCVISD::MRET_FLAG; 3424 3425 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 3426 } 3427 3428 return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps); 3429 } 3430 3431 void RISCVTargetLowering::validateCCReservedRegs( 3432 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 3433 MachineFunction &MF) const { 3434 const Function &F = MF.getFunction(); 3435 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 3436 3437 if (llvm::any_of(Regs, [&STI](auto Reg) { 3438 return STI.isRegisterReservedByUser(Reg.first); 3439 })) 3440 F.getContext().diagnose(DiagnosticInfoUnsupported{ 3441 F, "Argument register required, but has been reserved."}); 3442 } 3443 3444 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3445 return CI->isTailCall(); 3446 } 3447 3448 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 3449 #define NODE_NAME_CASE(NODE) \ 3450 case RISCVISD::NODE: \ 3451 return "RISCVISD::" #NODE; 3452 // clang-format off 3453 switch ((RISCVISD::NodeType)Opcode) { 3454 case RISCVISD::FIRST_NUMBER: 3455 break; 3456 NODE_NAME_CASE(RET_FLAG) 3457 NODE_NAME_CASE(URET_FLAG) 3458 NODE_NAME_CASE(SRET_FLAG) 3459 NODE_NAME_CASE(MRET_FLAG) 3460 NODE_NAME_CASE(CALL) 3461 NODE_NAME_CASE(SELECT_CC) 3462 NODE_NAME_CASE(BuildPairF64) 3463 NODE_NAME_CASE(SplitF64) 3464 NODE_NAME_CASE(TAIL) 3465 NODE_NAME_CASE(SLLW) 3466 NODE_NAME_CASE(SRAW) 3467 NODE_NAME_CASE(SRLW) 3468 NODE_NAME_CASE(DIVW) 3469 NODE_NAME_CASE(DIVUW) 3470 NODE_NAME_CASE(REMUW) 3471 NODE_NAME_CASE(ROLW) 3472 NODE_NAME_CASE(RORW) 3473 NODE_NAME_CASE(FSLW) 3474 NODE_NAME_CASE(FSRW) 3475 NODE_NAME_CASE(FMV_H_X) 3476 NODE_NAME_CASE(FMV_X_ANYEXTH) 3477 NODE_NAME_CASE(FMV_W_X_RV64) 3478 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 3479 NODE_NAME_CASE(READ_CYCLE_WIDE) 3480 NODE_NAME_CASE(GREVI) 3481 NODE_NAME_CASE(GREVIW) 3482 NODE_NAME_CASE(GORCI) 3483 NODE_NAME_CASE(GORCIW) 3484 NODE_NAME_CASE(VMV_X_S) 3485 NODE_NAME_CASE(SPLAT_VECTOR_I64) 3486 } 3487 // clang-format on 3488 return nullptr; 3489 #undef NODE_NAME_CASE 3490 } 3491 3492 /// getConstraintType - Given a constraint letter, return the type of 3493 /// constraint it is for this target. 3494 RISCVTargetLowering::ConstraintType 3495 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 3496 if (Constraint.size() == 1) { 3497 switch (Constraint[0]) { 3498 default: 3499 break; 3500 case 'f': 3501 return C_RegisterClass; 3502 case 'I': 3503 case 'J': 3504 case 'K': 3505 return C_Immediate; 3506 case 'A': 3507 return C_Memory; 3508 } 3509 } 3510 return TargetLowering::getConstraintType(Constraint); 3511 } 3512 3513 std::pair<unsigned, const TargetRegisterClass *> 3514 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 3515 StringRef Constraint, 3516 MVT VT) const { 3517 // First, see if this is a constraint that directly corresponds to a 3518 // RISCV register class. 3519 if (Constraint.size() == 1) { 3520 switch (Constraint[0]) { 3521 case 'r': 3522 return std::make_pair(0U, &RISCV::GPRRegClass); 3523 case 'f': 3524 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 3525 return std::make_pair(0U, &RISCV::FPR16RegClass); 3526 if (Subtarget.hasStdExtF() && VT == MVT::f32) 3527 return std::make_pair(0U, &RISCV::FPR32RegClass); 3528 if (Subtarget.hasStdExtD() && VT == MVT::f64) 3529 return std::make_pair(0U, &RISCV::FPR64RegClass); 3530 break; 3531 default: 3532 break; 3533 } 3534 } 3535 3536 // Clang will correctly decode the usage of register name aliases into their 3537 // official names. However, other frontends like `rustc` do not. This allows 3538 // users of these frontends to use the ABI names for registers in LLVM-style 3539 // register constraints. 3540 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 3541 .Case("{zero}", RISCV::X0) 3542 .Case("{ra}", RISCV::X1) 3543 .Case("{sp}", RISCV::X2) 3544 .Case("{gp}", RISCV::X3) 3545 .Case("{tp}", RISCV::X4) 3546 .Case("{t0}", RISCV::X5) 3547 .Case("{t1}", RISCV::X6) 3548 .Case("{t2}", RISCV::X7) 3549 .Cases("{s0}", "{fp}", RISCV::X8) 3550 .Case("{s1}", RISCV::X9) 3551 .Case("{a0}", RISCV::X10) 3552 .Case("{a1}", RISCV::X11) 3553 .Case("{a2}", RISCV::X12) 3554 .Case("{a3}", RISCV::X13) 3555 .Case("{a4}", RISCV::X14) 3556 .Case("{a5}", RISCV::X15) 3557 .Case("{a6}", RISCV::X16) 3558 .Case("{a7}", RISCV::X17) 3559 .Case("{s2}", RISCV::X18) 3560 .Case("{s3}", RISCV::X19) 3561 .Case("{s4}", RISCV::X20) 3562 .Case("{s5}", RISCV::X21) 3563 .Case("{s6}", RISCV::X22) 3564 .Case("{s7}", RISCV::X23) 3565 .Case("{s8}", RISCV::X24) 3566 .Case("{s9}", RISCV::X25) 3567 .Case("{s10}", RISCV::X26) 3568 .Case("{s11}", RISCV::X27) 3569 .Case("{t3}", RISCV::X28) 3570 .Case("{t4}", RISCV::X29) 3571 .Case("{t5}", RISCV::X30) 3572 .Case("{t6}", RISCV::X31) 3573 .Default(RISCV::NoRegister); 3574 if (XRegFromAlias != RISCV::NoRegister) 3575 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 3576 3577 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 3578 // TableGen record rather than the AsmName to choose registers for InlineAsm 3579 // constraints, plus we want to match those names to the widest floating point 3580 // register type available, manually select floating point registers here. 3581 // 3582 // The second case is the ABI name of the register, so that frontends can also 3583 // use the ABI names in register constraint lists. 3584 if (Subtarget.hasStdExtF()) { 3585 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 3586 .Cases("{f0}", "{ft0}", RISCV::F0_F) 3587 .Cases("{f1}", "{ft1}", RISCV::F1_F) 3588 .Cases("{f2}", "{ft2}", RISCV::F2_F) 3589 .Cases("{f3}", "{ft3}", RISCV::F3_F) 3590 .Cases("{f4}", "{ft4}", RISCV::F4_F) 3591 .Cases("{f5}", "{ft5}", RISCV::F5_F) 3592 .Cases("{f6}", "{ft6}", RISCV::F6_F) 3593 .Cases("{f7}", "{ft7}", RISCV::F7_F) 3594 .Cases("{f8}", "{fs0}", RISCV::F8_F) 3595 .Cases("{f9}", "{fs1}", RISCV::F9_F) 3596 .Cases("{f10}", "{fa0}", RISCV::F10_F) 3597 .Cases("{f11}", "{fa1}", RISCV::F11_F) 3598 .Cases("{f12}", "{fa2}", RISCV::F12_F) 3599 .Cases("{f13}", "{fa3}", RISCV::F13_F) 3600 .Cases("{f14}", "{fa4}", RISCV::F14_F) 3601 .Cases("{f15}", "{fa5}", RISCV::F15_F) 3602 .Cases("{f16}", "{fa6}", RISCV::F16_F) 3603 .Cases("{f17}", "{fa7}", RISCV::F17_F) 3604 .Cases("{f18}", "{fs2}", RISCV::F18_F) 3605 .Cases("{f19}", "{fs3}", RISCV::F19_F) 3606 .Cases("{f20}", "{fs4}", RISCV::F20_F) 3607 .Cases("{f21}", "{fs5}", RISCV::F21_F) 3608 .Cases("{f22}", "{fs6}", RISCV::F22_F) 3609 .Cases("{f23}", "{fs7}", RISCV::F23_F) 3610 .Cases("{f24}", "{fs8}", RISCV::F24_F) 3611 .Cases("{f25}", "{fs9}", RISCV::F25_F) 3612 .Cases("{f26}", "{fs10}", RISCV::F26_F) 3613 .Cases("{f27}", "{fs11}", RISCV::F27_F) 3614 .Cases("{f28}", "{ft8}", RISCV::F28_F) 3615 .Cases("{f29}", "{ft9}", RISCV::F29_F) 3616 .Cases("{f30}", "{ft10}", RISCV::F30_F) 3617 .Cases("{f31}", "{ft11}", RISCV::F31_F) 3618 .Default(RISCV::NoRegister); 3619 if (FReg != RISCV::NoRegister) { 3620 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 3621 if (Subtarget.hasStdExtD()) { 3622 unsigned RegNo = FReg - RISCV::F0_F; 3623 unsigned DReg = RISCV::F0_D + RegNo; 3624 return std::make_pair(DReg, &RISCV::FPR64RegClass); 3625 } 3626 return std::make_pair(FReg, &RISCV::FPR32RegClass); 3627 } 3628 } 3629 3630 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 3631 } 3632 3633 unsigned 3634 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 3635 // Currently only support length 1 constraints. 3636 if (ConstraintCode.size() == 1) { 3637 switch (ConstraintCode[0]) { 3638 case 'A': 3639 return InlineAsm::Constraint_A; 3640 default: 3641 break; 3642 } 3643 } 3644 3645 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 3646 } 3647 3648 void RISCVTargetLowering::LowerAsmOperandForConstraint( 3649 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 3650 SelectionDAG &DAG) const { 3651 // Currently only support length 1 constraints. 3652 if (Constraint.length() == 1) { 3653 switch (Constraint[0]) { 3654 case 'I': 3655 // Validate & create a 12-bit signed immediate operand. 3656 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3657 uint64_t CVal = C->getSExtValue(); 3658 if (isInt<12>(CVal)) 3659 Ops.push_back( 3660 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 3661 } 3662 return; 3663 case 'J': 3664 // Validate & create an integer zero operand. 3665 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 3666 if (C->getZExtValue() == 0) 3667 Ops.push_back( 3668 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 3669 return; 3670 case 'K': 3671 // Validate & create a 5-bit unsigned immediate operand. 3672 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3673 uint64_t CVal = C->getZExtValue(); 3674 if (isUInt<5>(CVal)) 3675 Ops.push_back( 3676 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 3677 } 3678 return; 3679 default: 3680 break; 3681 } 3682 } 3683 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 3684 } 3685 3686 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 3687 Instruction *Inst, 3688 AtomicOrdering Ord) const { 3689 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 3690 return Builder.CreateFence(Ord); 3691 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 3692 return Builder.CreateFence(AtomicOrdering::Release); 3693 return nullptr; 3694 } 3695 3696 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 3697 Instruction *Inst, 3698 AtomicOrdering Ord) const { 3699 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 3700 return Builder.CreateFence(AtomicOrdering::Acquire); 3701 return nullptr; 3702 } 3703 3704 TargetLowering::AtomicExpansionKind 3705 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 3706 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 3707 // point operations can't be used in an lr/sc sequence without breaking the 3708 // forward-progress guarantee. 3709 if (AI->isFloatingPointOperation()) 3710 return AtomicExpansionKind::CmpXChg; 3711 3712 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 3713 if (Size == 8 || Size == 16) 3714 return AtomicExpansionKind::MaskedIntrinsic; 3715 return AtomicExpansionKind::None; 3716 } 3717 3718 static Intrinsic::ID 3719 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 3720 if (XLen == 32) { 3721 switch (BinOp) { 3722 default: 3723 llvm_unreachable("Unexpected AtomicRMW BinOp"); 3724 case AtomicRMWInst::Xchg: 3725 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 3726 case AtomicRMWInst::Add: 3727 return Intrinsic::riscv_masked_atomicrmw_add_i32; 3728 case AtomicRMWInst::Sub: 3729 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 3730 case AtomicRMWInst::Nand: 3731 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 3732 case AtomicRMWInst::Max: 3733 return Intrinsic::riscv_masked_atomicrmw_max_i32; 3734 case AtomicRMWInst::Min: 3735 return Intrinsic::riscv_masked_atomicrmw_min_i32; 3736 case AtomicRMWInst::UMax: 3737 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 3738 case AtomicRMWInst::UMin: 3739 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 3740 } 3741 } 3742 3743 if (XLen == 64) { 3744 switch (BinOp) { 3745 default: 3746 llvm_unreachable("Unexpected AtomicRMW BinOp"); 3747 case AtomicRMWInst::Xchg: 3748 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 3749 case AtomicRMWInst::Add: 3750 return Intrinsic::riscv_masked_atomicrmw_add_i64; 3751 case AtomicRMWInst::Sub: 3752 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 3753 case AtomicRMWInst::Nand: 3754 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 3755 case AtomicRMWInst::Max: 3756 return Intrinsic::riscv_masked_atomicrmw_max_i64; 3757 case AtomicRMWInst::Min: 3758 return Intrinsic::riscv_masked_atomicrmw_min_i64; 3759 case AtomicRMWInst::UMax: 3760 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 3761 case AtomicRMWInst::UMin: 3762 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 3763 } 3764 } 3765 3766 llvm_unreachable("Unexpected XLen\n"); 3767 } 3768 3769 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 3770 IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 3771 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 3772 unsigned XLen = Subtarget.getXLen(); 3773 Value *Ordering = 3774 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 3775 Type *Tys[] = {AlignedAddr->getType()}; 3776 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 3777 AI->getModule(), 3778 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 3779 3780 if (XLen == 64) { 3781 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 3782 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 3783 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 3784 } 3785 3786 Value *Result; 3787 3788 // Must pass the shift amount needed to sign extend the loaded value prior 3789 // to performing a signed comparison for min/max. ShiftAmt is the number of 3790 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 3791 // is the number of bits to left+right shift the value in order to 3792 // sign-extend. 3793 if (AI->getOperation() == AtomicRMWInst::Min || 3794 AI->getOperation() == AtomicRMWInst::Max) { 3795 const DataLayout &DL = AI->getModule()->getDataLayout(); 3796 unsigned ValWidth = 3797 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 3798 Value *SextShamt = 3799 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 3800 Result = Builder.CreateCall(LrwOpScwLoop, 3801 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 3802 } else { 3803 Result = 3804 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 3805 } 3806 3807 if (XLen == 64) 3808 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 3809 return Result; 3810 } 3811 3812 TargetLowering::AtomicExpansionKind 3813 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 3814 AtomicCmpXchgInst *CI) const { 3815 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 3816 if (Size == 8 || Size == 16) 3817 return AtomicExpansionKind::MaskedIntrinsic; 3818 return AtomicExpansionKind::None; 3819 } 3820 3821 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 3822 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 3823 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 3824 unsigned XLen = Subtarget.getXLen(); 3825 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 3826 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 3827 if (XLen == 64) { 3828 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 3829 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 3830 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 3831 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 3832 } 3833 Type *Tys[] = {AlignedAddr->getType()}; 3834 Function *MaskedCmpXchg = 3835 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 3836 Value *Result = Builder.CreateCall( 3837 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 3838 if (XLen == 64) 3839 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 3840 return Result; 3841 } 3842 3843 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3844 EVT VT) const { 3845 VT = VT.getScalarType(); 3846 3847 if (!VT.isSimple()) 3848 return false; 3849 3850 switch (VT.getSimpleVT().SimpleTy) { 3851 case MVT::f16: 3852 return Subtarget.hasStdExtZfh(); 3853 case MVT::f32: 3854 return Subtarget.hasStdExtF(); 3855 case MVT::f64: 3856 return Subtarget.hasStdExtD(); 3857 default: 3858 break; 3859 } 3860 3861 return false; 3862 } 3863 3864 Register RISCVTargetLowering::getExceptionPointerRegister( 3865 const Constant *PersonalityFn) const { 3866 return RISCV::X10; 3867 } 3868 3869 Register RISCVTargetLowering::getExceptionSelectorRegister( 3870 const Constant *PersonalityFn) const { 3871 return RISCV::X11; 3872 } 3873 3874 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 3875 // Return false to suppress the unnecessary extensions if the LibCall 3876 // arguments or return value is f32 type for LP64 ABI. 3877 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 3878 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 3879 return false; 3880 3881 return true; 3882 } 3883 3884 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 3885 SDValue C) const { 3886 // Check integral scalar types. 3887 if (VT.isScalarInteger()) { 3888 // Do not perform the transformation on riscv32 with the M extension. 3889 if (!Subtarget.is64Bit() && Subtarget.hasStdExtM()) 3890 return false; 3891 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 3892 if (ConstNode->getAPIntValue().getBitWidth() > 8 * sizeof(int64_t)) 3893 return false; 3894 int64_t Imm = ConstNode->getSExtValue(); 3895 if (isPowerOf2_64(Imm + 1) || isPowerOf2_64(Imm - 1) || 3896 isPowerOf2_64(1 - Imm) || isPowerOf2_64(-1 - Imm)) 3897 return true; 3898 } 3899 } 3900 3901 return false; 3902 } 3903 3904 #define GET_REGISTER_MATCHER 3905 #include "RISCVGenAsmMatcher.inc" 3906 3907 Register 3908 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 3909 const MachineFunction &MF) const { 3910 Register Reg = MatchRegisterAltName(RegName); 3911 if (Reg == RISCV::NoRegister) 3912 Reg = MatchRegisterName(RegName); 3913 if (Reg == RISCV::NoRegister) 3914 report_fatal_error( 3915 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 3916 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 3917 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 3918 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 3919 StringRef(RegName) + "\".")); 3920 return Reg; 3921 } 3922 3923 namespace llvm { 3924 namespace RISCVVIntrinsicsTable { 3925 3926 #define GET_RISCVVIntrinsicsTable_IMPL 3927 #include "RISCVGenSearchableTables.inc" 3928 3929 } // namespace RISCVVIntrinsicsTable 3930 } // namespace llvm 3931