1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 /// \file 11 /// \brief Custom DAG lowering for SI 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifdef _MSC_VER 16 // Provide M_PI. 17 #define _USE_MATH_DEFINES 18 #include <cmath> 19 #endif 20 21 #include "AMDGPU.h" 22 #include "AMDGPUIntrinsicInfo.h" 23 #include "AMDGPUSubtarget.h" 24 #include "SIISelLowering.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineFunctionInfo.h" 27 #include "SIRegisterInfo.h" 28 #include "llvm/ADT/BitVector.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/CodeGen/CallingConvLower.h" 31 #include "llvm/CodeGen/MachineInstrBuilder.h" 32 #include "llvm/CodeGen/MachineRegisterInfo.h" 33 #include "llvm/CodeGen/SelectionDAG.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/IR/DiagnosticInfo.h" 36 #include "llvm/IR/Function.h" 37 38 using namespace llvm; 39 40 // -amdgpu-fast-fdiv - Command line option to enable faster 2.5 ulp fdiv. 41 static cl::opt<bool> EnableAMDGPUFastFDIV( 42 "amdgpu-fast-fdiv", 43 cl::desc("Enable faster 2.5 ulp fdiv"), 44 cl::init(false)); 45 46 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 47 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 48 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 49 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 50 return AMDGPU::SGPR0 + Reg; 51 } 52 } 53 llvm_unreachable("Cannot allocate sgpr"); 54 } 55 56 SITargetLowering::SITargetLowering(const TargetMachine &TM, 57 const SISubtarget &STI) 58 : AMDGPUTargetLowering(TM, STI) { 59 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 60 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 61 62 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 63 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 64 65 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 66 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 67 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 68 69 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 70 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 71 72 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 73 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 74 75 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 76 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 77 78 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 79 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 80 81 computeRegisterProperties(STI.getRegisterInfo()); 82 83 // We need to custom lower vector stores from local memory 84 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 85 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 86 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 87 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 88 setOperationAction(ISD::LOAD, MVT::i1, Custom); 89 90 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 91 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 92 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 93 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 94 setOperationAction(ISD::STORE, MVT::i1, Custom); 95 96 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 97 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 98 setOperationAction(ISD::FrameIndex, MVT::i32, Custom); 99 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 100 101 setOperationAction(ISD::SELECT, MVT::i1, Promote); 102 setOperationAction(ISD::SELECT, MVT::i64, Custom); 103 setOperationAction(ISD::SELECT, MVT::f64, Promote); 104 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 105 106 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 107 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 108 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 109 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 110 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 111 112 setOperationAction(ISD::SETCC, MVT::i1, Promote); 113 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 114 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 115 116 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 117 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 118 119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 125 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 126 127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 128 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 129 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 130 131 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 132 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 133 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 134 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 135 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 136 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 137 138 // We only support LOAD/STORE and vector manipulation ops for vectors 139 // with > 4 elements. 140 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) { 141 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 142 switch (Op) { 143 case ISD::LOAD: 144 case ISD::STORE: 145 case ISD::BUILD_VECTOR: 146 case ISD::BITCAST: 147 case ISD::EXTRACT_VECTOR_ELT: 148 case ISD::INSERT_VECTOR_ELT: 149 case ISD::INSERT_SUBVECTOR: 150 case ISD::EXTRACT_SUBVECTOR: 151 case ISD::SCALAR_TO_VECTOR: 152 break; 153 case ISD::CONCAT_VECTORS: 154 setOperationAction(Op, VT, Custom); 155 break; 156 default: 157 setOperationAction(Op, VT, Expand); 158 break; 159 } 160 } 161 } 162 163 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 164 // is expanded to avoid having two separate loops in case the index is a VGPR. 165 166 // Most operations are naturally 32-bit vector operations. We only support 167 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 168 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 169 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 170 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 171 172 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 173 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 174 175 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 176 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 177 178 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 179 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 180 } 181 182 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 183 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 184 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 185 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 186 187 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 188 // and output demarshalling 189 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 190 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 191 192 // We can't return success/failure, only the old value, 193 // let LLVM add the comparison 194 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 195 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 196 197 if (getSubtarget()->hasFlatAddressSpace()) { 198 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 199 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 200 } 201 202 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 203 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 204 205 // On SI this is s_memtime and s_memrealtime on VI. 206 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 207 setOperationAction(ISD::TRAP, MVT::Other, Custom); 208 209 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 210 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 211 212 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) { 213 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 214 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 215 setOperationAction(ISD::FRINT, MVT::f64, Legal); 216 } 217 218 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 219 220 setOperationAction(ISD::FSIN, MVT::f32, Custom); 221 setOperationAction(ISD::FCOS, MVT::f32, Custom); 222 setOperationAction(ISD::FDIV, MVT::f32, Custom); 223 setOperationAction(ISD::FDIV, MVT::f64, Custom); 224 225 setTargetDAGCombine(ISD::FADD); 226 setTargetDAGCombine(ISD::FSUB); 227 setTargetDAGCombine(ISD::FMINNUM); 228 setTargetDAGCombine(ISD::FMAXNUM); 229 setTargetDAGCombine(ISD::SMIN); 230 setTargetDAGCombine(ISD::SMAX); 231 setTargetDAGCombine(ISD::UMIN); 232 setTargetDAGCombine(ISD::UMAX); 233 setTargetDAGCombine(ISD::SETCC); 234 setTargetDAGCombine(ISD::AND); 235 setTargetDAGCombine(ISD::OR); 236 setTargetDAGCombine(ISD::UINT_TO_FP); 237 setTargetDAGCombine(ISD::FCANONICALIZE); 238 239 // All memory operations. Some folding on the pointer operand is done to help 240 // matching the constant offsets in the addressing modes. 241 setTargetDAGCombine(ISD::LOAD); 242 setTargetDAGCombine(ISD::STORE); 243 setTargetDAGCombine(ISD::ATOMIC_LOAD); 244 setTargetDAGCombine(ISD::ATOMIC_STORE); 245 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 246 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 247 setTargetDAGCombine(ISD::ATOMIC_SWAP); 248 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 249 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 250 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 251 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 252 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 253 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 254 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 255 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 256 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 257 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 258 259 setSchedulingPreference(Sched::RegPressure); 260 } 261 262 const SISubtarget *SITargetLowering::getSubtarget() const { 263 return static_cast<const SISubtarget *>(Subtarget); 264 } 265 266 //===----------------------------------------------------------------------===// 267 // TargetLowering queries 268 //===----------------------------------------------------------------------===// 269 270 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 271 const CallInst &CI, 272 unsigned IntrID) const { 273 switch (IntrID) { 274 case Intrinsic::amdgcn_atomic_inc: 275 case Intrinsic::amdgcn_atomic_dec: 276 Info.opc = ISD::INTRINSIC_W_CHAIN; 277 Info.memVT = MVT::getVT(CI.getType()); 278 Info.ptrVal = CI.getOperand(0); 279 Info.align = 0; 280 Info.vol = false; 281 Info.readMem = true; 282 Info.writeMem = true; 283 return true; 284 default: 285 return false; 286 } 287 } 288 289 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &, 290 EVT) const { 291 // SI has some legal vector types, but no legal vector operations. Say no 292 // shuffles are legal in order to prefer scalarizing some vector operations. 293 return false; 294 } 295 296 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 297 // Flat instructions do not have offsets, and only have the register 298 // address. 299 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1); 300 } 301 302 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 303 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 304 // additionally can do r + r + i with addr64. 32-bit has more addressing 305 // mode options. Depending on the resource constant, it can also do 306 // (i64 r0) + (i32 r1) * (i14 i). 307 // 308 // Private arrays end up using a scratch buffer most of the time, so also 309 // assume those use MUBUF instructions. Scratch loads / stores are currently 310 // implemented as mubuf instructions with offen bit set, so slightly 311 // different than the normal addr64. 312 if (!isUInt<12>(AM.BaseOffs)) 313 return false; 314 315 // FIXME: Since we can split immediate into soffset and immediate offset, 316 // would it make sense to allow any immediate? 317 318 switch (AM.Scale) { 319 case 0: // r + i or just i, depending on HasBaseReg. 320 return true; 321 case 1: 322 return true; // We have r + r or r + i. 323 case 2: 324 if (AM.HasBaseReg) { 325 // Reject 2 * r + r. 326 return false; 327 } 328 329 // Allow 2 * r as r + r 330 // Or 2 * r + i is allowed as r + r + i. 331 return true; 332 default: // Don't allow n * r 333 return false; 334 } 335 } 336 337 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 338 const AddrMode &AM, Type *Ty, 339 unsigned AS) const { 340 // No global is ever allowed as a base. 341 if (AM.BaseGV) 342 return false; 343 344 switch (AS) { 345 case AMDGPUAS::GLOBAL_ADDRESS: { 346 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 347 // Assume the we will use FLAT for all global memory accesses 348 // on VI. 349 // FIXME: This assumption is currently wrong. On VI we still use 350 // MUBUF instructions for the r + i addressing mode. As currently 351 // implemented, the MUBUF instructions only work on buffer < 4GB. 352 // It may be possible to support > 4GB buffers with MUBUF instructions, 353 // by setting the stride value in the resource descriptor which would 354 // increase the size limit to (stride * 4GB). However, this is risky, 355 // because it has never been validated. 356 return isLegalFlatAddressingMode(AM); 357 } 358 359 return isLegalMUBUFAddressingMode(AM); 360 } 361 case AMDGPUAS::CONSTANT_ADDRESS: { 362 // If the offset isn't a multiple of 4, it probably isn't going to be 363 // correctly aligned. 364 if (AM.BaseOffs % 4 != 0) 365 return isLegalMUBUFAddressingMode(AM); 366 367 // There are no SMRD extloads, so if we have to do a small type access we 368 // will use a MUBUF load. 369 // FIXME?: We also need to do this if unaligned, but we don't know the 370 // alignment here. 371 if (DL.getTypeStoreSize(Ty) < 4) 372 return isLegalMUBUFAddressingMode(AM); 373 374 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 375 // SMRD instructions have an 8-bit, dword offset on SI. 376 if (!isUInt<8>(AM.BaseOffs / 4)) 377 return false; 378 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) { 379 // On CI+, this can also be a 32-bit literal constant offset. If it fits 380 // in 8-bits, it can use a smaller encoding. 381 if (!isUInt<32>(AM.BaseOffs / 4)) 382 return false; 383 } else if (Subtarget->getGeneration() == SISubtarget::VOLCANIC_ISLANDS) { 384 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 385 if (!isUInt<20>(AM.BaseOffs)) 386 return false; 387 } else 388 llvm_unreachable("unhandled generation"); 389 390 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 391 return true; 392 393 if (AM.Scale == 1 && AM.HasBaseReg) 394 return true; 395 396 return false; 397 } 398 399 case AMDGPUAS::PRIVATE_ADDRESS: 400 return isLegalMUBUFAddressingMode(AM); 401 402 case AMDGPUAS::LOCAL_ADDRESS: 403 case AMDGPUAS::REGION_ADDRESS: { 404 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 405 // field. 406 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 407 // an 8-bit dword offset but we don't know the alignment here. 408 if (!isUInt<16>(AM.BaseOffs)) 409 return false; 410 411 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 412 return true; 413 414 if (AM.Scale == 1 && AM.HasBaseReg) 415 return true; 416 417 return false; 418 } 419 case AMDGPUAS::FLAT_ADDRESS: 420 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE: 421 // For an unknown address space, this usually means that this is for some 422 // reason being used for pure arithmetic, and not based on some addressing 423 // computation. We don't have instructions that compute pointers with any 424 // addressing modes, so treat them as having no offset like flat 425 // instructions. 426 return isLegalFlatAddressingMode(AM); 427 428 default: 429 llvm_unreachable("unhandled address space"); 430 } 431 } 432 433 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 434 unsigned AddrSpace, 435 unsigned Align, 436 bool *IsFast) const { 437 if (IsFast) 438 *IsFast = false; 439 440 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 441 // which isn't a simple VT. 442 if (!VT.isSimple() || VT == MVT::Other) 443 return false; 444 445 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 446 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 447 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 448 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 449 // with adjacent offsets. 450 bool AlignedBy4 = (Align % 4 == 0); 451 if (IsFast) 452 *IsFast = AlignedBy4; 453 454 return AlignedBy4; 455 } 456 457 if (Subtarget->hasUnalignedBufferAccess()) { 458 // If we have an uniform constant load, it still requires using a slow 459 // buffer instruction if unaligned. 460 if (IsFast) { 461 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) ? 462 (Align % 4 == 0) : true; 463 } 464 465 return true; 466 } 467 468 // Smaller than dword value must be aligned. 469 if (VT.bitsLT(MVT::i32)) 470 return false; 471 472 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 473 // byte-address are ignored, thus forcing Dword alignment. 474 // This applies to private, global, and constant memory. 475 if (IsFast) 476 *IsFast = true; 477 478 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 479 } 480 481 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 482 unsigned SrcAlign, bool IsMemset, 483 bool ZeroMemset, 484 bool MemcpyStrSrc, 485 MachineFunction &MF) const { 486 // FIXME: Should account for address space here. 487 488 // The default fallback uses the private pointer size as a guess for a type to 489 // use. Make sure we switch these to 64-bit accesses. 490 491 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 492 return MVT::v4i32; 493 494 if (Size >= 8 && DstAlign >= 4) 495 return MVT::v2i32; 496 497 // Use the default. 498 return MVT::Other; 499 } 500 501 static bool isFlatGlobalAddrSpace(unsigned AS) { 502 return AS == AMDGPUAS::GLOBAL_ADDRESS || 503 AS == AMDGPUAS::FLAT_ADDRESS || 504 AS == AMDGPUAS::CONSTANT_ADDRESS; 505 } 506 507 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 508 unsigned DestAS) const { 509 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 510 } 511 512 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 513 const MemSDNode *MemNode = cast<MemSDNode>(N); 514 const Value *Ptr = MemNode->getMemOperand()->getValue(); 515 516 // UndefValue means this is a load of a kernel input. These are uniform. 517 // Sometimes LDS instructions have constant pointers. 518 // If Ptr is null, then that means this mem operand contains a 519 // PseudoSourceValue like GOT. 520 if (!Ptr || isa<UndefValue>(Ptr) || isa<Argument>(Ptr) || 521 isa<Constant>(Ptr) || isa<GlobalValue>(Ptr)) 522 return true; 523 524 const Instruction *I = dyn_cast<Instruction>(Ptr); 525 return I && I->getMetadata("amdgpu.uniform"); 526 } 527 528 TargetLoweringBase::LegalizeTypeAction 529 SITargetLowering::getPreferredVectorAction(EVT VT) const { 530 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 531 return TypeSplitVector; 532 533 return TargetLoweringBase::getPreferredVectorAction(VT); 534 } 535 536 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 537 Type *Ty) const { 538 // FIXME: Could be smarter if called for vector constants. 539 return true; 540 } 541 542 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 543 544 // SimplifySetCC uses this function to determine whether or not it should 545 // create setcc with i1 operands. We don't have instructions for i1 setcc. 546 if (VT == MVT::i1 && Op == ISD::SETCC) 547 return false; 548 549 return TargetLowering::isTypeDesirableForOp(Op, VT); 550 } 551 552 SDValue SITargetLowering::LowerParameterPtr(SelectionDAG &DAG, 553 const SDLoc &SL, SDValue Chain, 554 unsigned Offset) const { 555 const DataLayout &DL = DAG.getDataLayout(); 556 MachineFunction &MF = DAG.getMachineFunction(); 557 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 558 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 559 560 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 561 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 562 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 563 MRI.getLiveInVirtReg(InputPtrReg), PtrVT); 564 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 565 DAG.getConstant(Offset, SL, PtrVT)); 566 } 567 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT, 568 const SDLoc &SL, SDValue Chain, 569 unsigned Offset, bool Signed) const { 570 const DataLayout &DL = DAG.getDataLayout(); 571 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 572 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 573 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 574 SDValue PtrOffset = DAG.getUNDEF(PtrVT); 575 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 576 577 unsigned Align = DL.getABITypeAlignment(Ty); 578 579 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 580 if (MemVT.isFloatingPoint()) 581 ExtTy = ISD::EXTLOAD; 582 583 SDValue Ptr = LowerParameterPtr(DAG, SL, Chain, Offset); 584 return DAG.getLoad(ISD::UNINDEXED, ExtTy, VT, SL, Chain, Ptr, PtrOffset, 585 PtrInfo, MemVT, Align, MachineMemOperand::MONonTemporal | 586 MachineMemOperand::MOInvariant); 587 } 588 589 SDValue SITargetLowering::LowerFormalArguments( 590 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 591 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 592 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 593 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 594 595 MachineFunction &MF = DAG.getMachineFunction(); 596 FunctionType *FType = MF.getFunction()->getFunctionType(); 597 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 598 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 599 600 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 601 const Function *Fn = MF.getFunction(); 602 DiagnosticInfoUnsupported NoGraphicsHSA( 603 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 604 DAG.getContext()->diagnose(NoGraphicsHSA); 605 return DAG.getEntryNode(); 606 } 607 608 // Create stack objects that are used for emitting debugger prologue if 609 // "amdgpu-debugger-emit-prologue" attribute was specified. 610 if (ST.debuggerEmitPrologue()) 611 createDebuggerPrologueStackObjects(MF); 612 613 SmallVector<ISD::InputArg, 16> Splits; 614 BitVector Skipped(Ins.size()); 615 616 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) { 617 const ISD::InputArg &Arg = Ins[i]; 618 619 // First check if it's a PS input addr 620 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 621 !Arg.Flags.isByVal() && PSInputNum <= 15) { 622 623 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 624 // We can safely skip PS inputs 625 Skipped.set(i); 626 ++PSInputNum; 627 continue; 628 } 629 630 Info->markPSInputAllocated(PSInputNum); 631 if (Arg.Used) 632 Info->PSInputEna |= 1 << PSInputNum; 633 634 ++PSInputNum; 635 } 636 637 if (AMDGPU::isShader(CallConv)) { 638 // Second split vertices into their elements 639 if (Arg.VT.isVector()) { 640 ISD::InputArg NewArg = Arg; 641 NewArg.Flags.setSplit(); 642 NewArg.VT = Arg.VT.getVectorElementType(); 643 644 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 645 // three or five element vertex only needs three or five registers, 646 // NOT four or eight. 647 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 648 unsigned NumElements = ParamType->getVectorNumElements(); 649 650 for (unsigned j = 0; j != NumElements; ++j) { 651 Splits.push_back(NewArg); 652 NewArg.PartOffset += NewArg.VT.getStoreSize(); 653 } 654 } else { 655 Splits.push_back(Arg); 656 } 657 } 658 } 659 660 SmallVector<CCValAssign, 16> ArgLocs; 661 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 662 *DAG.getContext()); 663 664 // At least one interpolation mode must be enabled or else the GPU will hang. 665 // 666 // Check PSInputAddr instead of PSInputEna. The idea is that if the user set 667 // PSInputAddr, the user wants to enable some bits after the compilation 668 // based on run-time states. Since we can't know what the final PSInputEna 669 // will look like, so we shouldn't do anything here and the user should take 670 // responsibility for the correct programming. 671 // 672 // Otherwise, the following restrictions apply: 673 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 674 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 675 // enabled too. 676 if (CallConv == CallingConv::AMDGPU_PS && 677 ((Info->getPSInputAddr() & 0x7F) == 0 || 678 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11)))) { 679 CCInfo.AllocateReg(AMDGPU::VGPR0); 680 CCInfo.AllocateReg(AMDGPU::VGPR1); 681 Info->markPSInputAllocated(0); 682 Info->PSInputEna |= 1; 683 } 684 685 if (!AMDGPU::isShader(CallConv)) { 686 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins, 687 Splits); 688 689 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 690 } else { 691 assert(!Info->hasPrivateSegmentBuffer() && !Info->hasDispatchPtr() && 692 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 693 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 694 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 695 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 696 !Info->hasWorkItemIDZ()); 697 } 698 699 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 700 if (Info->hasPrivateSegmentBuffer()) { 701 unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI); 702 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass); 703 CCInfo.AllocateReg(PrivateSegmentBufferReg); 704 } 705 706 if (Info->hasDispatchPtr()) { 707 unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI); 708 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass); 709 CCInfo.AllocateReg(DispatchPtrReg); 710 } 711 712 if (Info->hasQueuePtr()) { 713 unsigned QueuePtrReg = Info->addQueuePtr(*TRI); 714 MF.addLiveIn(QueuePtrReg, &AMDGPU::SReg_64RegClass); 715 CCInfo.AllocateReg(QueuePtrReg); 716 } 717 718 if (Info->hasKernargSegmentPtr()) { 719 unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI); 720 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass); 721 CCInfo.AllocateReg(InputPtrReg); 722 } 723 724 if (Info->hasDispatchID()) { 725 unsigned DispatchIDReg = Info->addDispatchID(*TRI); 726 MF.addLiveIn(DispatchIDReg, &AMDGPU::SReg_64RegClass); 727 CCInfo.AllocateReg(DispatchIDReg); 728 } 729 730 if (Info->hasFlatScratchInit()) { 731 unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI); 732 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SReg_64RegClass); 733 CCInfo.AllocateReg(FlatScratchInitReg); 734 } 735 736 AnalyzeFormalArguments(CCInfo, Splits); 737 738 SmallVector<SDValue, 16> Chains; 739 740 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 741 742 const ISD::InputArg &Arg = Ins[i]; 743 if (Skipped[i]) { 744 InVals.push_back(DAG.getUNDEF(Arg.VT)); 745 continue; 746 } 747 748 CCValAssign &VA = ArgLocs[ArgIdx++]; 749 MVT VT = VA.getLocVT(); 750 751 if (VA.isMemLoc()) { 752 VT = Ins[i].VT; 753 EVT MemVT = Splits[i].VT; 754 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() + 755 VA.getLocMemOffset(); 756 // The first 36 bytes of the input buffer contains information about 757 // thread group and global sizes. 758 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain, 759 Offset, Ins[i].Flags.isSExt()); 760 Chains.push_back(Arg.getValue(1)); 761 762 auto *ParamTy = 763 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 764 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 765 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 766 // On SI local pointers are just offsets into LDS, so they are always 767 // less than 16-bits. On CI and newer they could potentially be 768 // real pointers, so we can't guarantee their size. 769 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 770 DAG.getValueType(MVT::i16)); 771 } 772 773 InVals.push_back(Arg); 774 Info->setABIArgOffset(Offset + MemVT.getStoreSize()); 775 continue; 776 } 777 assert(VA.isRegLoc() && "Parameter must be in a register!"); 778 779 unsigned Reg = VA.getLocReg(); 780 781 if (VT == MVT::i64) { 782 // For now assume it is a pointer 783 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, 784 &AMDGPU::SReg_64RegClass); 785 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass); 786 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 787 InVals.push_back(Copy); 788 continue; 789 } 790 791 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 792 793 Reg = MF.addLiveIn(Reg, RC); 794 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 795 796 if (Arg.VT.isVector()) { 797 798 // Build a vector from the registers 799 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 800 unsigned NumElements = ParamType->getVectorNumElements(); 801 802 SmallVector<SDValue, 4> Regs; 803 Regs.push_back(Val); 804 for (unsigned j = 1; j != NumElements; ++j) { 805 Reg = ArgLocs[ArgIdx++].getLocReg(); 806 Reg = MF.addLiveIn(Reg, RC); 807 808 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 809 Regs.push_back(Copy); 810 } 811 812 // Fill up the missing vector elements 813 NumElements = Arg.VT.getVectorNumElements() - NumElements; 814 Regs.append(NumElements, DAG.getUNDEF(VT)); 815 816 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 817 continue; 818 } 819 820 InVals.push_back(Val); 821 } 822 823 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 824 // these from the dispatch pointer. 825 826 // Start adding system SGPRs. 827 if (Info->hasWorkGroupIDX()) { 828 unsigned Reg = Info->addWorkGroupIDX(); 829 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 830 CCInfo.AllocateReg(Reg); 831 } 832 833 if (Info->hasWorkGroupIDY()) { 834 unsigned Reg = Info->addWorkGroupIDY(); 835 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 836 CCInfo.AllocateReg(Reg); 837 } 838 839 if (Info->hasWorkGroupIDZ()) { 840 unsigned Reg = Info->addWorkGroupIDZ(); 841 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 842 CCInfo.AllocateReg(Reg); 843 } 844 845 if (Info->hasWorkGroupInfo()) { 846 unsigned Reg = Info->addWorkGroupInfo(); 847 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 848 CCInfo.AllocateReg(Reg); 849 } 850 851 if (Info->hasPrivateSegmentWaveByteOffset()) { 852 // Scratch wave offset passed in system SGPR. 853 unsigned PrivateSegmentWaveByteOffsetReg; 854 855 if (AMDGPU::isShader(CallConv)) { 856 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 857 Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 858 } else 859 PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset(); 860 861 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 862 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 863 } 864 865 // Now that we've figured out where the scratch register inputs are, see if 866 // should reserve the arguments and use them directly. 867 bool HasStackObjects = MF.getFrameInfo().hasStackObjects(); 868 // Record that we know we have non-spill stack objects so we don't need to 869 // check all stack objects later. 870 if (HasStackObjects) 871 Info->setHasNonSpillStackObjects(true); 872 873 if (ST.isAmdHsaOS()) { 874 // TODO: Assume we will spill without optimizations. 875 if (HasStackObjects) { 876 // If we have stack objects, we unquestionably need the private buffer 877 // resource. For the HSA ABI, this will be the first 4 user SGPR 878 // inputs. We can reserve those and use them directly. 879 880 unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue( 881 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER); 882 Info->setScratchRSrcReg(PrivateSegmentBufferReg); 883 884 unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue( 885 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 886 Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 887 } else { 888 unsigned ReservedBufferReg 889 = TRI->reservedPrivateSegmentBufferReg(MF); 890 unsigned ReservedOffsetReg 891 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 892 893 // We tentatively reserve the last registers (skipping the last two 894 // which may contain VCC). After register allocation, we'll replace 895 // these with the ones immediately after those which were really 896 // allocated. In the prologue copies will be inserted from the argument 897 // to these reserved registers. 898 Info->setScratchRSrcReg(ReservedBufferReg); 899 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 900 } 901 } else { 902 unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF); 903 904 // Without HSA, relocations are used for the scratch pointer and the 905 // buffer resource setup is always inserted in the prologue. Scratch wave 906 // offset is still in an input SGPR. 907 Info->setScratchRSrcReg(ReservedBufferReg); 908 909 if (HasStackObjects) { 910 unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue( 911 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 912 Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg); 913 } else { 914 unsigned ReservedOffsetReg 915 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 916 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 917 } 918 } 919 920 if (Info->hasWorkItemIDX()) { 921 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X); 922 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 923 CCInfo.AllocateReg(Reg); 924 } 925 926 if (Info->hasWorkItemIDY()) { 927 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y); 928 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 929 CCInfo.AllocateReg(Reg); 930 } 931 932 if (Info->hasWorkItemIDZ()) { 933 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z); 934 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 935 CCInfo.AllocateReg(Reg); 936 } 937 938 if (Chains.empty()) 939 return Chain; 940 941 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 942 } 943 944 SDValue 945 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 946 bool isVarArg, 947 const SmallVectorImpl<ISD::OutputArg> &Outs, 948 const SmallVectorImpl<SDValue> &OutVals, 949 const SDLoc &DL, SelectionDAG &DAG) const { 950 MachineFunction &MF = DAG.getMachineFunction(); 951 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 952 953 if (!AMDGPU::isShader(CallConv)) 954 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 955 OutVals, DL, DAG); 956 957 Info->setIfReturnsVoid(Outs.size() == 0); 958 959 SmallVector<ISD::OutputArg, 48> Splits; 960 SmallVector<SDValue, 48> SplitVals; 961 962 // Split vectors into their elements. 963 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 964 const ISD::OutputArg &Out = Outs[i]; 965 966 if (Out.VT.isVector()) { 967 MVT VT = Out.VT.getVectorElementType(); 968 ISD::OutputArg NewOut = Out; 969 NewOut.Flags.setSplit(); 970 NewOut.VT = VT; 971 972 // We want the original number of vector elements here, e.g. 973 // three or five, not four or eight. 974 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 975 976 for (unsigned j = 0; j != NumElements; ++j) { 977 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 978 DAG.getConstant(j, DL, MVT::i32)); 979 SplitVals.push_back(Elem); 980 Splits.push_back(NewOut); 981 NewOut.PartOffset += NewOut.VT.getStoreSize(); 982 } 983 } else { 984 SplitVals.push_back(OutVals[i]); 985 Splits.push_back(Out); 986 } 987 } 988 989 // CCValAssign - represent the assignment of the return value to a location. 990 SmallVector<CCValAssign, 48> RVLocs; 991 992 // CCState - Info about the registers and stack slots. 993 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 994 *DAG.getContext()); 995 996 // Analyze outgoing return values. 997 AnalyzeReturn(CCInfo, Splits); 998 999 SDValue Flag; 1000 SmallVector<SDValue, 48> RetOps; 1001 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1002 1003 // Copy the result values into the output registers. 1004 for (unsigned i = 0, realRVLocIdx = 0; 1005 i != RVLocs.size(); 1006 ++i, ++realRVLocIdx) { 1007 CCValAssign &VA = RVLocs[i]; 1008 assert(VA.isRegLoc() && "Can only return in registers!"); 1009 1010 SDValue Arg = SplitVals[realRVLocIdx]; 1011 1012 // Copied from other backends. 1013 switch (VA.getLocInfo()) { 1014 default: llvm_unreachable("Unknown loc info!"); 1015 case CCValAssign::Full: 1016 break; 1017 case CCValAssign::BCvt: 1018 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 1019 break; 1020 } 1021 1022 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 1023 Flag = Chain.getValue(1); 1024 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1025 } 1026 1027 // Update chain and glue. 1028 RetOps[0] = Chain; 1029 if (Flag.getNode()) 1030 RetOps.push_back(Flag); 1031 1032 unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN; 1033 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 1034 } 1035 1036 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 1037 SelectionDAG &DAG) const { 1038 unsigned Reg = StringSwitch<unsigned>(RegName) 1039 .Case("m0", AMDGPU::M0) 1040 .Case("exec", AMDGPU::EXEC) 1041 .Case("exec_lo", AMDGPU::EXEC_LO) 1042 .Case("exec_hi", AMDGPU::EXEC_HI) 1043 .Case("flat_scratch", AMDGPU::FLAT_SCR) 1044 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 1045 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 1046 .Default(AMDGPU::NoRegister); 1047 1048 if (Reg == AMDGPU::NoRegister) { 1049 report_fatal_error(Twine("invalid register name \"" 1050 + StringRef(RegName) + "\".")); 1051 1052 } 1053 1054 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1055 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 1056 report_fatal_error(Twine("invalid register \"" 1057 + StringRef(RegName) + "\" for subtarget.")); 1058 } 1059 1060 switch (Reg) { 1061 case AMDGPU::M0: 1062 case AMDGPU::EXEC_LO: 1063 case AMDGPU::EXEC_HI: 1064 case AMDGPU::FLAT_SCR_LO: 1065 case AMDGPU::FLAT_SCR_HI: 1066 if (VT.getSizeInBits() == 32) 1067 return Reg; 1068 break; 1069 case AMDGPU::EXEC: 1070 case AMDGPU::FLAT_SCR: 1071 if (VT.getSizeInBits() == 64) 1072 return Reg; 1073 break; 1074 default: 1075 llvm_unreachable("missing register type checking"); 1076 } 1077 1078 report_fatal_error(Twine("invalid type for register \"" 1079 + StringRef(RegName) + "\".")); 1080 } 1081 1082 // If kill is not the last instruction, split the block so kill is always a 1083 // proper terminator. 1084 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 1085 MachineBasicBlock *BB) const { 1086 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1087 1088 MachineBasicBlock::iterator SplitPoint(&MI); 1089 ++SplitPoint; 1090 1091 if (SplitPoint == BB->end()) { 1092 // Don't bother with a new block. 1093 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 1094 return BB; 1095 } 1096 1097 MachineFunction *MF = BB->getParent(); 1098 MachineBasicBlock *SplitBB 1099 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 1100 1101 MF->insert(++MachineFunction::iterator(BB), SplitBB); 1102 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 1103 1104 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 1105 BB->addSuccessor(SplitBB); 1106 1107 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 1108 return SplitBB; 1109 } 1110 1111 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 1112 // wavefront. If the value is uniform and just happens to be in a VGPR, this 1113 // will only do one iteration. In the worst case, this will loop 64 times. 1114 // 1115 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 1116 static void emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, 1117 MachineRegisterInfo &MRI, 1118 MachineBasicBlock &OrigBB, 1119 MachineBasicBlock &LoopBB, 1120 const DebugLoc &DL, 1121 MachineInstr *MovRel, 1122 const MachineOperand &IdxReg, 1123 unsigned InitReg, 1124 unsigned ResultReg, 1125 unsigned PhiReg, 1126 unsigned InitSaveExecReg, 1127 int Offset) { 1128 MachineBasicBlock::iterator I = LoopBB.begin(); 1129 1130 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1131 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1132 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 1133 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1134 1135 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 1136 .addReg(InitReg) 1137 .addMBB(&OrigBB) 1138 .addReg(ResultReg) 1139 .addMBB(&LoopBB); 1140 1141 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 1142 .addReg(InitSaveExecReg) 1143 .addMBB(&OrigBB) 1144 .addReg(NewExec) 1145 .addMBB(&LoopBB); 1146 1147 // Read the next variant <- also loop target. 1148 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 1149 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 1150 1151 // Compare the just read M0 value to all possible Idx values. 1152 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 1153 .addReg(CurrentIdxReg) 1154 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 1155 1156 // Move index from VCC into M0 1157 if (Offset == 0) { 1158 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1159 .addReg(CurrentIdxReg, RegState::Kill); 1160 } else { 1161 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 1162 .addReg(CurrentIdxReg, RegState::Kill) 1163 .addImm(Offset); 1164 } 1165 1166 // Update EXEC, save the original EXEC value to VCC. 1167 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 1168 .addReg(CondReg, RegState::Kill); 1169 1170 MRI.setSimpleHint(NewExec, CondReg); 1171 1172 // Do the actual move. 1173 LoopBB.insert(I, MovRel); 1174 1175 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 1176 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 1177 .addReg(AMDGPU::EXEC) 1178 .addReg(NewExec); 1179 1180 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 1181 // s_cbranch_scc0? 1182 1183 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 1184 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 1185 .addMBB(&LoopBB); 1186 } 1187 1188 // This has slightly sub-optimal regalloc when the source vector is killed by 1189 // the read. The register allocator does not understand that the kill is 1190 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 1191 // subregister from it, using 1 more VGPR than necessary. This was saved when 1192 // this was expanded after register allocation. 1193 static MachineBasicBlock *loadM0FromVGPR(const SIInstrInfo *TII, 1194 MachineBasicBlock &MBB, 1195 MachineInstr &MI, 1196 MachineInstr *MovRel, 1197 unsigned InitResultReg, 1198 unsigned PhiReg, 1199 int Offset) { 1200 MachineFunction *MF = MBB.getParent(); 1201 MachineRegisterInfo &MRI = MF->getRegInfo(); 1202 const DebugLoc &DL = MI.getDebugLoc(); 1203 MachineBasicBlock::iterator I(&MI); 1204 1205 unsigned DstReg = MI.getOperand(0).getReg(); 1206 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1207 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1208 1209 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 1210 1211 // Save the EXEC mask 1212 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 1213 .addReg(AMDGPU::EXEC); 1214 1215 // To insert the loop we need to split the block. Move everything after this 1216 // point to a new block, and insert a new empty block between the two. 1217 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 1218 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 1219 MachineFunction::iterator MBBI(MBB); 1220 ++MBBI; 1221 1222 MF->insert(MBBI, LoopBB); 1223 MF->insert(MBBI, RemainderBB); 1224 1225 LoopBB->addSuccessor(LoopBB); 1226 LoopBB->addSuccessor(RemainderBB); 1227 1228 // Move the rest of the block into a new block. 1229 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 1230 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 1231 1232 MBB.addSuccessor(LoopBB); 1233 1234 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1235 1236 emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, MovRel, *Idx, 1237 InitResultReg, DstReg, PhiReg, TmpExec, Offset); 1238 1239 MachineBasicBlock::iterator First = RemainderBB->begin(); 1240 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 1241 .addReg(SaveExec); 1242 1243 MI.eraseFromParent(); 1244 1245 return RemainderBB; 1246 } 1247 1248 // Returns subreg index, offset 1249 static std::pair<unsigned, int> 1250 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 1251 const TargetRegisterClass *SuperRC, 1252 unsigned VecReg, 1253 int Offset) { 1254 int NumElts = SuperRC->getSize() / 4; 1255 1256 // Skip out of bounds offsets, or else we would end up using an undefined 1257 // register. 1258 if (Offset >= NumElts || Offset < 0) 1259 return std::make_pair(AMDGPU::sub0, Offset); 1260 1261 return std::make_pair(AMDGPU::sub0 + Offset, 0); 1262 } 1263 1264 // Return true if the index is an SGPR and was set. 1265 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 1266 MachineRegisterInfo &MRI, 1267 MachineInstr &MI, 1268 int Offset) { 1269 MachineBasicBlock *MBB = MI.getParent(); 1270 const DebugLoc &DL = MI.getDebugLoc(); 1271 MachineBasicBlock::iterator I(&MI); 1272 1273 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1274 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 1275 1276 assert(Idx->getReg() != AMDGPU::NoRegister); 1277 1278 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 1279 return false; 1280 1281 if (Offset == 0) { 1282 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1283 .addOperand(*Idx); 1284 } else { 1285 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 1286 .addOperand(*Idx) 1287 .addImm(Offset); 1288 } 1289 1290 return true; 1291 } 1292 1293 // Control flow needs to be inserted if indexing with a VGPR. 1294 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 1295 MachineBasicBlock &MBB, 1296 const SIInstrInfo *TII) { 1297 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 1298 MachineFunction *MF = MBB.getParent(); 1299 MachineRegisterInfo &MRI = MF->getRegInfo(); 1300 1301 unsigned Dst = MI.getOperand(0).getReg(); 1302 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 1303 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 1304 1305 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 1306 1307 unsigned SubReg; 1308 std::tie(SubReg, Offset) 1309 = computeIndirectRegAndOffset(TRI, VecRC, SrcVec->getReg(), Offset); 1310 1311 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset)) { 1312 MachineBasicBlock::iterator I(&MI); 1313 const DebugLoc &DL = MI.getDebugLoc(); 1314 1315 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 1316 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) 1317 .addReg(SrcVec->getReg(), RegState::Implicit); 1318 MI.eraseFromParent(); 1319 1320 return &MBB; 1321 } 1322 1323 const DebugLoc &DL = MI.getDebugLoc(); 1324 MachineBasicBlock::iterator I(&MI); 1325 1326 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1327 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1328 1329 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 1330 1331 MachineInstr *MovRel = 1332 BuildMI(*MF, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 1333 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) 1334 .addReg(SrcVec->getReg(), RegState::Implicit); 1335 1336 return loadM0FromVGPR(TII, MBB, MI, MovRel, InitReg, PhiReg, Offset); 1337 } 1338 1339 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 1340 MachineBasicBlock &MBB, 1341 const SIInstrInfo *TII) { 1342 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 1343 MachineFunction *MF = MBB.getParent(); 1344 MachineRegisterInfo &MRI = MF->getRegInfo(); 1345 1346 unsigned Dst = MI.getOperand(0).getReg(); 1347 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 1348 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1349 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 1350 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 1351 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 1352 1353 // This can be an immediate, but will be folded later. 1354 assert(Val->getReg()); 1355 1356 unsigned SubReg; 1357 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 1358 SrcVec->getReg(), 1359 Offset); 1360 if (Idx->getReg() == AMDGPU::NoRegister) { 1361 MachineBasicBlock::iterator I(&MI); 1362 const DebugLoc &DL = MI.getDebugLoc(); 1363 1364 assert(Offset == 0); 1365 1366 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 1367 .addOperand(*SrcVec) 1368 .addOperand(*Val) 1369 .addImm(SubReg); 1370 1371 MI.eraseFromParent(); 1372 return &MBB; 1373 } 1374 1375 const MCInstrDesc &MovRelDesc = TII->get(AMDGPU::V_MOVRELD_B32_e32); 1376 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset)) { 1377 MachineBasicBlock::iterator I(&MI); 1378 const DebugLoc &DL = MI.getDebugLoc(); 1379 1380 MachineInstr *MovRel = 1381 BuildMI(MBB, I, DL, MovRelDesc) 1382 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 1383 .addOperand(*Val) 1384 .addReg(Dst, RegState::ImplicitDefine) 1385 .addReg(SrcVec->getReg(), RegState::Implicit); 1386 1387 const int ImpDefIdx = MovRelDesc.getNumOperands() + 1388 MovRelDesc.getNumImplicitUses(); 1389 const int ImpUseIdx = ImpDefIdx + 1; 1390 1391 MovRel->tieOperands(ImpDefIdx, ImpUseIdx); 1392 MI.eraseFromParent(); 1393 return &MBB; 1394 } 1395 1396 if (Val->isReg()) 1397 MRI.clearKillFlags(Val->getReg()); 1398 1399 const DebugLoc &DL = MI.getDebugLoc(); 1400 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 1401 1402 // vdst is not actually read and just provides the base register index. 1403 MachineInstr *MovRel = 1404 BuildMI(*MF, DL, MovRelDesc) 1405 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 1406 .addOperand(*Val) 1407 .addReg(Dst, RegState::ImplicitDefine) 1408 .addReg(PhiReg, RegState::Implicit); 1409 1410 const int ImpDefIdx = MovRelDesc.getNumOperands() + 1411 MovRelDesc.getNumImplicitUses(); 1412 const int ImpUseIdx = ImpDefIdx + 1; 1413 1414 MovRel->tieOperands(ImpDefIdx, ImpUseIdx); 1415 1416 return loadM0FromVGPR(TII, MBB, MI, MovRel, 1417 SrcVec->getReg(), PhiReg, Offset); 1418 } 1419 1420 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 1421 MachineInstr &MI, MachineBasicBlock *BB) const { 1422 switch (MI.getOpcode()) { 1423 case AMDGPU::SI_INIT_M0: { 1424 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1425 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 1426 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1427 .addOperand(MI.getOperand(0)); 1428 MI.eraseFromParent(); 1429 return BB; 1430 } 1431 case AMDGPU::GET_GROUPSTATICSIZE: { 1432 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1433 1434 MachineFunction *MF = BB->getParent(); 1435 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 1436 DebugLoc DL = MI.getDebugLoc(); 1437 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 1438 .addOperand(MI.getOperand(0)) 1439 .addImm(MFI->getLDSSize()); 1440 MI.eraseFromParent(); 1441 return BB; 1442 } 1443 case AMDGPU::SI_INDIRECT_SRC_V1: 1444 case AMDGPU::SI_INDIRECT_SRC_V2: 1445 case AMDGPU::SI_INDIRECT_SRC_V4: 1446 case AMDGPU::SI_INDIRECT_SRC_V8: 1447 case AMDGPU::SI_INDIRECT_SRC_V16: 1448 return emitIndirectSrc(MI, *BB, getSubtarget()->getInstrInfo()); 1449 case AMDGPU::SI_INDIRECT_DST_V1: 1450 case AMDGPU::SI_INDIRECT_DST_V2: 1451 case AMDGPU::SI_INDIRECT_DST_V4: 1452 case AMDGPU::SI_INDIRECT_DST_V8: 1453 case AMDGPU::SI_INDIRECT_DST_V16: 1454 return emitIndirectDst(MI, *BB, getSubtarget()->getInstrInfo()); 1455 case AMDGPU::SI_KILL: 1456 return splitKillBlock(MI, BB); 1457 default: 1458 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 1459 } 1460 } 1461 1462 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1463 // This currently forces unfolding various combinations of fsub into fma with 1464 // free fneg'd operands. As long as we have fast FMA (controlled by 1465 // isFMAFasterThanFMulAndFAdd), we should perform these. 1466 1467 // When fma is quarter rate, for f64 where add / sub are at best half rate, 1468 // most of these combines appear to be cycle neutral but save on instruction 1469 // count / code size. 1470 return true; 1471 } 1472 1473 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 1474 EVT VT) const { 1475 if (!VT.isVector()) { 1476 return MVT::i1; 1477 } 1478 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 1479 } 1480 1481 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const { 1482 return MVT::i32; 1483 } 1484 1485 // Answering this is somewhat tricky and depends on the specific device which 1486 // have different rates for fma or all f64 operations. 1487 // 1488 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 1489 // regardless of which device (although the number of cycles differs between 1490 // devices), so it is always profitable for f64. 1491 // 1492 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 1493 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 1494 // which we can always do even without fused FP ops since it returns the same 1495 // result as the separate operations and since it is always full 1496 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 1497 // however does not support denormals, so we do report fma as faster if we have 1498 // a fast fma device and require denormals. 1499 // 1500 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 1501 VT = VT.getScalarType(); 1502 1503 if (!VT.isSimple()) 1504 return false; 1505 1506 switch (VT.getSimpleVT().SimpleTy) { 1507 case MVT::f32: 1508 // This is as fast on some subtargets. However, we always have full rate f32 1509 // mad available which returns the same result as the separate operations 1510 // which we should prefer over fma. We can't use this if we want to support 1511 // denormals, so only report this in these cases. 1512 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 1513 case MVT::f64: 1514 return true; 1515 default: 1516 break; 1517 } 1518 1519 return false; 1520 } 1521 1522 //===----------------------------------------------------------------------===// 1523 // Custom DAG Lowering Operations 1524 //===----------------------------------------------------------------------===// 1525 1526 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 1527 switch (Op.getOpcode()) { 1528 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 1529 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG); 1530 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 1531 case ISD::LOAD: { 1532 SDValue Result = LowerLOAD(Op, DAG); 1533 assert((!Result.getNode() || 1534 Result.getNode()->getNumValues() == 2) && 1535 "Load should return a value and a chain"); 1536 return Result; 1537 } 1538 1539 case ISD::FSIN: 1540 case ISD::FCOS: 1541 return LowerTrig(Op, DAG); 1542 case ISD::SELECT: return LowerSELECT(Op, DAG); 1543 case ISD::FDIV: return LowerFDIV(Op, DAG); 1544 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 1545 case ISD::STORE: return LowerSTORE(Op, DAG); 1546 case ISD::GlobalAddress: { 1547 MachineFunction &MF = DAG.getMachineFunction(); 1548 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1549 return LowerGlobalAddress(MFI, Op, DAG); 1550 } 1551 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 1552 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 1553 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 1554 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 1555 case ISD::TRAP: return lowerTRAP(Op, DAG); 1556 } 1557 return SDValue(); 1558 } 1559 1560 /// \brief Helper function for LowerBRCOND 1561 static SDNode *findUser(SDValue Value, unsigned Opcode) { 1562 1563 SDNode *Parent = Value.getNode(); 1564 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 1565 I != E; ++I) { 1566 1567 if (I.getUse().get() != Value) 1568 continue; 1569 1570 if (I->getOpcode() == Opcode) 1571 return *I; 1572 } 1573 return nullptr; 1574 } 1575 1576 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const { 1577 1578 SDLoc SL(Op); 1579 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op); 1580 unsigned FrameIndex = FINode->getIndex(); 1581 1582 // A FrameIndex node represents a 32-bit offset into scratch memory. If the 1583 // high bit of a frame index offset were to be set, this would mean that it 1584 // represented an offset of ~2GB * 64 = ~128GB from the start of the scratch 1585 // buffer, with 64 being the number of threads per wave. 1586 // 1587 // The maximum private allocation for the entire GPU is 4G, and we are 1588 // concerned with the largest the index could ever be for an individual 1589 // workitem. This will occur with the minmum dispatch size. If a program 1590 // requires more, the dispatch size will be reduced. 1591 // 1592 // With this limit, we can mark the high bit of the FrameIndex node as known 1593 // zero, which is important, because it means in most situations we can prove 1594 // that values derived from FrameIndex nodes are non-negative. This enables us 1595 // to take advantage of more addressing modes when accessing scratch buffers, 1596 // since for scratch reads/writes, the register offset must always be 1597 // positive. 1598 1599 uint64_t MaxGPUAlloc = UINT64_C(4) * 1024 * 1024 * 1024; 1600 1601 // XXX - It is unclear if partial dispatch works. Assume it works at half wave 1602 // granularity. It is probably a full wave. 1603 uint64_t MinGranularity = 32; 1604 1605 unsigned KnownBits = Log2_64(MaxGPUAlloc / MinGranularity); 1606 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), KnownBits); 1607 1608 SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32); 1609 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI, 1610 DAG.getValueType(ExtVT)); 1611 } 1612 1613 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 1614 if (Intr->getOpcode() != ISD::INTRINSIC_W_CHAIN) 1615 return false; 1616 1617 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 1618 default: return false; 1619 case AMDGPUIntrinsic::amdgcn_if: 1620 case AMDGPUIntrinsic::amdgcn_else: 1621 case AMDGPUIntrinsic::amdgcn_break: 1622 case AMDGPUIntrinsic::amdgcn_if_break: 1623 case AMDGPUIntrinsic::amdgcn_else_break: 1624 case AMDGPUIntrinsic::amdgcn_loop: 1625 case AMDGPUIntrinsic::amdgcn_end_cf: 1626 return true; 1627 } 1628 } 1629 1630 void SITargetLowering::createDebuggerPrologueStackObjects( 1631 MachineFunction &MF) const { 1632 // Create stack objects that are used for emitting debugger prologue. 1633 // 1634 // Debugger prologue writes work group IDs and work item IDs to scratch memory 1635 // at fixed location in the following format: 1636 // offset 0: work group ID x 1637 // offset 4: work group ID y 1638 // offset 8: work group ID z 1639 // offset 16: work item ID x 1640 // offset 20: work item ID y 1641 // offset 24: work item ID z 1642 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1643 int ObjectIdx = 0; 1644 1645 // For each dimension: 1646 for (unsigned i = 0; i < 3; ++i) { 1647 // Create fixed stack object for work group ID. 1648 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 1649 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 1650 // Create fixed stack object for work item ID. 1651 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 1652 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 1653 } 1654 } 1655 1656 /// This transforms the control flow intrinsics to get the branch destination as 1657 /// last parameter, also switches branch target with BR if the need arise 1658 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 1659 SelectionDAG &DAG) const { 1660 1661 SDLoc DL(BRCOND); 1662 1663 SDNode *Intr = BRCOND.getOperand(1).getNode(); 1664 SDValue Target = BRCOND.getOperand(2); 1665 SDNode *BR = nullptr; 1666 SDNode *SetCC = nullptr; 1667 1668 if (Intr->getOpcode() == ISD::SETCC) { 1669 // As long as we negate the condition everything is fine 1670 SetCC = Intr; 1671 Intr = SetCC->getOperand(0).getNode(); 1672 1673 } else { 1674 // Get the target from BR if we don't negate the condition 1675 BR = findUser(BRCOND, ISD::BR); 1676 Target = BR->getOperand(1); 1677 } 1678 1679 if (!isCFIntrinsic(Intr)) { 1680 // This is a uniform branch so we don't need to legalize. 1681 return BRCOND; 1682 } 1683 1684 assert(!SetCC || 1685 (SetCC->getConstantOperandVal(1) == 1 && 1686 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 1687 ISD::SETNE)); 1688 1689 // Build the result and 1690 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 1691 1692 // operands of the new intrinsic call 1693 SmallVector<SDValue, 4> Ops; 1694 Ops.push_back(BRCOND.getOperand(0)); 1695 Ops.append(Intr->op_begin() + 1, Intr->op_end()); 1696 Ops.push_back(Target); 1697 1698 // build the new intrinsic call 1699 SDNode *Result = DAG.getNode( 1700 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL, 1701 DAG.getVTList(Res), Ops).getNode(); 1702 1703 if (BR) { 1704 // Give the branch instruction our target 1705 SDValue Ops[] = { 1706 BR->getOperand(0), 1707 BRCOND.getOperand(2) 1708 }; 1709 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 1710 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 1711 BR = NewBR.getNode(); 1712 } 1713 1714 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 1715 1716 // Copy the intrinsic results to registers 1717 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 1718 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 1719 if (!CopyToReg) 1720 continue; 1721 1722 Chain = DAG.getCopyToReg( 1723 Chain, DL, 1724 CopyToReg->getOperand(1), 1725 SDValue(Result, i - 1), 1726 SDValue()); 1727 1728 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 1729 } 1730 1731 // Remove the old intrinsic from the chain 1732 DAG.ReplaceAllUsesOfValueWith( 1733 SDValue(Intr, Intr->getNumValues() - 1), 1734 Intr->getOperand(0)); 1735 1736 return Chain; 1737 } 1738 1739 SDValue SITargetLowering::getSegmentAperture(unsigned AS, 1740 SelectionDAG &DAG) const { 1741 SDLoc SL; 1742 MachineFunction &MF = DAG.getMachineFunction(); 1743 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1744 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 1745 assert(UserSGPR != AMDGPU::NoRegister); 1746 1747 SDValue QueuePtr = CreateLiveInRegister( 1748 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 1749 1750 // Offset into amd_queue_t for group_segment_aperture_base_hi / 1751 // private_segment_aperture_base_hi. 1752 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 1753 1754 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr, 1755 DAG.getConstant(StructOffset, SL, MVT::i64)); 1756 1757 // TODO: Use custom target PseudoSourceValue. 1758 // TODO: We should use the value from the IR intrinsic call, but it might not 1759 // be available and how do we get it? 1760 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 1761 AMDGPUAS::CONSTANT_ADDRESS)); 1762 1763 MachinePointerInfo PtrInfo(V, StructOffset); 1764 return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, PtrInfo, 1765 MinAlign(64, StructOffset), 1766 MachineMemOperand::MOInvariant); 1767 } 1768 1769 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 1770 SelectionDAG &DAG) const { 1771 SDLoc SL(Op); 1772 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 1773 1774 SDValue Src = ASC->getOperand(0); 1775 1776 // FIXME: Really support non-0 null pointers. 1777 SDValue SegmentNullPtr = DAG.getConstant(-1, SL, MVT::i32); 1778 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 1779 1780 // flat -> local/private 1781 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 1782 if (ASC->getDestAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 1783 ASC->getDestAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 1784 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 1785 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 1786 1787 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 1788 NonNull, Ptr, SegmentNullPtr); 1789 } 1790 } 1791 1792 // local/private -> flat 1793 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 1794 if (ASC->getSrcAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 1795 ASC->getSrcAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 1796 SDValue NonNull 1797 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 1798 1799 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG); 1800 SDValue CvtPtr 1801 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 1802 1803 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 1804 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 1805 FlatNullPtr); 1806 } 1807 } 1808 1809 // global <-> flat are no-ops and never emitted. 1810 1811 const MachineFunction &MF = DAG.getMachineFunction(); 1812 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 1813 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 1814 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 1815 1816 return DAG.getUNDEF(ASC->getValueType(0)); 1817 } 1818 1819 static bool shouldEmitGOTReloc(const GlobalValue *GV, 1820 const TargetMachine &TM) { 1821 return GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS && 1822 !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 1823 } 1824 1825 bool 1826 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 1827 // We can fold offsets for anything that doesn't require a GOT relocation. 1828 return GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS && 1829 !shouldEmitGOTReloc(GA->getGlobal(), getTargetMachine()); 1830 } 1831 1832 static SDValue buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 1833 SDLoc DL, unsigned Offset, EVT PtrVT, 1834 unsigned GAFlags = SIInstrInfo::MO_NONE) { 1835 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 1836 // lowered to the following code sequence: 1837 // s_getpc_b64 s[0:1] 1838 // s_add_u32 s0, s0, $symbol 1839 // s_addc_u32 s1, s1, 0 1840 // 1841 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 1842 // a fixup or relocation is emitted to replace $symbol with a literal 1843 // constant, which is a pc-relative offset from the encoding of the $symbol 1844 // operand to the global variable. 1845 // 1846 // What we want here is an offset from the value returned by s_getpc 1847 // (which is the address of the s_add_u32 instruction) to the global 1848 // variable, but since the encoding of $symbol starts 4 bytes after the start 1849 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 1850 // small. This requires us to add 4 to the global variable offset in order to 1851 // compute the correct address. 1852 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 1853 GAFlags); 1854 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, GA); 1855 } 1856 1857 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 1858 SDValue Op, 1859 SelectionDAG &DAG) const { 1860 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 1861 1862 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS && 1863 GSD->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS) 1864 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 1865 1866 SDLoc DL(GSD); 1867 const GlobalValue *GV = GSD->getGlobal(); 1868 EVT PtrVT = Op.getValueType(); 1869 1870 if (!shouldEmitGOTReloc(GV, getTargetMachine())) 1871 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 1872 1873 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 1874 SIInstrInfo::MO_GOTPCREL); 1875 1876 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 1877 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 1878 const DataLayout &DataLayout = DAG.getDataLayout(); 1879 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 1880 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 1881 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1882 1883 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 1884 MachineMemOperand::MOInvariant); 1885 } 1886 1887 SDValue SITargetLowering::lowerTRAP(SDValue Op, 1888 SelectionDAG &DAG) const { 1889 const MachineFunction &MF = DAG.getMachineFunction(); 1890 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(), 1891 "trap handler not supported", 1892 Op.getDebugLoc(), 1893 DS_Warning); 1894 DAG.getContext()->diagnose(NoTrap); 1895 1896 // Emit s_endpgm. 1897 1898 // FIXME: This should really be selected to s_trap, but that requires 1899 // setting up the trap handler for it o do anything. 1900 return DAG.getNode(AMDGPUISD::ENDPGM, SDLoc(Op), MVT::Other, 1901 Op.getOperand(0)); 1902 } 1903 1904 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 1905 const SDLoc &DL, SDValue V) const { 1906 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 1907 // the destination register. 1908 // 1909 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 1910 // so we will end up with redundant moves to m0. 1911 // 1912 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 1913 1914 // A Null SDValue creates a glue result. 1915 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 1916 V, Chain); 1917 return SDValue(M0, 0); 1918 } 1919 1920 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 1921 SDValue Op, 1922 MVT VT, 1923 unsigned Offset) const { 1924 SDLoc SL(Op); 1925 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL, 1926 DAG.getEntryNode(), Offset, false); 1927 // The local size values will have the hi 16-bits as zero. 1928 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 1929 DAG.getValueType(VT)); 1930 } 1931 1932 static SDValue emitNonHSAIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) { 1933 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 1934 "non-hsa intrinsic with hsa target", 1935 DL.getDebugLoc()); 1936 DAG.getContext()->diagnose(BadIntrin); 1937 return DAG.getUNDEF(VT); 1938 } 1939 1940 static SDValue emitRemovedIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) { 1941 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 1942 "intrinsic not supported on subtarget", 1943 DL.getDebugLoc()); 1944 DAG.getContext()->diagnose(BadIntrin); 1945 return DAG.getUNDEF(VT); 1946 } 1947 1948 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 1949 SelectionDAG &DAG) const { 1950 MachineFunction &MF = DAG.getMachineFunction(); 1951 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 1952 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1953 1954 EVT VT = Op.getValueType(); 1955 SDLoc DL(Op); 1956 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1957 1958 // TODO: Should this propagate fast-math-flags? 1959 1960 switch (IntrinsicID) { 1961 case Intrinsic::amdgcn_dispatch_ptr: 1962 case Intrinsic::amdgcn_queue_ptr: { 1963 if (!Subtarget->isAmdHsaOS()) { 1964 DiagnosticInfoUnsupported BadIntrin( 1965 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 1966 DL.getDebugLoc()); 1967 DAG.getContext()->diagnose(BadIntrin); 1968 return DAG.getUNDEF(VT); 1969 } 1970 1971 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 1972 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR; 1973 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, 1974 TRI->getPreloadedValue(MF, Reg), VT); 1975 } 1976 case Intrinsic::amdgcn_implicitarg_ptr: { 1977 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT); 1978 return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset); 1979 } 1980 case Intrinsic::amdgcn_kernarg_segment_ptr: { 1981 unsigned Reg 1982 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 1983 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 1984 } 1985 case Intrinsic::amdgcn_dispatch_id: { 1986 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID); 1987 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 1988 } 1989 case Intrinsic::amdgcn_rcp: 1990 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 1991 case Intrinsic::amdgcn_rsq: 1992 case AMDGPUIntrinsic::AMDGPU_rsq: // Legacy name 1993 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 1994 case Intrinsic::amdgcn_rsq_legacy: { 1995 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 1996 return emitRemovedIntrinsicError(DAG, DL, VT); 1997 1998 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 1999 } 2000 case Intrinsic::amdgcn_rcp_legacy: { 2001 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 2002 return emitRemovedIntrinsicError(DAG, DL, VT); 2003 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 2004 } 2005 case Intrinsic::amdgcn_rsq_clamp: { 2006 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 2007 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 2008 2009 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 2010 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 2011 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 2012 2013 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 2014 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 2015 DAG.getConstantFP(Max, DL, VT)); 2016 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 2017 DAG.getConstantFP(Min, DL, VT)); 2018 } 2019 case Intrinsic::r600_read_ngroups_x: 2020 if (Subtarget->isAmdHsaOS()) 2021 return emitNonHSAIntrinsicError(DAG, DL, VT); 2022 2023 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2024 SI::KernelInputOffsets::NGROUPS_X, false); 2025 case Intrinsic::r600_read_ngroups_y: 2026 if (Subtarget->isAmdHsaOS()) 2027 return emitNonHSAIntrinsicError(DAG, DL, VT); 2028 2029 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2030 SI::KernelInputOffsets::NGROUPS_Y, false); 2031 case Intrinsic::r600_read_ngroups_z: 2032 if (Subtarget->isAmdHsaOS()) 2033 return emitNonHSAIntrinsicError(DAG, DL, VT); 2034 2035 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2036 SI::KernelInputOffsets::NGROUPS_Z, false); 2037 case Intrinsic::r600_read_global_size_x: 2038 if (Subtarget->isAmdHsaOS()) 2039 return emitNonHSAIntrinsicError(DAG, DL, VT); 2040 2041 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2042 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 2043 case Intrinsic::r600_read_global_size_y: 2044 if (Subtarget->isAmdHsaOS()) 2045 return emitNonHSAIntrinsicError(DAG, DL, VT); 2046 2047 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2048 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 2049 case Intrinsic::r600_read_global_size_z: 2050 if (Subtarget->isAmdHsaOS()) 2051 return emitNonHSAIntrinsicError(DAG, DL, VT); 2052 2053 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2054 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 2055 case Intrinsic::r600_read_local_size_x: 2056 if (Subtarget->isAmdHsaOS()) 2057 return emitNonHSAIntrinsicError(DAG, DL, VT); 2058 2059 return lowerImplicitZextParam(DAG, Op, MVT::i16, 2060 SI::KernelInputOffsets::LOCAL_SIZE_X); 2061 case Intrinsic::r600_read_local_size_y: 2062 if (Subtarget->isAmdHsaOS()) 2063 return emitNonHSAIntrinsicError(DAG, DL, VT); 2064 2065 return lowerImplicitZextParam(DAG, Op, MVT::i16, 2066 SI::KernelInputOffsets::LOCAL_SIZE_Y); 2067 case Intrinsic::r600_read_local_size_z: 2068 if (Subtarget->isAmdHsaOS()) 2069 return emitNonHSAIntrinsicError(DAG, DL, VT); 2070 2071 return lowerImplicitZextParam(DAG, Op, MVT::i16, 2072 SI::KernelInputOffsets::LOCAL_SIZE_Z); 2073 case Intrinsic::amdgcn_workgroup_id_x: 2074 case Intrinsic::r600_read_tgid_x: 2075 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 2076 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT); 2077 case Intrinsic::amdgcn_workgroup_id_y: 2078 case Intrinsic::r600_read_tgid_y: 2079 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 2080 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT); 2081 case Intrinsic::amdgcn_workgroup_id_z: 2082 case Intrinsic::r600_read_tgid_z: 2083 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 2084 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT); 2085 case Intrinsic::amdgcn_workitem_id_x: 2086 case Intrinsic::r600_read_tidig_x: 2087 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 2088 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT); 2089 case Intrinsic::amdgcn_workitem_id_y: 2090 case Intrinsic::r600_read_tidig_y: 2091 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 2092 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT); 2093 case Intrinsic::amdgcn_workitem_id_z: 2094 case Intrinsic::r600_read_tidig_z: 2095 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 2096 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT); 2097 case AMDGPUIntrinsic::SI_load_const: { 2098 SDValue Ops[] = { 2099 Op.getOperand(1), 2100 Op.getOperand(2) 2101 }; 2102 2103 MachineMemOperand *MMO = MF.getMachineMemOperand( 2104 MachinePointerInfo(), 2105 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant, 2106 VT.getStoreSize(), 4); 2107 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 2108 Op->getVTList(), Ops, VT, MMO); 2109 } 2110 case AMDGPUIntrinsic::amdgcn_fdiv_fast: { 2111 return lowerFDIV_FAST(Op, DAG); 2112 } 2113 case AMDGPUIntrinsic::SI_vs_load_input: 2114 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT, 2115 Op.getOperand(1), 2116 Op.getOperand(2), 2117 Op.getOperand(3)); 2118 2119 case AMDGPUIntrinsic::SI_fs_constant: { 2120 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3)); 2121 SDValue Glue = M0.getValue(1); 2122 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 2123 DAG.getConstant(2, DL, MVT::i32), // P0 2124 Op.getOperand(1), Op.getOperand(2), Glue); 2125 } 2126 case AMDGPUIntrinsic::SI_packf16: 2127 if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef()) 2128 return DAG.getUNDEF(MVT::i32); 2129 return Op; 2130 case AMDGPUIntrinsic::SI_fs_interp: { 2131 SDValue IJ = Op.getOperand(4); 2132 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ, 2133 DAG.getConstant(0, DL, MVT::i32)); 2134 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ, 2135 DAG.getConstant(1, DL, MVT::i32)); 2136 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3)); 2137 SDValue Glue = M0.getValue(1); 2138 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL, 2139 DAG.getVTList(MVT::f32, MVT::Glue), 2140 I, Op.getOperand(1), Op.getOperand(2), Glue); 2141 Glue = SDValue(P1.getNode(), 1); 2142 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J, 2143 Op.getOperand(1), Op.getOperand(2), Glue); 2144 } 2145 case Intrinsic::amdgcn_interp_p1: { 2146 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 2147 SDValue Glue = M0.getValue(1); 2148 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 2149 Op.getOperand(2), Op.getOperand(3), Glue); 2150 } 2151 case Intrinsic::amdgcn_interp_p2: { 2152 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 2153 SDValue Glue = SDValue(M0.getNode(), 1); 2154 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 2155 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 2156 Glue); 2157 } 2158 case Intrinsic::amdgcn_sin: 2159 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 2160 2161 case Intrinsic::amdgcn_cos: 2162 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 2163 2164 case Intrinsic::amdgcn_log_clamp: { 2165 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 2166 return SDValue(); 2167 2168 DiagnosticInfoUnsupported BadIntrin( 2169 *MF.getFunction(), "intrinsic not supported on subtarget", 2170 DL.getDebugLoc()); 2171 DAG.getContext()->diagnose(BadIntrin); 2172 return DAG.getUNDEF(VT); 2173 } 2174 case Intrinsic::amdgcn_ldexp: 2175 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 2176 Op.getOperand(1), Op.getOperand(2)); 2177 2178 case Intrinsic::amdgcn_fract: 2179 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 2180 2181 case Intrinsic::amdgcn_class: 2182 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 2183 Op.getOperand(1), Op.getOperand(2)); 2184 case Intrinsic::amdgcn_div_fmas: 2185 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 2186 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 2187 Op.getOperand(4)); 2188 2189 case Intrinsic::amdgcn_div_fixup: 2190 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 2191 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 2192 2193 case Intrinsic::amdgcn_trig_preop: 2194 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 2195 Op.getOperand(1), Op.getOperand(2)); 2196 case Intrinsic::amdgcn_div_scale: { 2197 // 3rd parameter required to be a constant. 2198 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 2199 if (!Param) 2200 return DAG.getUNDEF(VT); 2201 2202 // Translate to the operands expected by the machine instruction. The 2203 // first parameter must be the same as the first instruction. 2204 SDValue Numerator = Op.getOperand(1); 2205 SDValue Denominator = Op.getOperand(2); 2206 2207 // Note this order is opposite of the machine instruction's operations, 2208 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 2209 // intrinsic has the numerator as the first operand to match a normal 2210 // division operation. 2211 2212 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 2213 2214 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 2215 Denominator, Numerator); 2216 } 2217 case Intrinsic::amdgcn_icmp: { 2218 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 2219 int CondCode = CD->getSExtValue(); 2220 2221 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 2222 CondCode >= ICmpInst::Predicate::BAD_ICMP_PREDICATE) 2223 return DAG.getUNDEF(VT); 2224 2225 ICmpInst::Predicate IcInput = 2226 static_cast<ICmpInst::Predicate>(CondCode); 2227 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 2228 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 2229 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 2230 } 2231 case Intrinsic::amdgcn_fcmp: { 2232 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 2233 int CondCode = CD->getSExtValue(); 2234 2235 if (CondCode <= FCmpInst::Predicate::FCMP_FALSE || 2236 CondCode >= FCmpInst::Predicate::FCMP_TRUE) 2237 return DAG.getUNDEF(VT); 2238 2239 FCmpInst::Predicate IcInput = 2240 static_cast<FCmpInst::Predicate>(CondCode); 2241 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 2242 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 2243 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 2244 } 2245 case Intrinsic::amdgcn_fmul_legacy: 2246 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 2247 Op.getOperand(1), Op.getOperand(2)); 2248 case Intrinsic::amdgcn_sffbh: 2249 case AMDGPUIntrinsic::AMDGPU_flbit_i32: // Legacy name. 2250 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 2251 default: 2252 return AMDGPUTargetLowering::LowerOperation(Op, DAG); 2253 } 2254 } 2255 2256 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 2257 SelectionDAG &DAG) const { 2258 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2259 switch (IntrID) { 2260 case Intrinsic::amdgcn_atomic_inc: 2261 case Intrinsic::amdgcn_atomic_dec: { 2262 MemSDNode *M = cast<MemSDNode>(Op); 2263 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ? 2264 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC; 2265 SDValue Ops[] = { 2266 M->getOperand(0), // Chain 2267 M->getOperand(2), // Ptr 2268 M->getOperand(3) // Value 2269 }; 2270 2271 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 2272 M->getMemoryVT(), M->getMemOperand()); 2273 } 2274 default: 2275 return SDValue(); 2276 } 2277 } 2278 2279 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 2280 SelectionDAG &DAG) const { 2281 MachineFunction &MF = DAG.getMachineFunction(); 2282 SDLoc DL(Op); 2283 SDValue Chain = Op.getOperand(0); 2284 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2285 2286 switch (IntrinsicID) { 2287 case AMDGPUIntrinsic::SI_sendmsg: { 2288 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 2289 SDValue Glue = Chain.getValue(1); 2290 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain, 2291 Op.getOperand(2), Glue); 2292 } 2293 case AMDGPUIntrinsic::SI_tbuffer_store: { 2294 SDValue Ops[] = { 2295 Chain, 2296 Op.getOperand(2), 2297 Op.getOperand(3), 2298 Op.getOperand(4), 2299 Op.getOperand(5), 2300 Op.getOperand(6), 2301 Op.getOperand(7), 2302 Op.getOperand(8), 2303 Op.getOperand(9), 2304 Op.getOperand(10), 2305 Op.getOperand(11), 2306 Op.getOperand(12), 2307 Op.getOperand(13), 2308 Op.getOperand(14) 2309 }; 2310 2311 EVT VT = Op.getOperand(3).getValueType(); 2312 2313 MachineMemOperand *MMO = MF.getMachineMemOperand( 2314 MachinePointerInfo(), 2315 MachineMemOperand::MOStore, 2316 VT.getStoreSize(), 4); 2317 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 2318 Op->getVTList(), Ops, VT, MMO); 2319 } 2320 case AMDGPUIntrinsic::AMDGPU_kill: { 2321 SDValue Src = Op.getOperand(2); 2322 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 2323 if (!K->isNegative()) 2324 return Chain; 2325 2326 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 2327 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 2328 } 2329 2330 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 2331 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 2332 } 2333 default: 2334 return SDValue(); 2335 } 2336 } 2337 2338 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 2339 SDLoc DL(Op); 2340 LoadSDNode *Load = cast<LoadSDNode>(Op); 2341 ISD::LoadExtType ExtType = Load->getExtensionType(); 2342 EVT MemVT = Load->getMemoryVT(); 2343 2344 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 2345 assert(MemVT == MVT::i1 && "Only i1 non-extloads expected"); 2346 // FIXME: Copied from PPC 2347 // First, load into 32 bits, then truncate to 1 bit. 2348 2349 SDValue Chain = Load->getChain(); 2350 SDValue BasePtr = Load->getBasePtr(); 2351 MachineMemOperand *MMO = Load->getMemOperand(); 2352 2353 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 2354 BasePtr, MVT::i8, MMO); 2355 2356 SDValue Ops[] = { 2357 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 2358 NewLD.getValue(1) 2359 }; 2360 2361 return DAG.getMergeValues(Ops, DL); 2362 } 2363 2364 if (!MemVT.isVector()) 2365 return SDValue(); 2366 2367 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 2368 "Custom lowering for non-i32 vectors hasn't been implemented."); 2369 2370 unsigned AS = Load->getAddressSpace(); 2371 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 2372 AS, Load->getAlignment())) { 2373 SDValue Ops[2]; 2374 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 2375 return DAG.getMergeValues(Ops, DL); 2376 } 2377 2378 unsigned NumElements = MemVT.getVectorNumElements(); 2379 switch (AS) { 2380 case AMDGPUAS::CONSTANT_ADDRESS: 2381 if (isMemOpUniform(Load)) 2382 return SDValue(); 2383 // Non-uniform loads will be selected to MUBUF instructions, so they 2384 // have the same legalization requires ments as global and private 2385 // loads. 2386 // 2387 // Fall-through 2388 case AMDGPUAS::GLOBAL_ADDRESS: 2389 case AMDGPUAS::FLAT_ADDRESS: 2390 if (NumElements > 4) 2391 return SplitVectorLoad(Op, DAG); 2392 // v4 loads are supported for private and global memory. 2393 return SDValue(); 2394 case AMDGPUAS::PRIVATE_ADDRESS: { 2395 // Depending on the setting of the private_element_size field in the 2396 // resource descriptor, we can only make private accesses up to a certain 2397 // size. 2398 switch (Subtarget->getMaxPrivateElementSize()) { 2399 case 4: 2400 return scalarizeVectorLoad(Load, DAG); 2401 case 8: 2402 if (NumElements > 2) 2403 return SplitVectorLoad(Op, DAG); 2404 return SDValue(); 2405 case 16: 2406 // Same as global/flat 2407 if (NumElements > 4) 2408 return SplitVectorLoad(Op, DAG); 2409 return SDValue(); 2410 default: 2411 llvm_unreachable("unsupported private_element_size"); 2412 } 2413 } 2414 case AMDGPUAS::LOCAL_ADDRESS: { 2415 if (NumElements > 2) 2416 return SplitVectorLoad(Op, DAG); 2417 2418 if (NumElements == 2) 2419 return SDValue(); 2420 2421 // If properly aligned, if we split we might be able to use ds_read_b64. 2422 return SplitVectorLoad(Op, DAG); 2423 } 2424 default: 2425 return SDValue(); 2426 } 2427 } 2428 2429 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 2430 if (Op.getValueType() != MVT::i64) 2431 return SDValue(); 2432 2433 SDLoc DL(Op); 2434 SDValue Cond = Op.getOperand(0); 2435 2436 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 2437 SDValue One = DAG.getConstant(1, DL, MVT::i32); 2438 2439 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 2440 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 2441 2442 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 2443 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 2444 2445 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 2446 2447 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 2448 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 2449 2450 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 2451 2452 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 2453 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 2454 } 2455 2456 // Catch division cases where we can use shortcuts with rcp and rsq 2457 // instructions. 2458 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 2459 SelectionDAG &DAG) const { 2460 SDLoc SL(Op); 2461 SDValue LHS = Op.getOperand(0); 2462 SDValue RHS = Op.getOperand(1); 2463 EVT VT = Op.getValueType(); 2464 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath; 2465 2466 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 2467 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()))) { 2468 2469 if (CLHS->isExactlyValue(1.0)) { 2470 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 2471 // the CI documentation has a worst case error of 1 ulp. 2472 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 2473 // use it as long as we aren't trying to use denormals. 2474 2475 // 1.0 / sqrt(x) -> rsq(x) 2476 // 2477 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 2478 // error seems really high at 2^29 ULP. 2479 if (RHS.getOpcode() == ISD::FSQRT) 2480 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 2481 2482 // 1.0 / x -> rcp(x) 2483 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 2484 } 2485 2486 // Same as for 1.0, but expand the sign out of the constant. 2487 if (CLHS->isExactlyValue(-1.0)) { 2488 // -1.0 / x -> rcp (fneg x) 2489 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 2490 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 2491 } 2492 } 2493 } 2494 2495 const SDNodeFlags *Flags = Op->getFlags(); 2496 2497 if (Unsafe || Flags->hasAllowReciprocal()) { 2498 // Turn into multiply by the reciprocal. 2499 // x / y -> x * (1.0 / y) 2500 SDNodeFlags Flags; 2501 Flags.setUnsafeAlgebra(true); 2502 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 2503 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags); 2504 } 2505 2506 return SDValue(); 2507 } 2508 2509 // Faster 2.5 ULP division that does not support denormals. 2510 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 2511 SDLoc SL(Op); 2512 SDValue LHS = Op.getOperand(1); 2513 SDValue RHS = Op.getOperand(2); 2514 2515 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 2516 2517 const APFloat K0Val(BitsToFloat(0x6f800000)); 2518 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 2519 2520 const APFloat K1Val(BitsToFloat(0x2f800000)); 2521 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 2522 2523 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 2524 2525 EVT SetCCVT = 2526 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 2527 2528 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 2529 2530 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 2531 2532 // TODO: Should this propagate fast-math-flags? 2533 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 2534 2535 // rcp does not support denormals. 2536 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 2537 2538 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 2539 2540 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 2541 } 2542 2543 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 2544 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 2545 return FastLowered; 2546 2547 SDLoc SL(Op); 2548 SDValue LHS = Op.getOperand(0); 2549 SDValue RHS = Op.getOperand(1); 2550 2551 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 2552 2553 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 2554 2555 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, RHS, RHS, LHS); 2556 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, LHS, RHS, LHS); 2557 2558 // Denominator is scaled to not be denormal, so using rcp is ok. 2559 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, DenominatorScaled); 2560 2561 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, DenominatorScaled); 2562 2563 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, ApproxRcp, One); 2564 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, ApproxRcp); 2565 2566 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, NumeratorScaled, Fma1); 2567 2568 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, NumeratorScaled); 2569 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul); 2570 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, NumeratorScaled); 2571 2572 SDValue Scale = NumeratorScaled.getValue(1); 2573 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, Fma4, Fma1, Fma3, Scale); 2574 2575 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 2576 } 2577 2578 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 2579 if (DAG.getTarget().Options.UnsafeFPMath) 2580 return lowerFastUnsafeFDIV(Op, DAG); 2581 2582 SDLoc SL(Op); 2583 SDValue X = Op.getOperand(0); 2584 SDValue Y = Op.getOperand(1); 2585 2586 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 2587 2588 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 2589 2590 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 2591 2592 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 2593 2594 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 2595 2596 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 2597 2598 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 2599 2600 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 2601 2602 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 2603 2604 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 2605 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 2606 2607 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 2608 NegDivScale0, Mul, DivScale1); 2609 2610 SDValue Scale; 2611 2612 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 2613 // Workaround a hardware bug on SI where the condition output from div_scale 2614 // is not usable. 2615 2616 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 2617 2618 // Figure out if the scale to use for div_fmas. 2619 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 2620 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 2621 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 2622 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 2623 2624 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 2625 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 2626 2627 SDValue Scale0Hi 2628 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 2629 SDValue Scale1Hi 2630 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 2631 2632 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 2633 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 2634 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 2635 } else { 2636 Scale = DivScale1.getValue(1); 2637 } 2638 2639 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 2640 Fma4, Fma3, Mul, Scale); 2641 2642 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 2643 } 2644 2645 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 2646 EVT VT = Op.getValueType(); 2647 2648 if (VT == MVT::f32) 2649 return LowerFDIV32(Op, DAG); 2650 2651 if (VT == MVT::f64) 2652 return LowerFDIV64(Op, DAG); 2653 2654 llvm_unreachable("Unexpected type for fdiv"); 2655 } 2656 2657 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 2658 SDLoc DL(Op); 2659 StoreSDNode *Store = cast<StoreSDNode>(Op); 2660 EVT VT = Store->getMemoryVT(); 2661 2662 if (VT == MVT::i1) { 2663 return DAG.getTruncStore(Store->getChain(), DL, 2664 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 2665 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 2666 } 2667 2668 assert(VT.isVector() && 2669 Store->getValue().getValueType().getScalarType() == MVT::i32); 2670 2671 unsigned AS = Store->getAddressSpace(); 2672 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 2673 AS, Store->getAlignment())) { 2674 return expandUnalignedStore(Store, DAG); 2675 } 2676 2677 unsigned NumElements = VT.getVectorNumElements(); 2678 switch (AS) { 2679 case AMDGPUAS::GLOBAL_ADDRESS: 2680 case AMDGPUAS::FLAT_ADDRESS: 2681 if (NumElements > 4) 2682 return SplitVectorStore(Op, DAG); 2683 return SDValue(); 2684 case AMDGPUAS::PRIVATE_ADDRESS: { 2685 switch (Subtarget->getMaxPrivateElementSize()) { 2686 case 4: 2687 return scalarizeVectorStore(Store, DAG); 2688 case 8: 2689 if (NumElements > 2) 2690 return SplitVectorStore(Op, DAG); 2691 return SDValue(); 2692 case 16: 2693 if (NumElements > 4) 2694 return SplitVectorStore(Op, DAG); 2695 return SDValue(); 2696 default: 2697 llvm_unreachable("unsupported private_element_size"); 2698 } 2699 } 2700 case AMDGPUAS::LOCAL_ADDRESS: { 2701 if (NumElements > 2) 2702 return SplitVectorStore(Op, DAG); 2703 2704 if (NumElements == 2) 2705 return Op; 2706 2707 // If properly aligned, if we split we might be able to use ds_write_b64. 2708 return SplitVectorStore(Op, DAG); 2709 } 2710 default: 2711 llvm_unreachable("unhandled address space"); 2712 } 2713 } 2714 2715 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 2716 SDLoc DL(Op); 2717 EVT VT = Op.getValueType(); 2718 SDValue Arg = Op.getOperand(0); 2719 // TODO: Should this propagate fast-math-flags? 2720 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 2721 DAG.getNode(ISD::FMUL, DL, VT, Arg, 2722 DAG.getConstantFP(0.5/M_PI, DL, 2723 VT))); 2724 2725 switch (Op.getOpcode()) { 2726 case ISD::FCOS: 2727 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 2728 case ISD::FSIN: 2729 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 2730 default: 2731 llvm_unreachable("Wrong trig opcode"); 2732 } 2733 } 2734 2735 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 2736 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 2737 assert(AtomicNode->isCompareAndSwap()); 2738 unsigned AS = AtomicNode->getAddressSpace(); 2739 2740 // No custom lowering required for local address space 2741 if (!isFlatGlobalAddrSpace(AS)) 2742 return Op; 2743 2744 // Non-local address space requires custom lowering for atomic compare 2745 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 2746 SDLoc DL(Op); 2747 SDValue ChainIn = Op.getOperand(0); 2748 SDValue Addr = Op.getOperand(1); 2749 SDValue Old = Op.getOperand(2); 2750 SDValue New = Op.getOperand(3); 2751 EVT VT = Op.getValueType(); 2752 MVT SimpleVT = VT.getSimpleVT(); 2753 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 2754 2755 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 2756 SDValue Ops[] = { ChainIn, Addr, NewOld }; 2757 2758 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 2759 Ops, VT, AtomicNode->getMemOperand()); 2760 } 2761 2762 //===----------------------------------------------------------------------===// 2763 // Custom DAG optimizations 2764 //===----------------------------------------------------------------------===// 2765 2766 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 2767 DAGCombinerInfo &DCI) const { 2768 EVT VT = N->getValueType(0); 2769 EVT ScalarVT = VT.getScalarType(); 2770 if (ScalarVT != MVT::f32) 2771 return SDValue(); 2772 2773 SelectionDAG &DAG = DCI.DAG; 2774 SDLoc DL(N); 2775 2776 SDValue Src = N->getOperand(0); 2777 EVT SrcVT = Src.getValueType(); 2778 2779 // TODO: We could try to match extracting the higher bytes, which would be 2780 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 2781 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 2782 // about in practice. 2783 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 2784 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 2785 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 2786 DCI.AddToWorklist(Cvt.getNode()); 2787 return Cvt; 2788 } 2789 } 2790 2791 return SDValue(); 2792 } 2793 2794 /// \brief Return true if the given offset Size in bytes can be folded into 2795 /// the immediate offsets of a memory instruction for the given address space. 2796 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 2797 const SISubtarget &STI) { 2798 switch (AS) { 2799 case AMDGPUAS::GLOBAL_ADDRESS: { 2800 // MUBUF instructions a 12-bit offset in bytes. 2801 return isUInt<12>(OffsetSize); 2802 } 2803 case AMDGPUAS::CONSTANT_ADDRESS: { 2804 // SMRD instructions have an 8-bit offset in dwords on SI and 2805 // a 20-bit offset in bytes on VI. 2806 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 2807 return isUInt<20>(OffsetSize); 2808 else 2809 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 2810 } 2811 case AMDGPUAS::LOCAL_ADDRESS: 2812 case AMDGPUAS::REGION_ADDRESS: { 2813 // The single offset versions have a 16-bit offset in bytes. 2814 return isUInt<16>(OffsetSize); 2815 } 2816 case AMDGPUAS::PRIVATE_ADDRESS: 2817 // Indirect register addressing does not use any offsets. 2818 default: 2819 return 0; 2820 } 2821 } 2822 2823 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 2824 2825 // This is a variant of 2826 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 2827 // 2828 // The normal DAG combiner will do this, but only if the add has one use since 2829 // that would increase the number of instructions. 2830 // 2831 // This prevents us from seeing a constant offset that can be folded into a 2832 // memory instruction's addressing mode. If we know the resulting add offset of 2833 // a pointer can be folded into an addressing offset, we can replace the pointer 2834 // operand with the add of new constant offset. This eliminates one of the uses, 2835 // and may allow the remaining use to also be simplified. 2836 // 2837 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 2838 unsigned AddrSpace, 2839 DAGCombinerInfo &DCI) const { 2840 SDValue N0 = N->getOperand(0); 2841 SDValue N1 = N->getOperand(1); 2842 2843 if (N0.getOpcode() != ISD::ADD) 2844 return SDValue(); 2845 2846 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 2847 if (!CN1) 2848 return SDValue(); 2849 2850 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2851 if (!CAdd) 2852 return SDValue(); 2853 2854 // If the resulting offset is too large, we can't fold it into the addressing 2855 // mode offset. 2856 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 2857 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget())) 2858 return SDValue(); 2859 2860 SelectionDAG &DAG = DCI.DAG; 2861 SDLoc SL(N); 2862 EVT VT = N->getValueType(0); 2863 2864 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 2865 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 2866 2867 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 2868 } 2869 2870 SDValue SITargetLowering::performAndCombine(SDNode *N, 2871 DAGCombinerInfo &DCI) const { 2872 if (DCI.isBeforeLegalize()) 2873 return SDValue(); 2874 2875 if (SDValue Base = AMDGPUTargetLowering::performAndCombine(N, DCI)) 2876 return Base; 2877 2878 SelectionDAG &DAG = DCI.DAG; 2879 2880 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 2881 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 2882 SDValue LHS = N->getOperand(0); 2883 SDValue RHS = N->getOperand(1); 2884 2885 if (LHS.getOpcode() == ISD::SETCC && 2886 RHS.getOpcode() == ISD::SETCC) { 2887 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 2888 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 2889 2890 SDValue X = LHS.getOperand(0); 2891 SDValue Y = RHS.getOperand(0); 2892 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 2893 return SDValue(); 2894 2895 if (LCC == ISD::SETO) { 2896 if (X != LHS.getOperand(1)) 2897 return SDValue(); 2898 2899 if (RCC == ISD::SETUNE) { 2900 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 2901 if (!C1 || !C1->isInfinity() || C1->isNegative()) 2902 return SDValue(); 2903 2904 const uint32_t Mask = SIInstrFlags::N_NORMAL | 2905 SIInstrFlags::N_SUBNORMAL | 2906 SIInstrFlags::N_ZERO | 2907 SIInstrFlags::P_ZERO | 2908 SIInstrFlags::P_SUBNORMAL | 2909 SIInstrFlags::P_NORMAL; 2910 2911 static_assert(((~(SIInstrFlags::S_NAN | 2912 SIInstrFlags::Q_NAN | 2913 SIInstrFlags::N_INFINITY | 2914 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 2915 "mask not equal"); 2916 2917 SDLoc DL(N); 2918 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 2919 X, DAG.getConstant(Mask, DL, MVT::i32)); 2920 } 2921 } 2922 } 2923 2924 return SDValue(); 2925 } 2926 2927 SDValue SITargetLowering::performOrCombine(SDNode *N, 2928 DAGCombinerInfo &DCI) const { 2929 SelectionDAG &DAG = DCI.DAG; 2930 SDValue LHS = N->getOperand(0); 2931 SDValue RHS = N->getOperand(1); 2932 2933 EVT VT = N->getValueType(0); 2934 if (VT == MVT::i64) { 2935 // TODO: This could be a generic combine with a predicate for extracting the 2936 // high half of an integer being free. 2937 2938 // (or i64:x, (zero_extend i32:y)) -> 2939 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 2940 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 2941 RHS.getOpcode() != ISD::ZERO_EXTEND) 2942 std::swap(LHS, RHS); 2943 2944 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 2945 SDValue ExtSrc = RHS.getOperand(0); 2946 EVT SrcVT = ExtSrc.getValueType(); 2947 if (SrcVT == MVT::i32) { 2948 SDLoc SL(N); 2949 SDValue LowLHS, HiBits; 2950 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 2951 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 2952 2953 DCI.AddToWorklist(LowOr.getNode()); 2954 DCI.AddToWorklist(HiBits.getNode()); 2955 2956 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 2957 LowOr, HiBits); 2958 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 2959 } 2960 } 2961 } 2962 2963 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 2964 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 2965 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 2966 SDValue Src = LHS.getOperand(0); 2967 if (Src != RHS.getOperand(0)) 2968 return SDValue(); 2969 2970 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 2971 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 2972 if (!CLHS || !CRHS) 2973 return SDValue(); 2974 2975 // Only 10 bits are used. 2976 static const uint32_t MaxMask = 0x3ff; 2977 2978 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 2979 SDLoc DL(N); 2980 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 2981 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 2982 } 2983 2984 return SDValue(); 2985 } 2986 2987 SDValue SITargetLowering::performClassCombine(SDNode *N, 2988 DAGCombinerInfo &DCI) const { 2989 SelectionDAG &DAG = DCI.DAG; 2990 SDValue Mask = N->getOperand(1); 2991 2992 // fp_class x, 0 -> false 2993 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 2994 if (CMask->isNullValue()) 2995 return DAG.getConstant(0, SDLoc(N), MVT::i1); 2996 } 2997 2998 if (N->getOperand(0).isUndef()) 2999 return DAG.getUNDEF(MVT::i1); 3000 3001 return SDValue(); 3002 } 3003 3004 // Constant fold canonicalize. 3005 SDValue SITargetLowering::performFCanonicalizeCombine( 3006 SDNode *N, 3007 DAGCombinerInfo &DCI) const { 3008 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 3009 if (!CFP) 3010 return SDValue(); 3011 3012 SelectionDAG &DAG = DCI.DAG; 3013 const APFloat &C = CFP->getValueAPF(); 3014 3015 // Flush denormals to 0 if not enabled. 3016 if (C.isDenormal()) { 3017 EVT VT = N->getValueType(0); 3018 if (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) 3019 return DAG.getConstantFP(0.0, SDLoc(N), VT); 3020 3021 if (VT == MVT::f64 && !Subtarget->hasFP64Denormals()) 3022 return DAG.getConstantFP(0.0, SDLoc(N), VT); 3023 } 3024 3025 if (C.isNaN()) { 3026 EVT VT = N->getValueType(0); 3027 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 3028 if (C.isSignaling()) { 3029 // Quiet a signaling NaN. 3030 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 3031 } 3032 3033 // Make sure it is the canonical NaN bitpattern. 3034 // 3035 // TODO: Can we use -1 as the canonical NaN value since it's an inline 3036 // immediate? 3037 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 3038 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 3039 } 3040 3041 return SDValue(CFP, 0); 3042 } 3043 3044 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 3045 switch (Opc) { 3046 case ISD::FMAXNUM: 3047 return AMDGPUISD::FMAX3; 3048 case ISD::SMAX: 3049 return AMDGPUISD::SMAX3; 3050 case ISD::UMAX: 3051 return AMDGPUISD::UMAX3; 3052 case ISD::FMINNUM: 3053 return AMDGPUISD::FMIN3; 3054 case ISD::SMIN: 3055 return AMDGPUISD::SMIN3; 3056 case ISD::UMIN: 3057 return AMDGPUISD::UMIN3; 3058 default: 3059 llvm_unreachable("Not a min/max opcode"); 3060 } 3061 } 3062 3063 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL, 3064 SDValue Op0, SDValue Op1, bool Signed) { 3065 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 3066 if (!K1) 3067 return SDValue(); 3068 3069 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 3070 if (!K0) 3071 return SDValue(); 3072 3073 if (Signed) { 3074 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 3075 return SDValue(); 3076 } else { 3077 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 3078 return SDValue(); 3079 } 3080 3081 EVT VT = K0->getValueType(0); 3082 return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT, 3083 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 3084 } 3085 3086 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 3087 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 3088 return true; 3089 3090 return DAG.isKnownNeverNaN(Op); 3091 } 3092 3093 static SDValue performFPMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL, 3094 SDValue Op0, SDValue Op1) { 3095 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1); 3096 if (!K1) 3097 return SDValue(); 3098 3099 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1)); 3100 if (!K0) 3101 return SDValue(); 3102 3103 // Ordered >= (although NaN inputs should have folded away by now). 3104 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 3105 if (Cmp == APFloat::cmpGreaterThan) 3106 return SDValue(); 3107 3108 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 3109 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then 3110 // give the other result, which is different from med3 with a NaN input. 3111 SDValue Var = Op0.getOperand(0); 3112 if (!isKnownNeverSNan(DAG, Var)) 3113 return SDValue(); 3114 3115 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 3116 Var, SDValue(K0, 0), SDValue(K1, 0)); 3117 } 3118 3119 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 3120 DAGCombinerInfo &DCI) const { 3121 SelectionDAG &DAG = DCI.DAG; 3122 3123 unsigned Opc = N->getOpcode(); 3124 SDValue Op0 = N->getOperand(0); 3125 SDValue Op1 = N->getOperand(1); 3126 3127 // Only do this if the inner op has one use since this will just increases 3128 // register pressure for no benefit. 3129 3130 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY) { 3131 // max(max(a, b), c) -> max3(a, b, c) 3132 // min(min(a, b), c) -> min3(a, b, c) 3133 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 3134 SDLoc DL(N); 3135 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 3136 DL, 3137 N->getValueType(0), 3138 Op0.getOperand(0), 3139 Op0.getOperand(1), 3140 Op1); 3141 } 3142 3143 // Try commuted. 3144 // max(a, max(b, c)) -> max3(a, b, c) 3145 // min(a, min(b, c)) -> min3(a, b, c) 3146 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 3147 SDLoc DL(N); 3148 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 3149 DL, 3150 N->getValueType(0), 3151 Op0, 3152 Op1.getOperand(0), 3153 Op1.getOperand(1)); 3154 } 3155 } 3156 3157 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 3158 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 3159 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 3160 return Med3; 3161 } 3162 3163 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 3164 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 3165 return Med3; 3166 } 3167 3168 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 3169 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 3170 (Opc == AMDGPUISD::FMIN_LEGACY && 3171 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 3172 N->getValueType(0) == MVT::f32 && Op0.hasOneUse()) { 3173 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 3174 return Res; 3175 } 3176 3177 return SDValue(); 3178 } 3179 3180 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 3181 DAGCombinerInfo &DCI) const { 3182 SelectionDAG &DAG = DCI.DAG; 3183 SDLoc SL(N); 3184 3185 SDValue LHS = N->getOperand(0); 3186 SDValue RHS = N->getOperand(1); 3187 EVT VT = LHS.getValueType(); 3188 3189 if (VT != MVT::f32 && VT != MVT::f64) 3190 return SDValue(); 3191 3192 // Match isinf pattern 3193 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 3194 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 3195 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 3196 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 3197 if (!CRHS) 3198 return SDValue(); 3199 3200 const APFloat &APF = CRHS->getValueAPF(); 3201 if (APF.isInfinity() && !APF.isNegative()) { 3202 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 3203 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 3204 DAG.getConstant(Mask, SL, MVT::i32)); 3205 } 3206 } 3207 3208 return SDValue(); 3209 } 3210 3211 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 3212 DAGCombinerInfo &DCI) const { 3213 SelectionDAG &DAG = DCI.DAG; 3214 SDLoc DL(N); 3215 3216 switch (N->getOpcode()) { 3217 default: 3218 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 3219 case ISD::SETCC: 3220 return performSetCCCombine(N, DCI); 3221 case ISD::FMAXNUM: 3222 case ISD::FMINNUM: 3223 case ISD::SMAX: 3224 case ISD::SMIN: 3225 case ISD::UMAX: 3226 case ISD::UMIN: 3227 case AMDGPUISD::FMIN_LEGACY: 3228 case AMDGPUISD::FMAX_LEGACY: { 3229 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 3230 N->getValueType(0) != MVT::f64 && 3231 getTargetMachine().getOptLevel() > CodeGenOpt::None) 3232 return performMinMaxCombine(N, DCI); 3233 break; 3234 } 3235 3236 case AMDGPUISD::CVT_F32_UBYTE0: 3237 case AMDGPUISD::CVT_F32_UBYTE1: 3238 case AMDGPUISD::CVT_F32_UBYTE2: 3239 case AMDGPUISD::CVT_F32_UBYTE3: { 3240 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 3241 SDValue Src = N->getOperand(0); 3242 3243 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 3244 if (Src.getOpcode() == ISD::SRL) { 3245 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 3246 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 3247 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 3248 3249 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src.getOperand(1))) { 3250 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 3251 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 3252 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, DL, 3253 MVT::f32, Src.getOperand(0)); 3254 } 3255 } 3256 } 3257 3258 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 3259 3260 APInt KnownZero, KnownOne; 3261 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 3262 !DCI.isBeforeLegalizeOps()); 3263 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3264 if (TLO.ShrinkDemandedConstant(Src, Demanded) || 3265 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) { 3266 DCI.CommitTargetLoweringOpt(TLO); 3267 } 3268 3269 break; 3270 } 3271 3272 case ISD::UINT_TO_FP: { 3273 return performUCharToFloatCombine(N, DCI); 3274 } 3275 case ISD::FADD: { 3276 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 3277 break; 3278 3279 EVT VT = N->getValueType(0); 3280 if (VT != MVT::f32) 3281 break; 3282 3283 // Only do this if we are not trying to support denormals. v_mad_f32 does 3284 // not support denormals ever. 3285 if (Subtarget->hasFP32Denormals()) 3286 break; 3287 3288 SDValue LHS = N->getOperand(0); 3289 SDValue RHS = N->getOperand(1); 3290 3291 // These should really be instruction patterns, but writing patterns with 3292 // source modiifiers is a pain. 3293 3294 // fadd (fadd (a, a), b) -> mad 2.0, a, b 3295 if (LHS.getOpcode() == ISD::FADD) { 3296 SDValue A = LHS.getOperand(0); 3297 if (A == LHS.getOperand(1)) { 3298 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 3299 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS); 3300 } 3301 } 3302 3303 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 3304 if (RHS.getOpcode() == ISD::FADD) { 3305 SDValue A = RHS.getOperand(0); 3306 if (A == RHS.getOperand(1)) { 3307 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 3308 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS); 3309 } 3310 } 3311 3312 return SDValue(); 3313 } 3314 case ISD::FSUB: { 3315 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 3316 break; 3317 3318 EVT VT = N->getValueType(0); 3319 3320 // Try to get the fneg to fold into the source modifier. This undoes generic 3321 // DAG combines and folds them into the mad. 3322 // 3323 // Only do this if we are not trying to support denormals. v_mad_f32 does 3324 // not support denormals ever. 3325 if (VT == MVT::f32 && 3326 !Subtarget->hasFP32Denormals()) { 3327 SDValue LHS = N->getOperand(0); 3328 SDValue RHS = N->getOperand(1); 3329 if (LHS.getOpcode() == ISD::FADD) { 3330 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 3331 3332 SDValue A = LHS.getOperand(0); 3333 if (A == LHS.getOperand(1)) { 3334 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 3335 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS); 3336 3337 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS); 3338 } 3339 } 3340 3341 if (RHS.getOpcode() == ISD::FADD) { 3342 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 3343 3344 SDValue A = RHS.getOperand(0); 3345 if (A == RHS.getOperand(1)) { 3346 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32); 3347 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS); 3348 } 3349 } 3350 3351 return SDValue(); 3352 } 3353 3354 break; 3355 } 3356 case ISD::LOAD: 3357 case ISD::STORE: 3358 case ISD::ATOMIC_LOAD: 3359 case ISD::ATOMIC_STORE: 3360 case ISD::ATOMIC_CMP_SWAP: 3361 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3362 case ISD::ATOMIC_SWAP: 3363 case ISD::ATOMIC_LOAD_ADD: 3364 case ISD::ATOMIC_LOAD_SUB: 3365 case ISD::ATOMIC_LOAD_AND: 3366 case ISD::ATOMIC_LOAD_OR: 3367 case ISD::ATOMIC_LOAD_XOR: 3368 case ISD::ATOMIC_LOAD_NAND: 3369 case ISD::ATOMIC_LOAD_MIN: 3370 case ISD::ATOMIC_LOAD_MAX: 3371 case ISD::ATOMIC_LOAD_UMIN: 3372 case ISD::ATOMIC_LOAD_UMAX: 3373 case AMDGPUISD::ATOMIC_INC: 3374 case AMDGPUISD::ATOMIC_DEC: { // TODO: Target mem intrinsics. 3375 if (DCI.isBeforeLegalize()) 3376 break; 3377 3378 MemSDNode *MemNode = cast<MemSDNode>(N); 3379 SDValue Ptr = MemNode->getBasePtr(); 3380 3381 // TODO: We could also do this for multiplies. 3382 unsigned AS = MemNode->getAddressSpace(); 3383 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) { 3384 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 3385 if (NewPtr) { 3386 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end()); 3387 3388 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 3389 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0); 3390 } 3391 } 3392 break; 3393 } 3394 case ISD::AND: 3395 return performAndCombine(N, DCI); 3396 case ISD::OR: 3397 return performOrCombine(N, DCI); 3398 case AMDGPUISD::FP_CLASS: 3399 return performClassCombine(N, DCI); 3400 case ISD::FCANONICALIZE: 3401 return performFCanonicalizeCombine(N, DCI); 3402 case AMDGPUISD::FRACT: 3403 case AMDGPUISD::RCP: 3404 case AMDGPUISD::RSQ: 3405 case AMDGPUISD::RCP_LEGACY: 3406 case AMDGPUISD::RSQ_LEGACY: 3407 case AMDGPUISD::RSQ_CLAMP: 3408 case AMDGPUISD::LDEXP: { 3409 SDValue Src = N->getOperand(0); 3410 if (Src.isUndef()) 3411 return Src; 3412 break; 3413 } 3414 } 3415 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 3416 } 3417 3418 /// \brief Helper function for adjustWritemask 3419 static unsigned SubIdx2Lane(unsigned Idx) { 3420 switch (Idx) { 3421 default: return 0; 3422 case AMDGPU::sub0: return 0; 3423 case AMDGPU::sub1: return 1; 3424 case AMDGPU::sub2: return 2; 3425 case AMDGPU::sub3: return 3; 3426 } 3427 } 3428 3429 /// \brief Adjust the writemask of MIMG instructions 3430 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 3431 SelectionDAG &DAG) const { 3432 SDNode *Users[4] = { }; 3433 unsigned Lane = 0; 3434 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 3435 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 3436 unsigned NewDmask = 0; 3437 3438 // Try to figure out the used register components 3439 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 3440 I != E; ++I) { 3441 3442 // Abort if we can't understand the usage 3443 if (!I->isMachineOpcode() || 3444 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 3445 return; 3446 3447 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 3448 // Note that subregs are packed, i.e. Lane==0 is the first bit set 3449 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 3450 // set, etc. 3451 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 3452 3453 // Set which texture component corresponds to the lane. 3454 unsigned Comp; 3455 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 3456 assert(Dmask); 3457 Comp = countTrailingZeros(Dmask); 3458 Dmask &= ~(1 << Comp); 3459 } 3460 3461 // Abort if we have more than one user per component 3462 if (Users[Lane]) 3463 return; 3464 3465 Users[Lane] = *I; 3466 NewDmask |= 1 << Comp; 3467 } 3468 3469 // Abort if there's no change 3470 if (NewDmask == OldDmask) 3471 return; 3472 3473 // Adjust the writemask in the node 3474 std::vector<SDValue> Ops; 3475 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 3476 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 3477 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 3478 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 3479 3480 // If we only got one lane, replace it with a copy 3481 // (if NewDmask has only one bit set...) 3482 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 3483 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 3484 MVT::i32); 3485 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 3486 SDLoc(), Users[Lane]->getValueType(0), 3487 SDValue(Node, 0), RC); 3488 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 3489 return; 3490 } 3491 3492 // Update the users of the node with the new indices 3493 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 3494 3495 SDNode *User = Users[i]; 3496 if (!User) 3497 continue; 3498 3499 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 3500 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 3501 3502 switch (Idx) { 3503 default: break; 3504 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 3505 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 3506 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 3507 } 3508 } 3509 } 3510 3511 static bool isFrameIndexOp(SDValue Op) { 3512 if (Op.getOpcode() == ISD::AssertZext) 3513 Op = Op.getOperand(0); 3514 3515 return isa<FrameIndexSDNode>(Op); 3516 } 3517 3518 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 3519 /// with frame index operands. 3520 /// LLVM assumes that inputs are to these instructions are registers. 3521 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 3522 SelectionDAG &DAG) const { 3523 3524 SmallVector<SDValue, 8> Ops; 3525 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 3526 if (!isFrameIndexOp(Node->getOperand(i))) { 3527 Ops.push_back(Node->getOperand(i)); 3528 continue; 3529 } 3530 3531 SDLoc DL(Node); 3532 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 3533 Node->getOperand(i).getValueType(), 3534 Node->getOperand(i)), 0)); 3535 } 3536 3537 DAG.UpdateNodeOperands(Node, Ops); 3538 } 3539 3540 /// \brief Fold the instructions after selecting them. 3541 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 3542 SelectionDAG &DAG) const { 3543 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3544 unsigned Opcode = Node->getMachineOpcode(); 3545 3546 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 3547 !TII->isGather4(Opcode)) 3548 adjustWritemask(Node, DAG); 3549 3550 if (Opcode == AMDGPU::INSERT_SUBREG || 3551 Opcode == AMDGPU::REG_SEQUENCE) { 3552 legalizeTargetIndependentNode(Node, DAG); 3553 return Node; 3554 } 3555 return Node; 3556 } 3557 3558 /// \brief Assign the register class depending on the number of 3559 /// bits set in the writemask 3560 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 3561 SDNode *Node) const { 3562 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3563 3564 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 3565 3566 if (TII->isVOP3(MI.getOpcode())) { 3567 // Make sure constant bus requirements are respected. 3568 TII->legalizeOperandsVOP3(MRI, MI); 3569 return; 3570 } 3571 3572 if (TII->isMIMG(MI)) { 3573 unsigned VReg = MI.getOperand(0).getReg(); 3574 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4; 3575 unsigned Writemask = MI.getOperand(DmaskIdx).getImm(); 3576 unsigned BitsSet = 0; 3577 for (unsigned i = 0; i < 4; ++i) 3578 BitsSet += Writemask & (1 << i) ? 1 : 0; 3579 3580 const TargetRegisterClass *RC; 3581 switch (BitsSet) { 3582 default: return; 3583 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 3584 case 2: RC = &AMDGPU::VReg_64RegClass; break; 3585 case 3: RC = &AMDGPU::VReg_96RegClass; break; 3586 } 3587 3588 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet); 3589 MI.setDesc(TII->get(NewOpcode)); 3590 MRI.setRegClass(VReg, RC); 3591 return; 3592 } 3593 3594 // Replace unused atomics with the no return version. 3595 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 3596 if (NoRetAtomicOp != -1) { 3597 if (!Node->hasAnyUseOfValue(0)) { 3598 MI.setDesc(TII->get(NoRetAtomicOp)); 3599 MI.RemoveOperand(0); 3600 return; 3601 } 3602 3603 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 3604 // instruction, because the return type of these instructions is a vec2 of 3605 // the memory type, so it can be tied to the input operand. 3606 // This means these instructions always have a use, so we need to add a 3607 // special case to check if the atomic has only one extract_subreg use, 3608 // which itself has no uses. 3609 if ((Node->hasNUsesOfValue(1, 0) && 3610 Node->use_begin()->isMachineOpcode() && 3611 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 3612 !Node->use_begin()->hasAnyUseOfValue(0))) { 3613 unsigned Def = MI.getOperand(0).getReg(); 3614 3615 // Change this into a noret atomic. 3616 MI.setDesc(TII->get(NoRetAtomicOp)); 3617 MI.RemoveOperand(0); 3618 3619 // If we only remove the def operand from the atomic instruction, the 3620 // extract_subreg will be left with a use of a vreg without a def. 3621 // So we need to insert an implicit_def to avoid machine verifier 3622 // errors. 3623 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 3624 TII->get(AMDGPU::IMPLICIT_DEF), Def); 3625 } 3626 return; 3627 } 3628 } 3629 3630 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 3631 uint64_t Val) { 3632 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 3633 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 3634 } 3635 3636 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 3637 const SDLoc &DL, 3638 SDValue Ptr) const { 3639 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3640 3641 // Build the half of the subregister with the constants before building the 3642 // full 128-bit register. If we are building multiple resource descriptors, 3643 // this will allow CSEing of the 2-component register. 3644 const SDValue Ops0[] = { 3645 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 3646 buildSMovImm32(DAG, DL, 0), 3647 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 3648 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 3649 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 3650 }; 3651 3652 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 3653 MVT::v2i32, Ops0), 0); 3654 3655 // Combine the constants and the pointer. 3656 const SDValue Ops1[] = { 3657 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 3658 Ptr, 3659 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 3660 SubRegHi, 3661 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 3662 }; 3663 3664 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 3665 } 3666 3667 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 3668 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 3669 /// of the resource descriptor) to create an offset, which is added to 3670 /// the resource pointer. 3671 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 3672 SDValue Ptr, uint32_t RsrcDword1, 3673 uint64_t RsrcDword2And3) const { 3674 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 3675 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 3676 if (RsrcDword1) { 3677 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 3678 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 3679 0); 3680 } 3681 3682 SDValue DataLo = buildSMovImm32(DAG, DL, 3683 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 3684 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 3685 3686 const SDValue Ops[] = { 3687 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 3688 PtrLo, 3689 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 3690 PtrHi, 3691 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 3692 DataLo, 3693 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 3694 DataHi, 3695 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 3696 }; 3697 3698 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 3699 } 3700 3701 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG, 3702 const TargetRegisterClass *RC, 3703 unsigned Reg, EVT VT) const { 3704 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT); 3705 3706 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()), 3707 cast<RegisterSDNode>(VReg)->getReg(), VT); 3708 } 3709 3710 //===----------------------------------------------------------------------===// 3711 // SI Inline Assembly Support 3712 //===----------------------------------------------------------------------===// 3713 3714 std::pair<unsigned, const TargetRegisterClass *> 3715 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 3716 StringRef Constraint, 3717 MVT VT) const { 3718 3719 if (Constraint.size() == 1) { 3720 switch (Constraint[0]) { 3721 case 's': 3722 case 'r': 3723 switch (VT.getSizeInBits()) { 3724 default: 3725 return std::make_pair(0U, nullptr); 3726 case 32: 3727 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass); 3728 case 64: 3729 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 3730 case 128: 3731 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 3732 case 256: 3733 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 3734 } 3735 3736 case 'v': 3737 switch (VT.getSizeInBits()) { 3738 default: 3739 return std::make_pair(0U, nullptr); 3740 case 32: 3741 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 3742 case 64: 3743 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 3744 case 96: 3745 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 3746 case 128: 3747 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 3748 case 256: 3749 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 3750 case 512: 3751 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 3752 } 3753 } 3754 } 3755 3756 if (Constraint.size() > 1) { 3757 const TargetRegisterClass *RC = nullptr; 3758 if (Constraint[1] == 'v') { 3759 RC = &AMDGPU::VGPR_32RegClass; 3760 } else if (Constraint[1] == 's') { 3761 RC = &AMDGPU::SGPR_32RegClass; 3762 } 3763 3764 if (RC) { 3765 uint32_t Idx; 3766 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 3767 if (!Failed && Idx < RC->getNumRegs()) 3768 return std::make_pair(RC->getRegister(Idx), RC); 3769 } 3770 } 3771 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 3772 } 3773 3774 SITargetLowering::ConstraintType 3775 SITargetLowering::getConstraintType(StringRef Constraint) const { 3776 if (Constraint.size() == 1) { 3777 switch (Constraint[0]) { 3778 default: break; 3779 case 's': 3780 case 'v': 3781 return C_RegisterClass; 3782 } 3783 } 3784 return TargetLowering::getConstraintType(Constraint); 3785 } 3786