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 "SIISelLowering.h" 22 #include "AMDGPU.h" 23 #include "AMDGPUIntrinsicInfo.h" 24 #include "AMDGPUSubtarget.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/IR/DiagnosticInfo.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/ADT/SmallString.h" 37 38 using namespace llvm; 39 40 SITargetLowering::SITargetLowering(TargetMachine &TM, 41 const AMDGPUSubtarget &STI) 42 : AMDGPUTargetLowering(TM, STI) { 43 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 44 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 45 46 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 47 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 48 49 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 50 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 51 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 52 53 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 54 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 55 56 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 57 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 58 59 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 60 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 61 62 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 63 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 64 65 computeRegisterProperties(STI.getRegisterInfo()); 66 67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 68 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 69 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 70 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 71 72 setOperationAction(ISD::ADD, MVT::i32, Legal); 73 setOperationAction(ISD::ADDC, MVT::i32, Legal); 74 setOperationAction(ISD::ADDE, MVT::i32, Legal); 75 setOperationAction(ISD::SUBC, MVT::i32, Legal); 76 setOperationAction(ISD::SUBE, MVT::i32, Legal); 77 78 setOperationAction(ISD::FSIN, MVT::f32, Custom); 79 setOperationAction(ISD::FCOS, MVT::f32, Custom); 80 81 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 82 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 83 84 // We need to custom lower vector stores from local memory 85 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 86 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 87 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 88 89 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 90 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 91 92 setOperationAction(ISD::STORE, MVT::i1, Custom); 93 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 94 95 setOperationAction(ISD::SELECT, MVT::i64, Custom); 96 setOperationAction(ISD::SELECT, MVT::f64, Promote); 97 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 98 99 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 100 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 101 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 102 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 103 104 setOperationAction(ISD::SETCC, MVT::i1, Promote); 105 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 106 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 107 108 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 109 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 110 111 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal); 112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 114 115 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal); 116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 118 119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal); 120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 122 123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 125 126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 128 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom); 129 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 130 131 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 132 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 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 // On SI this is s_memtime and s_memrealtime on VI. 139 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 140 141 for (MVT VT : MVT::integer_valuetypes()) { 142 if (VT == MVT::i64) 143 continue; 144 145 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 146 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal); 147 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal); 148 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand); 149 150 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 151 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal); 152 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal); 153 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand); 154 155 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote); 156 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal); 157 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal); 158 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand); 159 } 160 161 for (MVT VT : MVT::integer_vector_valuetypes()) { 162 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand); 163 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand); 164 } 165 166 for (MVT VT : MVT::fp_valuetypes()) 167 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 168 169 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand); 170 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand); 171 172 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 173 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 174 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 175 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 176 177 178 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand); 179 180 setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand); 181 setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand); 182 183 setOperationAction(ISD::LOAD, MVT::i1, Custom); 184 185 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 186 AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32); 187 188 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 189 AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32); 190 191 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 192 193 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 194 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 195 setOperationAction(ISD::FrameIndex, MVT::i32, Custom); 196 197 // These should use UDIVREM, so set them to expand 198 setOperationAction(ISD::UDIV, MVT::i64, Expand); 199 setOperationAction(ISD::UREM, MVT::i64, Expand); 200 201 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 202 setOperationAction(ISD::SELECT, MVT::i1, Promote); 203 204 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 205 206 207 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 208 209 // We only support LOAD/STORE and vector manipulation ops for vectors 210 // with > 4 elements. 211 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) { 212 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 213 switch(Op) { 214 case ISD::LOAD: 215 case ISD::STORE: 216 case ISD::BUILD_VECTOR: 217 case ISD::BITCAST: 218 case ISD::EXTRACT_VECTOR_ELT: 219 case ISD::INSERT_VECTOR_ELT: 220 case ISD::INSERT_SUBVECTOR: 221 case ISD::EXTRACT_SUBVECTOR: 222 case ISD::SCALAR_TO_VECTOR: 223 break; 224 case ISD::CONCAT_VECTORS: 225 setOperationAction(Op, VT, Custom); 226 break; 227 default: 228 setOperationAction(Op, VT, Expand); 229 break; 230 } 231 } 232 } 233 234 // Most operations are naturally 32-bit vector operations. We only support 235 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 236 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 237 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 238 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 239 240 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 241 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 242 243 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 244 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 245 246 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 247 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 248 } 249 250 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) { 251 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 252 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 253 setOperationAction(ISD::FRINT, MVT::f64, Legal); 254 } 255 256 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 257 setOperationAction(ISD::FDIV, MVT::f32, Custom); 258 setOperationAction(ISD::FDIV, MVT::f64, Custom); 259 260 setTargetDAGCombine(ISD::FADD); 261 setTargetDAGCombine(ISD::FSUB); 262 setTargetDAGCombine(ISD::FMINNUM); 263 setTargetDAGCombine(ISD::FMAXNUM); 264 setTargetDAGCombine(ISD::SMIN); 265 setTargetDAGCombine(ISD::SMAX); 266 setTargetDAGCombine(ISD::UMIN); 267 setTargetDAGCombine(ISD::UMAX); 268 setTargetDAGCombine(ISD::SETCC); 269 setTargetDAGCombine(ISD::AND); 270 setTargetDAGCombine(ISD::OR); 271 setTargetDAGCombine(ISD::UINT_TO_FP); 272 273 // All memory operations. Some folding on the pointer operand is done to help 274 // matching the constant offsets in the addressing modes. 275 setTargetDAGCombine(ISD::LOAD); 276 setTargetDAGCombine(ISD::STORE); 277 setTargetDAGCombine(ISD::ATOMIC_LOAD); 278 setTargetDAGCombine(ISD::ATOMIC_STORE); 279 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 280 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 281 setTargetDAGCombine(ISD::ATOMIC_SWAP); 282 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 283 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 284 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 285 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 286 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 287 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 288 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 289 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 290 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 291 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 292 293 setSchedulingPreference(Sched::RegPressure); 294 } 295 296 //===----------------------------------------------------------------------===// 297 // TargetLowering queries 298 //===----------------------------------------------------------------------===// 299 300 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &, 301 EVT) const { 302 // SI has some legal vector types, but no legal vector operations. Say no 303 // shuffles are legal in order to prefer scalarizing some vector operations. 304 return false; 305 } 306 307 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 308 // Flat instructions do not have offsets, and only have the register 309 // address. 310 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1); 311 } 312 313 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 314 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 315 // additionally can do r + r + i with addr64. 32-bit has more addressing 316 // mode options. Depending on the resource constant, it can also do 317 // (i64 r0) + (i32 r1) * (i14 i). 318 // 319 // Private arrays end up using a scratch buffer most of the time, so also 320 // assume those use MUBUF instructions. Scratch loads / stores are currently 321 // implemented as mubuf instructions with offen bit set, so slightly 322 // different than the normal addr64. 323 if (!isUInt<12>(AM.BaseOffs)) 324 return false; 325 326 // FIXME: Since we can split immediate into soffset and immediate offset, 327 // would it make sense to allow any immediate? 328 329 switch (AM.Scale) { 330 case 0: // r + i or just i, depending on HasBaseReg. 331 return true; 332 case 1: 333 return true; // We have r + r or r + i. 334 case 2: 335 if (AM.HasBaseReg) { 336 // Reject 2 * r + r. 337 return false; 338 } 339 340 // Allow 2 * r as r + r 341 // Or 2 * r + i is allowed as r + r + i. 342 return true; 343 default: // Don't allow n * r 344 return false; 345 } 346 } 347 348 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 349 const AddrMode &AM, Type *Ty, 350 unsigned AS) const { 351 // No global is ever allowed as a base. 352 if (AM.BaseGV) 353 return false; 354 355 switch (AS) { 356 case AMDGPUAS::GLOBAL_ADDRESS: { 357 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 358 // Assume the we will use FLAT for all global memory accesses 359 // on VI. 360 // FIXME: This assumption is currently wrong. On VI we still use 361 // MUBUF instructions for the r + i addressing mode. As currently 362 // implemented, the MUBUF instructions only work on buffer < 4GB. 363 // It may be possible to support > 4GB buffers with MUBUF instructions, 364 // by setting the stride value in the resource descriptor which would 365 // increase the size limit to (stride * 4GB). However, this is risky, 366 // because it has never been validated. 367 return isLegalFlatAddressingMode(AM); 368 } 369 370 return isLegalMUBUFAddressingMode(AM); 371 } 372 case AMDGPUAS::CONSTANT_ADDRESS: { 373 // If the offset isn't a multiple of 4, it probably isn't going to be 374 // correctly aligned. 375 if (AM.BaseOffs % 4 != 0) 376 return isLegalMUBUFAddressingMode(AM); 377 378 // There are no SMRD extloads, so if we have to do a small type access we 379 // will use a MUBUF load. 380 // FIXME?: We also need to do this if unaligned, but we don't know the 381 // alignment here. 382 if (DL.getTypeStoreSize(Ty) < 4) 383 return isLegalMUBUFAddressingMode(AM); 384 385 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 386 // SMRD instructions have an 8-bit, dword offset on SI. 387 if (!isUInt<8>(AM.BaseOffs / 4)) 388 return false; 389 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 390 // On CI+, this can also be a 32-bit literal constant offset. If it fits 391 // in 8-bits, it can use a smaller encoding. 392 if (!isUInt<32>(AM.BaseOffs / 4)) 393 return false; 394 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) { 395 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 396 if (!isUInt<20>(AM.BaseOffs)) 397 return false; 398 } else 399 llvm_unreachable("unhandled generation"); 400 401 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 402 return true; 403 404 if (AM.Scale == 1 && AM.HasBaseReg) 405 return true; 406 407 return false; 408 } 409 410 case AMDGPUAS::PRIVATE_ADDRESS: 411 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE: 412 return isLegalMUBUFAddressingMode(AM); 413 414 case AMDGPUAS::LOCAL_ADDRESS: 415 case AMDGPUAS::REGION_ADDRESS: { 416 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 417 // field. 418 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 419 // an 8-bit dword offset but we don't know the alignment here. 420 if (!isUInt<16>(AM.BaseOffs)) 421 return false; 422 423 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 424 return true; 425 426 if (AM.Scale == 1 && AM.HasBaseReg) 427 return true; 428 429 return false; 430 } 431 case AMDGPUAS::FLAT_ADDRESS: 432 return isLegalFlatAddressingMode(AM); 433 434 default: 435 llvm_unreachable("unhandled address space"); 436 } 437 } 438 439 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 440 unsigned AddrSpace, 441 unsigned Align, 442 bool *IsFast) const { 443 if (IsFast) 444 *IsFast = false; 445 446 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 447 // which isn't a simple VT. 448 if (!VT.isSimple() || VT == MVT::Other) 449 return false; 450 451 // TODO - CI+ supports unaligned memory accesses, but this requires driver 452 // support. 453 454 // XXX - The only mention I see of this in the ISA manual is for LDS direct 455 // reads the "byte address and must be dword aligned". Is it also true for the 456 // normal loads and stores? 457 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) { 458 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 459 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 460 // with adjacent offsets. 461 bool AlignedBy4 = (Align % 4 == 0); 462 if (IsFast) 463 *IsFast = AlignedBy4; 464 return AlignedBy4; 465 } 466 467 // Smaller than dword value must be aligned. 468 // FIXME: This should be allowed on CI+ 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 513 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 514 const MemSDNode *MemNode = cast<MemSDNode>(N); 515 const Value *Ptr = MemNode->getMemOperand()->getValue(); 516 517 // UndefValue means this is a load of a kernel input. These are uniform. 518 // Sometimes LDS instructions have constant pointers 519 if (isa<UndefValue>(Ptr) || isa<Argument>(Ptr) || isa<Constant>(Ptr) || 520 isa<GlobalValue>(Ptr)) 521 return true; 522 523 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 524 return I && I->getMetadata("amdgpu.uniform"); 525 } 526 527 TargetLoweringBase::LegalizeTypeAction 528 SITargetLowering::getPreferredVectorAction(EVT VT) const { 529 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 530 return TypeSplitVector; 531 532 return TargetLoweringBase::getPreferredVectorAction(VT); 533 } 534 535 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 536 Type *Ty) const { 537 const SIInstrInfo *TII = 538 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 539 return TII->isInlineConstant(Imm); 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::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT, 553 SDLoc SL, SDValue Chain, 554 unsigned Offset, bool Signed) const { 555 const DataLayout &DL = DAG.getDataLayout(); 556 MachineFunction &MF = DAG.getMachineFunction(); 557 const SIRegisterInfo *TRI = 558 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 559 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 560 561 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 562 563 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 564 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 565 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 566 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 567 MRI.getLiveInVirtReg(InputPtrReg), PtrVT); 568 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 569 DAG.getConstant(Offset, SL, PtrVT)); 570 SDValue PtrOffset = DAG.getUNDEF(PtrVT); 571 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 572 573 unsigned Align = DL.getABITypeAlignment(Ty); 574 575 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 576 if (MemVT.isFloatingPoint()) 577 ExtTy = ISD::EXTLOAD; 578 579 return DAG.getLoad(ISD::UNINDEXED, ExtTy, 580 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT, 581 false, // isVolatile 582 true, // isNonTemporal 583 true, // isInvariant 584 Align); // Alignment 585 } 586 587 SDValue SITargetLowering::LowerFormalArguments( 588 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 589 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG, 590 SmallVectorImpl<SDValue> &InVals) const { 591 const SIRegisterInfo *TRI = 592 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo()); 593 594 MachineFunction &MF = DAG.getMachineFunction(); 595 FunctionType *FType = MF.getFunction()->getFunctionType(); 596 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 597 const AMDGPUSubtarget &ST = MF.getSubtarget<AMDGPUSubtarget>(); 598 599 if (Subtarget->isAmdHsaOS() && Info->getShaderType() != ShaderType::COMPUTE) { 600 const Function *Fn = MF.getFunction(); 601 DiagnosticInfoUnsupported NoGraphicsHSA( 602 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 603 DAG.getContext()->diagnose(NoGraphicsHSA); 604 return SDValue(); 605 } 606 607 // FIXME: We currently assume all calling conventions are kernels. 608 609 SmallVector<ISD::InputArg, 16> Splits; 610 BitVector Skipped(Ins.size()); 611 612 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) { 613 const ISD::InputArg &Arg = Ins[i]; 614 615 // First check if it's a PS input addr 616 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() && 617 !Arg.Flags.isByVal() && PSInputNum <= 15) { 618 619 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 620 // We can safely skip PS inputs 621 Skipped.set(i); 622 ++PSInputNum; 623 continue; 624 } 625 626 Info->markPSInputAllocated(PSInputNum); 627 if (Arg.Used) 628 Info->PSInputEna |= 1 << PSInputNum; 629 630 ++PSInputNum; 631 } 632 633 // Second split vertices into their elements 634 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) { 635 ISD::InputArg NewArg = Arg; 636 NewArg.Flags.setSplit(); 637 NewArg.VT = Arg.VT.getVectorElementType(); 638 639 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 640 // three or five element vertex only needs three or five registers, 641 // NOT four or eight. 642 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 643 unsigned NumElements = ParamType->getVectorNumElements(); 644 645 for (unsigned j = 0; j != NumElements; ++j) { 646 Splits.push_back(NewArg); 647 NewArg.PartOffset += NewArg.VT.getStoreSize(); 648 } 649 650 } else if (Info->getShaderType() != ShaderType::COMPUTE) { 651 Splits.push_back(Arg); 652 } 653 } 654 655 SmallVector<CCValAssign, 16> ArgLocs; 656 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 657 *DAG.getContext()); 658 659 // At least one interpolation mode must be enabled or else the GPU will hang. 660 // 661 // Check PSInputAddr instead of PSInputEna. The idea is that if the user set 662 // PSInputAddr, the user wants to enable some bits after the compilation 663 // based on run-time states. Since we can't know what the final PSInputEna 664 // will look like, so we shouldn't do anything here and the user should take 665 // responsibility for the correct programming. 666 // 667 // Otherwise, the following restrictions apply: 668 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 669 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 670 // enabled too. 671 if (Info->getShaderType() == ShaderType::PIXEL && 672 ((Info->getPSInputAddr() & 0x7F) == 0 || 673 ((Info->getPSInputAddr() & 0xF) == 0 && 674 Info->isPSInputAllocated(11)))) { 675 CCInfo.AllocateReg(AMDGPU::VGPR0); 676 CCInfo.AllocateReg(AMDGPU::VGPR1); 677 Info->markPSInputAllocated(0); 678 Info->PSInputEna |= 1; 679 } 680 681 if (Info->getShaderType() == ShaderType::COMPUTE) { 682 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins, 683 Splits); 684 } 685 686 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 687 if (Info->hasPrivateSegmentBuffer()) { 688 unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI); 689 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass); 690 CCInfo.AllocateReg(PrivateSegmentBufferReg); 691 } 692 693 if (Info->hasDispatchPtr()) { 694 unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI); 695 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass); 696 CCInfo.AllocateReg(DispatchPtrReg); 697 } 698 699 if (Info->hasKernargSegmentPtr()) { 700 unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI); 701 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass); 702 CCInfo.AllocateReg(InputPtrReg); 703 } 704 705 if (Info->hasFlatScratchInit()) { 706 unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI); 707 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SReg_64RegClass); 708 CCInfo.AllocateReg(FlatScratchInitReg); 709 } 710 711 AnalyzeFormalArguments(CCInfo, Splits); 712 713 SmallVector<SDValue, 16> Chains; 714 715 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 716 717 const ISD::InputArg &Arg = Ins[i]; 718 if (Skipped[i]) { 719 InVals.push_back(DAG.getUNDEF(Arg.VT)); 720 continue; 721 } 722 723 CCValAssign &VA = ArgLocs[ArgIdx++]; 724 MVT VT = VA.getLocVT(); 725 726 if (VA.isMemLoc()) { 727 VT = Ins[i].VT; 728 EVT MemVT = Splits[i].VT; 729 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() + 730 VA.getLocMemOffset(); 731 // The first 36 bytes of the input buffer contains information about 732 // thread group and global sizes. 733 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain, 734 Offset, Ins[i].Flags.isSExt()); 735 Chains.push_back(Arg.getValue(1)); 736 737 auto *ParamTy = 738 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 739 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 740 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 741 // On SI local pointers are just offsets into LDS, so they are always 742 // less than 16-bits. On CI and newer they could potentially be 743 // real pointers, so we can't guarantee their size. 744 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 745 DAG.getValueType(MVT::i16)); 746 } 747 748 InVals.push_back(Arg); 749 Info->ABIArgOffset = Offset + MemVT.getStoreSize(); 750 continue; 751 } 752 assert(VA.isRegLoc() && "Parameter must be in a register!"); 753 754 unsigned Reg = VA.getLocReg(); 755 756 if (VT == MVT::i64) { 757 // For now assume it is a pointer 758 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, 759 &AMDGPU::SReg_64RegClass); 760 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass); 761 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 762 InVals.push_back(Copy); 763 continue; 764 } 765 766 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 767 768 Reg = MF.addLiveIn(Reg, RC); 769 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 770 771 if (Arg.VT.isVector()) { 772 773 // Build a vector from the registers 774 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 775 unsigned NumElements = ParamType->getVectorNumElements(); 776 777 SmallVector<SDValue, 4> Regs; 778 Regs.push_back(Val); 779 for (unsigned j = 1; j != NumElements; ++j) { 780 Reg = ArgLocs[ArgIdx++].getLocReg(); 781 Reg = MF.addLiveIn(Reg, RC); 782 783 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 784 Regs.push_back(Copy); 785 } 786 787 // Fill up the missing vector elements 788 NumElements = Arg.VT.getVectorNumElements() - NumElements; 789 Regs.append(NumElements, DAG.getUNDEF(VT)); 790 791 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs)); 792 continue; 793 } 794 795 InVals.push_back(Val); 796 } 797 798 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 799 // these from the dispatch pointer. 800 801 // Start adding system SGPRs. 802 if (Info->hasWorkGroupIDX()) { 803 unsigned Reg = Info->addWorkGroupIDX(); 804 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 805 CCInfo.AllocateReg(Reg); 806 } else 807 llvm_unreachable("work group id x is always enabled"); 808 809 if (Info->hasWorkGroupIDY()) { 810 unsigned Reg = Info->addWorkGroupIDY(); 811 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 812 CCInfo.AllocateReg(Reg); 813 } 814 815 if (Info->hasWorkGroupIDZ()) { 816 unsigned Reg = Info->addWorkGroupIDZ(); 817 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 818 CCInfo.AllocateReg(Reg); 819 } 820 821 if (Info->hasWorkGroupInfo()) { 822 unsigned Reg = Info->addWorkGroupInfo(); 823 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 824 CCInfo.AllocateReg(Reg); 825 } 826 827 if (Info->hasPrivateSegmentWaveByteOffset()) { 828 // Scratch wave offset passed in system SGPR. 829 unsigned PrivateSegmentWaveByteOffsetReg 830 = Info->addPrivateSegmentWaveByteOffset(); 831 832 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 833 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 834 } 835 836 // Now that we've figured out where the scratch register inputs are, see if 837 // should reserve the arguments and use them directly. 838 bool HasStackObjects = MF.getFrameInfo()->hasStackObjects(); 839 // Record that we know we have non-spill stack objects so we don't need to 840 // check all stack objects later. 841 if (HasStackObjects) 842 Info->setHasNonSpillStackObjects(true); 843 844 if (ST.isAmdHsaOS()) { 845 // TODO: Assume we will spill without optimizations. 846 if (HasStackObjects) { 847 // If we have stack objects, we unquestionably need the private buffer 848 // resource. For the HSA ABI, this will be the first 4 user SGPR 849 // inputs. We can reserve those and use them directly. 850 851 unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue( 852 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER); 853 Info->setScratchRSrcReg(PrivateSegmentBufferReg); 854 855 unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue( 856 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 857 Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 858 } else { 859 unsigned ReservedBufferReg 860 = TRI->reservedPrivateSegmentBufferReg(MF); 861 unsigned ReservedOffsetReg 862 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 863 864 // We tentatively reserve the last registers (skipping the last two 865 // which may contain VCC). After register allocation, we'll replace 866 // these with the ones immediately after those which were really 867 // allocated. In the prologue copies will be inserted from the argument 868 // to these reserved registers. 869 Info->setScratchRSrcReg(ReservedBufferReg); 870 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 871 } 872 } else { 873 unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF); 874 875 // Without HSA, relocations are used for the scratch pointer and the 876 // buffer resource setup is always inserted in the prologue. Scratch wave 877 // offset is still in an input SGPR. 878 Info->setScratchRSrcReg(ReservedBufferReg); 879 880 if (HasStackObjects) { 881 unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue( 882 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 883 Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg); 884 } else { 885 unsigned ReservedOffsetReg 886 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 887 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 888 } 889 } 890 891 if (Info->hasWorkItemIDX()) { 892 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X); 893 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 894 CCInfo.AllocateReg(Reg); 895 } else 896 llvm_unreachable("workitem id x should always be enabled"); 897 898 if (Info->hasWorkItemIDY()) { 899 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y); 900 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 901 CCInfo.AllocateReg(Reg); 902 } 903 904 if (Info->hasWorkItemIDZ()) { 905 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z); 906 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 907 CCInfo.AllocateReg(Reg); 908 } 909 910 if (Chains.empty()) 911 return Chain; 912 913 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 914 } 915 916 SDValue SITargetLowering::LowerReturn(SDValue Chain, 917 CallingConv::ID CallConv, 918 bool isVarArg, 919 const SmallVectorImpl<ISD::OutputArg> &Outs, 920 const SmallVectorImpl<SDValue> &OutVals, 921 SDLoc DL, SelectionDAG &DAG) const { 922 MachineFunction &MF = DAG.getMachineFunction(); 923 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 924 925 if (Info->getShaderType() == ShaderType::COMPUTE) 926 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 927 OutVals, DL, DAG); 928 929 Info->setIfReturnsVoid(Outs.size() == 0); 930 931 SmallVector<ISD::OutputArg, 48> Splits; 932 SmallVector<SDValue, 48> SplitVals; 933 934 // Split vectors into their elements. 935 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 936 const ISD::OutputArg &Out = Outs[i]; 937 938 if (Out.VT.isVector()) { 939 MVT VT = Out.VT.getVectorElementType(); 940 ISD::OutputArg NewOut = Out; 941 NewOut.Flags.setSplit(); 942 NewOut.VT = VT; 943 944 // We want the original number of vector elements here, e.g. 945 // three or five, not four or eight. 946 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 947 948 for (unsigned j = 0; j != NumElements; ++j) { 949 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 950 DAG.getConstant(j, DL, MVT::i32)); 951 SplitVals.push_back(Elem); 952 Splits.push_back(NewOut); 953 NewOut.PartOffset += NewOut.VT.getStoreSize(); 954 } 955 } else { 956 SplitVals.push_back(OutVals[i]); 957 Splits.push_back(Out); 958 } 959 } 960 961 // CCValAssign - represent the assignment of the return value to a location. 962 SmallVector<CCValAssign, 48> RVLocs; 963 964 // CCState - Info about the registers and stack slots. 965 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 966 *DAG.getContext()); 967 968 // Analyze outgoing return values. 969 AnalyzeReturn(CCInfo, Splits); 970 971 SDValue Flag; 972 SmallVector<SDValue, 48> RetOps; 973 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 974 975 // Copy the result values into the output registers. 976 for (unsigned i = 0, realRVLocIdx = 0; 977 i != RVLocs.size(); 978 ++i, ++realRVLocIdx) { 979 CCValAssign &VA = RVLocs[i]; 980 assert(VA.isRegLoc() && "Can only return in registers!"); 981 982 SDValue Arg = SplitVals[realRVLocIdx]; 983 984 // Copied from other backends. 985 switch (VA.getLocInfo()) { 986 default: llvm_unreachable("Unknown loc info!"); 987 case CCValAssign::Full: 988 break; 989 case CCValAssign::BCvt: 990 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 991 break; 992 } 993 994 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 995 Flag = Chain.getValue(1); 996 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 997 } 998 999 // Update chain and glue. 1000 RetOps[0] = Chain; 1001 if (Flag.getNode()) 1002 RetOps.push_back(Flag); 1003 1004 return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, RetOps); 1005 } 1006 1007 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 1008 SelectionDAG &DAG) const { 1009 unsigned Reg = StringSwitch<unsigned>(RegName) 1010 .Case("m0", AMDGPU::M0) 1011 .Case("exec", AMDGPU::EXEC) 1012 .Case("exec_lo", AMDGPU::EXEC_LO) 1013 .Case("exec_hi", AMDGPU::EXEC_HI) 1014 .Case("flat_scratch", AMDGPU::FLAT_SCR) 1015 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 1016 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 1017 .Default(AMDGPU::NoRegister); 1018 1019 if (Reg == AMDGPU::NoRegister) { 1020 report_fatal_error(Twine("invalid register name \"" 1021 + StringRef(RegName) + "\".")); 1022 1023 } 1024 1025 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 1026 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 1027 report_fatal_error(Twine("invalid register \"" 1028 + StringRef(RegName) + "\" for subtarget.")); 1029 } 1030 1031 switch (Reg) { 1032 case AMDGPU::M0: 1033 case AMDGPU::EXEC_LO: 1034 case AMDGPU::EXEC_HI: 1035 case AMDGPU::FLAT_SCR_LO: 1036 case AMDGPU::FLAT_SCR_HI: 1037 if (VT.getSizeInBits() == 32) 1038 return Reg; 1039 break; 1040 case AMDGPU::EXEC: 1041 case AMDGPU::FLAT_SCR: 1042 if (VT.getSizeInBits() == 64) 1043 return Reg; 1044 break; 1045 default: 1046 llvm_unreachable("missing register type checking"); 1047 } 1048 1049 report_fatal_error(Twine("invalid type for register \"" 1050 + StringRef(RegName) + "\".")); 1051 } 1052 1053 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter( 1054 MachineInstr * MI, MachineBasicBlock * BB) const { 1055 1056 switch (MI->getOpcode()) { 1057 default: 1058 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 1059 case AMDGPU::BRANCH: 1060 return BB; 1061 } 1062 return BB; 1063 } 1064 1065 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1066 // This currently forces unfolding various combinations of fsub into fma with 1067 // free fneg'd operands. As long as we have fast FMA (controlled by 1068 // isFMAFasterThanFMulAndFAdd), we should perform these. 1069 1070 // When fma is quarter rate, for f64 where add / sub are at best half rate, 1071 // most of these combines appear to be cycle neutral but save on instruction 1072 // count / code size. 1073 return true; 1074 } 1075 1076 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 1077 EVT VT) const { 1078 if (!VT.isVector()) { 1079 return MVT::i1; 1080 } 1081 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 1082 } 1083 1084 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const { 1085 return MVT::i32; 1086 } 1087 1088 // Answering this is somewhat tricky and depends on the specific device which 1089 // have different rates for fma or all f64 operations. 1090 // 1091 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 1092 // regardless of which device (although the number of cycles differs between 1093 // devices), so it is always profitable for f64. 1094 // 1095 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 1096 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 1097 // which we can always do even without fused FP ops since it returns the same 1098 // result as the separate operations and since it is always full 1099 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 1100 // however does not support denormals, so we do report fma as faster if we have 1101 // a fast fma device and require denormals. 1102 // 1103 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 1104 VT = VT.getScalarType(); 1105 1106 if (!VT.isSimple()) 1107 return false; 1108 1109 switch (VT.getSimpleVT().SimpleTy) { 1110 case MVT::f32: 1111 // This is as fast on some subtargets. However, we always have full rate f32 1112 // mad available which returns the same result as the separate operations 1113 // which we should prefer over fma. We can't use this if we want to support 1114 // denormals, so only report this in these cases. 1115 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 1116 case MVT::f64: 1117 return true; 1118 default: 1119 break; 1120 } 1121 1122 return false; 1123 } 1124 1125 //===----------------------------------------------------------------------===// 1126 // Custom DAG Lowering Operations 1127 //===----------------------------------------------------------------------===// 1128 1129 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 1130 switch (Op.getOpcode()) { 1131 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 1132 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG); 1133 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 1134 case ISD::LOAD: { 1135 SDValue Result = LowerLOAD(Op, DAG); 1136 assert((!Result.getNode() || 1137 Result.getNode()->getNumValues() == 2) && 1138 "Load should return a value and a chain"); 1139 return Result; 1140 } 1141 1142 case ISD::FSIN: 1143 case ISD::FCOS: 1144 return LowerTrig(Op, DAG); 1145 case ISD::SELECT: return LowerSELECT(Op, DAG); 1146 case ISD::FDIV: return LowerFDIV(Op, DAG); 1147 case ISD::STORE: return LowerSTORE(Op, DAG); 1148 case ISD::GlobalAddress: { 1149 MachineFunction &MF = DAG.getMachineFunction(); 1150 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1151 return LowerGlobalAddress(MFI, Op, DAG); 1152 } 1153 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 1154 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 1155 } 1156 return SDValue(); 1157 } 1158 1159 /// \brief Helper function for LowerBRCOND 1160 static SDNode *findUser(SDValue Value, unsigned Opcode) { 1161 1162 SDNode *Parent = Value.getNode(); 1163 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 1164 I != E; ++I) { 1165 1166 if (I.getUse().get() != Value) 1167 continue; 1168 1169 if (I->getOpcode() == Opcode) 1170 return *I; 1171 } 1172 return nullptr; 1173 } 1174 1175 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const { 1176 1177 SDLoc SL(Op); 1178 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op); 1179 unsigned FrameIndex = FINode->getIndex(); 1180 1181 // A FrameIndex node represents a 32-bit offset into scratch memory. If the 1182 // high bit of a frame index offset were to be set, this would mean that it 1183 // represented an offset of ~2GB * 64 = ~128GB from the start of the scratch 1184 // buffer, with 64 being the number of threads per wave. 1185 // 1186 // The maximum private allocation for the entire GPU is 4G, and we are 1187 // concerned with the largest the index could ever be for an individual 1188 // workitem. This will occur with the minmum dispatch size. If a program 1189 // requires more, the dispatch size will be reduced. 1190 // 1191 // With this limit, we can mark the high bit of the FrameIndex node as known 1192 // zero, which is important, because it means in most situations we can prove 1193 // that values derived from FrameIndex nodes are non-negative. This enables us 1194 // to take advantage of more addressing modes when accessing scratch buffers, 1195 // since for scratch reads/writes, the register offset must always be 1196 // positive. 1197 1198 uint64_t MaxGPUAlloc = UINT64_C(4) * 1024 * 1024 * 1024; 1199 1200 // XXX - It is unclear if partial dispatch works. Assume it works at half wave 1201 // granularity. It is probably a full wave. 1202 uint64_t MinGranularity = 32; 1203 1204 unsigned KnownBits = Log2_64(MaxGPUAlloc / MinGranularity); 1205 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), KnownBits); 1206 1207 SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32); 1208 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI, 1209 DAG.getValueType(ExtVT)); 1210 } 1211 1212 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 1213 if (Intr->getOpcode() != ISD::INTRINSIC_W_CHAIN) 1214 return false; 1215 1216 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 1217 default: return false; 1218 case AMDGPUIntrinsic::amdgcn_if: 1219 case AMDGPUIntrinsic::amdgcn_else: 1220 case AMDGPUIntrinsic::amdgcn_break: 1221 case AMDGPUIntrinsic::amdgcn_if_break: 1222 case AMDGPUIntrinsic::amdgcn_else_break: 1223 case AMDGPUIntrinsic::amdgcn_loop: 1224 case AMDGPUIntrinsic::amdgcn_end_cf: 1225 return true; 1226 } 1227 } 1228 1229 /// This transforms the control flow intrinsics to get the branch destination as 1230 /// last parameter, also switches branch target with BR if the need arise 1231 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 1232 SelectionDAG &DAG) const { 1233 1234 SDLoc DL(BRCOND); 1235 1236 SDNode *Intr = BRCOND.getOperand(1).getNode(); 1237 SDValue Target = BRCOND.getOperand(2); 1238 SDNode *BR = nullptr; 1239 SDNode *SetCC = nullptr; 1240 1241 if (Intr->getOpcode() == ISD::SETCC) { 1242 // As long as we negate the condition everything is fine 1243 SetCC = Intr; 1244 Intr = SetCC->getOperand(0).getNode(); 1245 1246 } else { 1247 // Get the target from BR if we don't negate the condition 1248 BR = findUser(BRCOND, ISD::BR); 1249 Target = BR->getOperand(1); 1250 } 1251 1252 if (Intr->getOpcode() != ISD::INTRINSIC_W_CHAIN) { 1253 // This is a uniform branch so we don't need to legalize. 1254 return BRCOND; 1255 } 1256 1257 assert(!SetCC || 1258 (SetCC->getConstantOperandVal(1) == 1 && 1259 isCFIntrinsic(Intr) && 1260 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 1261 ISD::SETNE)); 1262 1263 // Build the result and 1264 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 1265 1266 // operands of the new intrinsic call 1267 SmallVector<SDValue, 4> Ops; 1268 Ops.push_back(BRCOND.getOperand(0)); 1269 Ops.append(Intr->op_begin() + 1, Intr->op_end()); 1270 Ops.push_back(Target); 1271 1272 // build the new intrinsic call 1273 SDNode *Result = DAG.getNode( 1274 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL, 1275 DAG.getVTList(Res), Ops).getNode(); 1276 1277 if (BR) { 1278 // Give the branch instruction our target 1279 SDValue Ops[] = { 1280 BR->getOperand(0), 1281 BRCOND.getOperand(2) 1282 }; 1283 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 1284 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 1285 BR = NewBR.getNode(); 1286 } 1287 1288 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 1289 1290 // Copy the intrinsic results to registers 1291 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 1292 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 1293 if (!CopyToReg) 1294 continue; 1295 1296 Chain = DAG.getCopyToReg( 1297 Chain, DL, 1298 CopyToReg->getOperand(1), 1299 SDValue(Result, i - 1), 1300 SDValue()); 1301 1302 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 1303 } 1304 1305 // Remove the old intrinsic from the chain 1306 DAG.ReplaceAllUsesOfValueWith( 1307 SDValue(Intr, Intr->getNumValues() - 1), 1308 Intr->getOperand(0)); 1309 1310 return Chain; 1311 } 1312 1313 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 1314 SDValue Op, 1315 SelectionDAG &DAG) const { 1316 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 1317 1318 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS) 1319 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 1320 1321 SDLoc DL(GSD); 1322 const GlobalValue *GV = GSD->getGlobal(); 1323 MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace()); 1324 1325 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32); 1326 return DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT, GA); 1327 } 1328 1329 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL, 1330 SDValue V) const { 1331 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 1332 // so we will end up with redundant moves to m0. 1333 // 1334 // We can't use S_MOV_B32, because there is no way to specify m0 as the 1335 // destination register. 1336 // 1337 // We have to use them both. Machine cse will combine all the S_MOV_B32 1338 // instructions and the register coalescer eliminate the extra copies. 1339 SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V); 1340 return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32), 1341 SDValue(M0, 0), SDValue()); // Glue 1342 // A Null SDValue creates 1343 // a glue result. 1344 } 1345 1346 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 1347 SDValue Op, 1348 MVT VT, 1349 unsigned Offset) const { 1350 SDLoc SL(Op); 1351 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL, 1352 DAG.getEntryNode(), Offset, false); 1353 // The local size values will have the hi 16-bits as zero. 1354 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 1355 DAG.getValueType(VT)); 1356 } 1357 1358 static SDValue emitNonHSAIntrinsicError(SelectionDAG& DAG, EVT VT) { 1359 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 1360 "non-hsa intrinsic with hsa target"); 1361 DAG.getContext()->diagnose(BadIntrin); 1362 return DAG.getUNDEF(VT); 1363 } 1364 1365 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 1366 SelectionDAG &DAG) const { 1367 MachineFunction &MF = DAG.getMachineFunction(); 1368 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 1369 const SIRegisterInfo *TRI = 1370 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo()); 1371 1372 EVT VT = Op.getValueType(); 1373 SDLoc DL(Op); 1374 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1375 1376 // TODO: Should this propagate fast-math-flags? 1377 1378 switch (IntrinsicID) { 1379 case Intrinsic::amdgcn_dispatch_ptr: 1380 if (!Subtarget->isAmdHsaOS()) { 1381 DiagnosticInfoUnsupported BadIntrin( 1382 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 1383 DL.getDebugLoc()); 1384 DAG.getContext()->diagnose(BadIntrin); 1385 return DAG.getUNDEF(VT); 1386 } 1387 1388 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, 1389 TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_PTR), VT); 1390 case Intrinsic::amdgcn_rcp: 1391 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 1392 case Intrinsic::amdgcn_rsq: 1393 case AMDGPUIntrinsic::AMDGPU_rsq: // Legacy name 1394 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 1395 case Intrinsic::amdgcn_rsq_clamp: 1396 case AMDGPUIntrinsic::AMDGPU_rsq_clamped: { // Legacy name 1397 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 1398 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 1399 1400 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 1401 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 1402 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 1403 1404 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 1405 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 1406 DAG.getConstantFP(Max, DL, VT)); 1407 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 1408 DAG.getConstantFP(Min, DL, VT)); 1409 } 1410 case Intrinsic::r600_read_ngroups_x: 1411 if (Subtarget->isAmdHsaOS()) 1412 return emitNonHSAIntrinsicError(DAG, VT); 1413 1414 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1415 SI::KernelInputOffsets::NGROUPS_X, false); 1416 case Intrinsic::r600_read_ngroups_y: 1417 if (Subtarget->isAmdHsaOS()) 1418 return emitNonHSAIntrinsicError(DAG, VT); 1419 1420 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1421 SI::KernelInputOffsets::NGROUPS_Y, false); 1422 case Intrinsic::r600_read_ngroups_z: 1423 if (Subtarget->isAmdHsaOS()) 1424 return emitNonHSAIntrinsicError(DAG, VT); 1425 1426 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1427 SI::KernelInputOffsets::NGROUPS_Z, false); 1428 case Intrinsic::r600_read_global_size_x: 1429 if (Subtarget->isAmdHsaOS()) 1430 return emitNonHSAIntrinsicError(DAG, VT); 1431 1432 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1433 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 1434 case Intrinsic::r600_read_global_size_y: 1435 if (Subtarget->isAmdHsaOS()) 1436 return emitNonHSAIntrinsicError(DAG, VT); 1437 1438 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1439 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 1440 case Intrinsic::r600_read_global_size_z: 1441 if (Subtarget->isAmdHsaOS()) 1442 return emitNonHSAIntrinsicError(DAG, VT); 1443 1444 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1445 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 1446 case Intrinsic::r600_read_local_size_x: 1447 if (Subtarget->isAmdHsaOS()) 1448 return emitNonHSAIntrinsicError(DAG, VT); 1449 1450 return lowerImplicitZextParam(DAG, Op, MVT::i16, 1451 SI::KernelInputOffsets::LOCAL_SIZE_X); 1452 case Intrinsic::r600_read_local_size_y: 1453 if (Subtarget->isAmdHsaOS()) 1454 return emitNonHSAIntrinsicError(DAG, VT); 1455 1456 return lowerImplicitZextParam(DAG, Op, MVT::i16, 1457 SI::KernelInputOffsets::LOCAL_SIZE_Y); 1458 case Intrinsic::r600_read_local_size_z: 1459 if (Subtarget->isAmdHsaOS()) 1460 return emitNonHSAIntrinsicError(DAG, VT); 1461 1462 return lowerImplicitZextParam(DAG, Op, MVT::i16, 1463 SI::KernelInputOffsets::LOCAL_SIZE_Z); 1464 case Intrinsic::amdgcn_read_workdim: 1465 case AMDGPUIntrinsic::AMDGPU_read_workdim: // Legacy name. 1466 // Really only 2 bits. 1467 return lowerImplicitZextParam(DAG, Op, MVT::i8, 1468 getImplicitParameterOffset(MFI, GRID_DIM)); 1469 case Intrinsic::amdgcn_workgroup_id_x: 1470 case Intrinsic::r600_read_tgid_x: 1471 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 1472 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT); 1473 case Intrinsic::amdgcn_workgroup_id_y: 1474 case Intrinsic::r600_read_tgid_y: 1475 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 1476 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT); 1477 case Intrinsic::amdgcn_workgroup_id_z: 1478 case Intrinsic::r600_read_tgid_z: 1479 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 1480 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT); 1481 case Intrinsic::amdgcn_workitem_id_x: 1482 case Intrinsic::r600_read_tidig_x: 1483 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 1484 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT); 1485 case Intrinsic::amdgcn_workitem_id_y: 1486 case Intrinsic::r600_read_tidig_y: 1487 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 1488 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT); 1489 case Intrinsic::amdgcn_workitem_id_z: 1490 case Intrinsic::r600_read_tidig_z: 1491 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 1492 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT); 1493 case AMDGPUIntrinsic::SI_load_const: { 1494 SDValue Ops[] = { 1495 Op.getOperand(1), 1496 Op.getOperand(2) 1497 }; 1498 1499 MachineMemOperand *MMO = MF.getMachineMemOperand( 1500 MachinePointerInfo(), 1501 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant, 1502 VT.getStoreSize(), 4); 1503 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 1504 Op->getVTList(), Ops, VT, MMO); 1505 } 1506 case AMDGPUIntrinsic::SI_vs_load_input: 1507 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT, 1508 Op.getOperand(1), 1509 Op.getOperand(2), 1510 Op.getOperand(3)); 1511 1512 case AMDGPUIntrinsic::SI_fs_constant: { 1513 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3)); 1514 SDValue Glue = M0.getValue(1); 1515 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 1516 DAG.getConstant(2, DL, MVT::i32), // P0 1517 Op.getOperand(1), Op.getOperand(2), Glue); 1518 } 1519 case AMDGPUIntrinsic::SI_packf16: 1520 if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef()) 1521 return DAG.getUNDEF(MVT::i32); 1522 return Op; 1523 case AMDGPUIntrinsic::SI_fs_interp: { 1524 SDValue IJ = Op.getOperand(4); 1525 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ, 1526 DAG.getConstant(0, DL, MVT::i32)); 1527 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ, 1528 DAG.getConstant(1, DL, MVT::i32)); 1529 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3)); 1530 SDValue Glue = M0.getValue(1); 1531 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL, 1532 DAG.getVTList(MVT::f32, MVT::Glue), 1533 I, Op.getOperand(1), Op.getOperand(2), Glue); 1534 Glue = SDValue(P1.getNode(), 1); 1535 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J, 1536 Op.getOperand(1), Op.getOperand(2), Glue); 1537 } 1538 case Intrinsic::amdgcn_interp_p1: { 1539 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 1540 SDValue Glue = M0.getValue(1); 1541 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 1542 Op.getOperand(2), Op.getOperand(3), Glue); 1543 } 1544 case Intrinsic::amdgcn_interp_p2: { 1545 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 1546 SDValue Glue = SDValue(M0.getNode(), 1); 1547 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 1548 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 1549 Glue); 1550 } 1551 case Intrinsic::amdgcn_sin: 1552 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 1553 1554 case Intrinsic::amdgcn_cos: 1555 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 1556 1557 case Intrinsic::amdgcn_log_clamp: { 1558 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 1559 return SDValue(); 1560 1561 DiagnosticInfoUnsupported BadIntrin( 1562 *MF.getFunction(), "intrinsic not supported on subtarget", 1563 DL.getDebugLoc()); 1564 DAG.getContext()->diagnose(BadIntrin); 1565 return DAG.getUNDEF(VT); 1566 } 1567 case Intrinsic::amdgcn_ldexp: 1568 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 1569 Op.getOperand(1), Op.getOperand(2)); 1570 case Intrinsic::amdgcn_class: 1571 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 1572 Op.getOperand(1), Op.getOperand(2)); 1573 case Intrinsic::amdgcn_div_fmas: 1574 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 1575 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 1576 Op.getOperand(4)); 1577 1578 case Intrinsic::amdgcn_div_fixup: 1579 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 1580 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 1581 1582 case Intrinsic::amdgcn_trig_preop: 1583 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 1584 Op.getOperand(1), Op.getOperand(2)); 1585 case Intrinsic::amdgcn_div_scale: { 1586 // 3rd parameter required to be a constant. 1587 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 1588 if (!Param) 1589 return DAG.getUNDEF(VT); 1590 1591 // Translate to the operands expected by the machine instruction. The 1592 // first parameter must be the same as the first instruction. 1593 SDValue Numerator = Op.getOperand(1); 1594 SDValue Denominator = Op.getOperand(2); 1595 1596 // Note this order is opposite of the machine instruction's operations, 1597 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 1598 // intrinsic has the numerator as the first operand to match a normal 1599 // division operation. 1600 1601 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 1602 1603 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 1604 Denominator, Numerator); 1605 } 1606 case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte0: 1607 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Op.getOperand(1)); 1608 case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte1: 1609 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE1, DL, VT, Op.getOperand(1)); 1610 case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte2: 1611 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE2, DL, VT, Op.getOperand(1)); 1612 case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte3: 1613 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE3, DL, VT, Op.getOperand(1)); 1614 default: 1615 return AMDGPUTargetLowering::LowerOperation(Op, DAG); 1616 } 1617 } 1618 1619 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 1620 SelectionDAG &DAG) const { 1621 MachineFunction &MF = DAG.getMachineFunction(); 1622 SDLoc DL(Op); 1623 SDValue Chain = Op.getOperand(0); 1624 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 1625 1626 switch (IntrinsicID) { 1627 case AMDGPUIntrinsic::SI_sendmsg: { 1628 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 1629 SDValue Glue = Chain.getValue(1); 1630 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain, 1631 Op.getOperand(2), Glue); 1632 } 1633 case AMDGPUIntrinsic::SI_tbuffer_store: { 1634 SDValue Ops[] = { 1635 Chain, 1636 Op.getOperand(2), 1637 Op.getOperand(3), 1638 Op.getOperand(4), 1639 Op.getOperand(5), 1640 Op.getOperand(6), 1641 Op.getOperand(7), 1642 Op.getOperand(8), 1643 Op.getOperand(9), 1644 Op.getOperand(10), 1645 Op.getOperand(11), 1646 Op.getOperand(12), 1647 Op.getOperand(13), 1648 Op.getOperand(14) 1649 }; 1650 1651 EVT VT = Op.getOperand(3).getValueType(); 1652 1653 MachineMemOperand *MMO = MF.getMachineMemOperand( 1654 MachinePointerInfo(), 1655 MachineMemOperand::MOStore, 1656 VT.getStoreSize(), 4); 1657 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 1658 Op->getVTList(), Ops, VT, MMO); 1659 } 1660 default: 1661 return SDValue(); 1662 } 1663 } 1664 1665 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 1666 SDLoc DL(Op); 1667 LoadSDNode *Load = cast<LoadSDNode>(Op); 1668 ISD::LoadExtType ExtType = Load->getExtensionType(); 1669 EVT MemVT = Load->getMemoryVT(); 1670 1671 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 1672 assert(MemVT == MVT::i1 && "Only i1 non-extloads expected"); 1673 // FIXME: Copied from PPC 1674 // First, load into 32 bits, then truncate to 1 bit. 1675 1676 SDValue Chain = Load->getChain(); 1677 SDValue BasePtr = Load->getBasePtr(); 1678 MachineMemOperand *MMO = Load->getMemOperand(); 1679 1680 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 1681 BasePtr, MVT::i8, MMO); 1682 1683 SDValue Ops[] = { 1684 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 1685 NewLD.getValue(1) 1686 }; 1687 1688 return DAG.getMergeValues(Ops, DL); 1689 } 1690 1691 if (!MemVT.isVector()) 1692 return SDValue(); 1693 1694 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 1695 "Custom lowering for non-i32 vectors hasn't been implemented."); 1696 unsigned NumElements = MemVT.getVectorNumElements(); 1697 assert(NumElements != 2 && "v2 loads are supported for all address spaces."); 1698 1699 switch (Load->getAddressSpace()) { 1700 case AMDGPUAS::CONSTANT_ADDRESS: 1701 if (isMemOpUniform(Load)) 1702 return SDValue(); 1703 // Non-uniform loads will be selected to MUBUF instructions, so they 1704 // have the same legalization requires ments as global and private 1705 // loads. 1706 // 1707 // Fall-through 1708 case AMDGPUAS::GLOBAL_ADDRESS: 1709 case AMDGPUAS::FLAT_ADDRESS: 1710 if (NumElements > 4) 1711 return SplitVectorLoad(Op, DAG); 1712 // v4 loads are supported for private and global memory. 1713 return SDValue(); 1714 case AMDGPUAS::PRIVATE_ADDRESS: { 1715 // Depending on the setting of the private_element_size field in the 1716 // resource descriptor, we can only make private accesses up to a certain 1717 // size. 1718 switch (Subtarget->getMaxPrivateElementSize()) { 1719 case 4: 1720 return ScalarizeVectorLoad(Op, DAG); 1721 case 8: 1722 if (NumElements > 2) 1723 return SplitVectorLoad(Op, DAG); 1724 return SDValue(); 1725 case 16: 1726 // Same as global/flat 1727 if (NumElements > 4) 1728 return SplitVectorLoad(Op, DAG); 1729 return SDValue(); 1730 default: 1731 llvm_unreachable("unsupported private_element_size"); 1732 } 1733 } 1734 case AMDGPUAS::LOCAL_ADDRESS: 1735 // If properly aligned, if we split we might be able to use ds_read_b64. 1736 return SplitVectorLoad(Op, DAG); 1737 default: 1738 return SDValue(); 1739 } 1740 } 1741 1742 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 1743 if (Op.getValueType() != MVT::i64) 1744 return SDValue(); 1745 1746 SDLoc DL(Op); 1747 SDValue Cond = Op.getOperand(0); 1748 1749 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 1750 SDValue One = DAG.getConstant(1, DL, MVT::i32); 1751 1752 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 1753 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 1754 1755 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 1756 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 1757 1758 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 1759 1760 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 1761 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 1762 1763 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 1764 1765 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi); 1766 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 1767 } 1768 1769 // Catch division cases where we can use shortcuts with rcp and rsq 1770 // instructions. 1771 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const { 1772 SDLoc SL(Op); 1773 SDValue LHS = Op.getOperand(0); 1774 SDValue RHS = Op.getOperand(1); 1775 EVT VT = Op.getValueType(); 1776 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath; 1777 1778 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 1779 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) && 1780 CLHS->isExactlyValue(1.0)) { 1781 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 1782 // the CI documentation has a worst case error of 1 ulp. 1783 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 1784 // use it as long as we aren't trying to use denormals. 1785 1786 // 1.0 / sqrt(x) -> rsq(x) 1787 // 1788 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 1789 // error seems really high at 2^29 ULP. 1790 if (RHS.getOpcode() == ISD::FSQRT) 1791 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 1792 1793 // 1.0 / x -> rcp(x) 1794 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 1795 } 1796 } 1797 1798 if (Unsafe) { 1799 // Turn into multiply by the reciprocal. 1800 // x / y -> x * (1.0 / y) 1801 SDNodeFlags Flags; 1802 Flags.setUnsafeAlgebra(true); 1803 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 1804 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags); 1805 } 1806 1807 return SDValue(); 1808 } 1809 1810 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 1811 if (SDValue FastLowered = LowerFastFDIV(Op, DAG)) 1812 return FastLowered; 1813 1814 // This uses v_rcp_f32 which does not handle denormals. Let this hit a 1815 // selection error for now rather than do something incorrect. 1816 if (Subtarget->hasFP32Denormals()) 1817 return SDValue(); 1818 1819 SDLoc SL(Op); 1820 SDValue LHS = Op.getOperand(0); 1821 SDValue RHS = Op.getOperand(1); 1822 1823 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 1824 1825 const APFloat K0Val(BitsToFloat(0x6f800000)); 1826 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 1827 1828 const APFloat K1Val(BitsToFloat(0x2f800000)); 1829 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 1830 1831 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 1832 1833 EVT SetCCVT = 1834 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 1835 1836 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 1837 1838 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 1839 1840 // TODO: Should this propagate fast-math-flags? 1841 1842 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 1843 1844 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 1845 1846 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 1847 1848 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 1849 } 1850 1851 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 1852 if (DAG.getTarget().Options.UnsafeFPMath) 1853 return LowerFastFDIV(Op, DAG); 1854 1855 SDLoc SL(Op); 1856 SDValue X = Op.getOperand(0); 1857 SDValue Y = Op.getOperand(1); 1858 1859 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 1860 1861 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 1862 1863 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 1864 1865 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 1866 1867 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 1868 1869 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 1870 1871 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 1872 1873 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 1874 1875 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 1876 1877 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 1878 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 1879 1880 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 1881 NegDivScale0, Mul, DivScale1); 1882 1883 SDValue Scale; 1884 1885 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1886 // Workaround a hardware bug on SI where the condition output from div_scale 1887 // is not usable. 1888 1889 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 1890 1891 // Figure out if the scale to use for div_fmas. 1892 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 1893 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 1894 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 1895 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 1896 1897 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 1898 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 1899 1900 SDValue Scale0Hi 1901 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 1902 SDValue Scale1Hi 1903 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 1904 1905 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 1906 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 1907 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 1908 } else { 1909 Scale = DivScale1.getValue(1); 1910 } 1911 1912 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 1913 Fma4, Fma3, Mul, Scale); 1914 1915 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 1916 } 1917 1918 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 1919 EVT VT = Op.getValueType(); 1920 1921 if (VT == MVT::f32) 1922 return LowerFDIV32(Op, DAG); 1923 1924 if (VT == MVT::f64) 1925 return LowerFDIV64(Op, DAG); 1926 1927 llvm_unreachable("Unexpected type for fdiv"); 1928 } 1929 1930 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 1931 SDLoc DL(Op); 1932 StoreSDNode *Store = cast<StoreSDNode>(Op); 1933 EVT VT = Store->getMemoryVT(); 1934 1935 if (VT == MVT::i1) { 1936 return DAG.getTruncStore(Store->getChain(), DL, 1937 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 1938 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 1939 } 1940 1941 assert(Store->getValue().getValueType().getScalarType() == MVT::i32); 1942 1943 unsigned NumElements = VT.getVectorNumElements(); 1944 switch (Store->getAddressSpace()) { 1945 case AMDGPUAS::GLOBAL_ADDRESS: 1946 case AMDGPUAS::FLAT_ADDRESS: 1947 if (NumElements > 4) 1948 return SplitVectorStore(Op, DAG); 1949 return SDValue(); 1950 case AMDGPUAS::PRIVATE_ADDRESS: { 1951 switch (Subtarget->getMaxPrivateElementSize()) { 1952 case 4: 1953 return ScalarizeVectorStore(Op, DAG); 1954 case 8: 1955 if (NumElements > 2) 1956 return SplitVectorStore(Op, DAG); 1957 return SDValue(); 1958 case 16: 1959 if (NumElements > 4) 1960 return SplitVectorStore(Op, DAG); 1961 return SDValue(); 1962 default: 1963 llvm_unreachable("unsupported private_element_size"); 1964 } 1965 } 1966 case AMDGPUAS::LOCAL_ADDRESS: 1967 // If properly aligned, if we split we might be able to use ds_write_b64. 1968 return SplitVectorStore(Op, DAG); 1969 default: 1970 llvm_unreachable("unhandled address space"); 1971 } 1972 } 1973 1974 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 1975 SDLoc DL(Op); 1976 EVT VT = Op.getValueType(); 1977 SDValue Arg = Op.getOperand(0); 1978 // TODO: Should this propagate fast-math-flags? 1979 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 1980 DAG.getNode(ISD::FMUL, DL, VT, Arg, 1981 DAG.getConstantFP(0.5/M_PI, DL, 1982 VT))); 1983 1984 switch (Op.getOpcode()) { 1985 case ISD::FCOS: 1986 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 1987 case ISD::FSIN: 1988 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 1989 default: 1990 llvm_unreachable("Wrong trig opcode"); 1991 } 1992 } 1993 1994 //===----------------------------------------------------------------------===// 1995 // Custom DAG optimizations 1996 //===----------------------------------------------------------------------===// 1997 1998 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 1999 DAGCombinerInfo &DCI) const { 2000 EVT VT = N->getValueType(0); 2001 EVT ScalarVT = VT.getScalarType(); 2002 if (ScalarVT != MVT::f32) 2003 return SDValue(); 2004 2005 SelectionDAG &DAG = DCI.DAG; 2006 SDLoc DL(N); 2007 2008 SDValue Src = N->getOperand(0); 2009 EVT SrcVT = Src.getValueType(); 2010 2011 // TODO: We could try to match extracting the higher bytes, which would be 2012 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 2013 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 2014 // about in practice. 2015 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 2016 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 2017 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 2018 DCI.AddToWorklist(Cvt.getNode()); 2019 return Cvt; 2020 } 2021 } 2022 2023 // We are primarily trying to catch operations on illegal vector types 2024 // before they are expanded. 2025 // For scalars, we can use the more flexible method of checking masked bits 2026 // after legalization. 2027 if (!DCI.isBeforeLegalize() || 2028 !SrcVT.isVector() || 2029 SrcVT.getVectorElementType() != MVT::i8) { 2030 return SDValue(); 2031 } 2032 2033 assert(DCI.isBeforeLegalize() && "Unexpected legal type"); 2034 2035 // Weird sized vectors are a pain to handle, but we know 3 is really the same 2036 // size as 4. 2037 unsigned NElts = SrcVT.getVectorNumElements(); 2038 if (!SrcVT.isSimple() && NElts != 3) 2039 return SDValue(); 2040 2041 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to 2042 // prevent a mess from expanding to v4i32 and repacking. 2043 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) { 2044 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT); 2045 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT); 2046 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts); 2047 LoadSDNode *Load = cast<LoadSDNode>(Src); 2048 2049 unsigned AS = Load->getAddressSpace(); 2050 unsigned Align = Load->getAlignment(); 2051 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext()); 2052 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 2053 2054 // Don't try to replace the load if we have to expand it due to alignment 2055 // problems. Otherwise we will end up scalarizing the load, and trying to 2056 // repack into the vector for no real reason. 2057 if (Align < ABIAlignment && 2058 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) { 2059 return SDValue(); 2060 } 2061 2062 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT, 2063 Load->getChain(), 2064 Load->getBasePtr(), 2065 LoadVT, 2066 Load->getMemOperand()); 2067 2068 // Make sure successors of the original load stay after it by updating 2069 // them to use the new Chain. 2070 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1)); 2071 2072 SmallVector<SDValue, 4> Elts; 2073 if (RegVT.isVector()) 2074 DAG.ExtractVectorElements(NewLoad, Elts); 2075 else 2076 Elts.push_back(NewLoad); 2077 2078 SmallVector<SDValue, 4> Ops; 2079 2080 unsigned EltIdx = 0; 2081 for (SDValue Elt : Elts) { 2082 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx); 2083 for (unsigned I = 0; I < ComponentsInElt; ++I) { 2084 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I; 2085 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt); 2086 DCI.AddToWorklist(Cvt.getNode()); 2087 Ops.push_back(Cvt); 2088 } 2089 2090 ++EltIdx; 2091 } 2092 2093 assert(Ops.size() == NElts); 2094 2095 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops); 2096 } 2097 2098 return SDValue(); 2099 } 2100 2101 /// \brief Return true if the given offset Size in bytes can be folded into 2102 /// the immediate offsets of a memory instruction for the given address space. 2103 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 2104 const AMDGPUSubtarget &STI) { 2105 switch (AS) { 2106 case AMDGPUAS::GLOBAL_ADDRESS: { 2107 // MUBUF instructions a 12-bit offset in bytes. 2108 return isUInt<12>(OffsetSize); 2109 } 2110 case AMDGPUAS::CONSTANT_ADDRESS: { 2111 // SMRD instructions have an 8-bit offset in dwords on SI and 2112 // a 20-bit offset in bytes on VI. 2113 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 2114 return isUInt<20>(OffsetSize); 2115 else 2116 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 2117 } 2118 case AMDGPUAS::LOCAL_ADDRESS: 2119 case AMDGPUAS::REGION_ADDRESS: { 2120 // The single offset versions have a 16-bit offset in bytes. 2121 return isUInt<16>(OffsetSize); 2122 } 2123 case AMDGPUAS::PRIVATE_ADDRESS: 2124 // Indirect register addressing does not use any offsets. 2125 default: 2126 return 0; 2127 } 2128 } 2129 2130 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 2131 2132 // This is a variant of 2133 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 2134 // 2135 // The normal DAG combiner will do this, but only if the add has one use since 2136 // that would increase the number of instructions. 2137 // 2138 // This prevents us from seeing a constant offset that can be folded into a 2139 // memory instruction's addressing mode. If we know the resulting add offset of 2140 // a pointer can be folded into an addressing offset, we can replace the pointer 2141 // operand with the add of new constant offset. This eliminates one of the uses, 2142 // and may allow the remaining use to also be simplified. 2143 // 2144 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 2145 unsigned AddrSpace, 2146 DAGCombinerInfo &DCI) const { 2147 SDValue N0 = N->getOperand(0); 2148 SDValue N1 = N->getOperand(1); 2149 2150 if (N0.getOpcode() != ISD::ADD) 2151 return SDValue(); 2152 2153 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 2154 if (!CN1) 2155 return SDValue(); 2156 2157 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2158 if (!CAdd) 2159 return SDValue(); 2160 2161 // If the resulting offset is too large, we can't fold it into the addressing 2162 // mode offset. 2163 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 2164 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget)) 2165 return SDValue(); 2166 2167 SelectionDAG &DAG = DCI.DAG; 2168 SDLoc SL(N); 2169 EVT VT = N->getValueType(0); 2170 2171 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 2172 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 2173 2174 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 2175 } 2176 2177 SDValue SITargetLowering::performAndCombine(SDNode *N, 2178 DAGCombinerInfo &DCI) const { 2179 if (DCI.isBeforeLegalize()) 2180 return SDValue(); 2181 2182 if (SDValue Base = AMDGPUTargetLowering::performAndCombine(N, DCI)) 2183 return Base; 2184 2185 SelectionDAG &DAG = DCI.DAG; 2186 2187 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 2188 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 2189 SDValue LHS = N->getOperand(0); 2190 SDValue RHS = N->getOperand(1); 2191 2192 if (LHS.getOpcode() == ISD::SETCC && 2193 RHS.getOpcode() == ISD::SETCC) { 2194 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 2195 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 2196 2197 SDValue X = LHS.getOperand(0); 2198 SDValue Y = RHS.getOperand(0); 2199 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 2200 return SDValue(); 2201 2202 if (LCC == ISD::SETO) { 2203 if (X != LHS.getOperand(1)) 2204 return SDValue(); 2205 2206 if (RCC == ISD::SETUNE) { 2207 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 2208 if (!C1 || !C1->isInfinity() || C1->isNegative()) 2209 return SDValue(); 2210 2211 const uint32_t Mask = SIInstrFlags::N_NORMAL | 2212 SIInstrFlags::N_SUBNORMAL | 2213 SIInstrFlags::N_ZERO | 2214 SIInstrFlags::P_ZERO | 2215 SIInstrFlags::P_SUBNORMAL | 2216 SIInstrFlags::P_NORMAL; 2217 2218 static_assert(((~(SIInstrFlags::S_NAN | 2219 SIInstrFlags::Q_NAN | 2220 SIInstrFlags::N_INFINITY | 2221 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 2222 "mask not equal"); 2223 2224 SDLoc DL(N); 2225 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 2226 X, DAG.getConstant(Mask, DL, MVT::i32)); 2227 } 2228 } 2229 } 2230 2231 return SDValue(); 2232 } 2233 2234 SDValue SITargetLowering::performOrCombine(SDNode *N, 2235 DAGCombinerInfo &DCI) const { 2236 SelectionDAG &DAG = DCI.DAG; 2237 SDValue LHS = N->getOperand(0); 2238 SDValue RHS = N->getOperand(1); 2239 2240 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 2241 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 2242 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 2243 SDValue Src = LHS.getOperand(0); 2244 if (Src != RHS.getOperand(0)) 2245 return SDValue(); 2246 2247 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 2248 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 2249 if (!CLHS || !CRHS) 2250 return SDValue(); 2251 2252 // Only 10 bits are used. 2253 static const uint32_t MaxMask = 0x3ff; 2254 2255 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 2256 SDLoc DL(N); 2257 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 2258 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 2259 } 2260 2261 return SDValue(); 2262 } 2263 2264 SDValue SITargetLowering::performClassCombine(SDNode *N, 2265 DAGCombinerInfo &DCI) const { 2266 SelectionDAG &DAG = DCI.DAG; 2267 SDValue Mask = N->getOperand(1); 2268 2269 // fp_class x, 0 -> false 2270 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 2271 if (CMask->isNullValue()) 2272 return DAG.getConstant(0, SDLoc(N), MVT::i1); 2273 } 2274 2275 return SDValue(); 2276 } 2277 2278 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 2279 switch (Opc) { 2280 case ISD::FMAXNUM: 2281 return AMDGPUISD::FMAX3; 2282 case ISD::SMAX: 2283 return AMDGPUISD::SMAX3; 2284 case ISD::UMAX: 2285 return AMDGPUISD::UMAX3; 2286 case ISD::FMINNUM: 2287 return AMDGPUISD::FMIN3; 2288 case ISD::SMIN: 2289 return AMDGPUISD::SMIN3; 2290 case ISD::UMIN: 2291 return AMDGPUISD::UMIN3; 2292 default: 2293 llvm_unreachable("Not a min/max opcode"); 2294 } 2295 } 2296 2297 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG, 2298 SDLoc SL, 2299 SDValue Op0, 2300 SDValue Op1, 2301 bool Signed) { 2302 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 2303 if (!K1) 2304 return SDValue(); 2305 2306 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 2307 if (!K0) 2308 return SDValue(); 2309 2310 2311 if (Signed) { 2312 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 2313 return SDValue(); 2314 } else { 2315 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 2316 return SDValue(); 2317 } 2318 2319 EVT VT = K0->getValueType(0); 2320 return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT, 2321 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 2322 } 2323 2324 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 2325 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 2326 return true; 2327 2328 return DAG.isKnownNeverNaN(Op); 2329 } 2330 2331 static SDValue performFPMed3ImmCombine(SelectionDAG &DAG, 2332 SDLoc SL, 2333 SDValue Op0, 2334 SDValue Op1) { 2335 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1); 2336 if (!K1) 2337 return SDValue(); 2338 2339 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1)); 2340 if (!K0) 2341 return SDValue(); 2342 2343 // Ordered >= (although NaN inputs should have folded away by now). 2344 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 2345 if (Cmp == APFloat::cmpGreaterThan) 2346 return SDValue(); 2347 2348 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 2349 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then 2350 // give the other result, which is different from med3 with a NaN input. 2351 SDValue Var = Op0.getOperand(0); 2352 if (!isKnownNeverSNan(DAG, Var)) 2353 return SDValue(); 2354 2355 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 2356 Var, SDValue(K0, 0), SDValue(K1, 0)); 2357 } 2358 2359 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 2360 DAGCombinerInfo &DCI) const { 2361 SelectionDAG &DAG = DCI.DAG; 2362 2363 unsigned Opc = N->getOpcode(); 2364 SDValue Op0 = N->getOperand(0); 2365 SDValue Op1 = N->getOperand(1); 2366 2367 // Only do this if the inner op has one use since this will just increases 2368 // register pressure for no benefit. 2369 2370 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY) { 2371 // max(max(a, b), c) -> max3(a, b, c) 2372 // min(min(a, b), c) -> min3(a, b, c) 2373 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 2374 SDLoc DL(N); 2375 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 2376 DL, 2377 N->getValueType(0), 2378 Op0.getOperand(0), 2379 Op0.getOperand(1), 2380 Op1); 2381 } 2382 2383 // Try commuted. 2384 // max(a, max(b, c)) -> max3(a, b, c) 2385 // min(a, min(b, c)) -> min3(a, b, c) 2386 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 2387 SDLoc DL(N); 2388 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 2389 DL, 2390 N->getValueType(0), 2391 Op0, 2392 Op1.getOperand(0), 2393 Op1.getOperand(1)); 2394 } 2395 } 2396 2397 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 2398 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 2399 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 2400 return Med3; 2401 } 2402 2403 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 2404 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 2405 return Med3; 2406 } 2407 2408 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 2409 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 2410 (Opc == AMDGPUISD::FMIN_LEGACY && 2411 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 2412 N->getValueType(0) == MVT::f32 && Op0.hasOneUse()) { 2413 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 2414 return Res; 2415 } 2416 2417 return SDValue(); 2418 } 2419 2420 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 2421 DAGCombinerInfo &DCI) const { 2422 SelectionDAG &DAG = DCI.DAG; 2423 SDLoc SL(N); 2424 2425 SDValue LHS = N->getOperand(0); 2426 SDValue RHS = N->getOperand(1); 2427 EVT VT = LHS.getValueType(); 2428 2429 if (VT != MVT::f32 && VT != MVT::f64) 2430 return SDValue(); 2431 2432 // Match isinf pattern 2433 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 2434 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 2435 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 2436 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 2437 if (!CRHS) 2438 return SDValue(); 2439 2440 const APFloat &APF = CRHS->getValueAPF(); 2441 if (APF.isInfinity() && !APF.isNegative()) { 2442 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 2443 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 2444 DAG.getConstant(Mask, SL, MVT::i32)); 2445 } 2446 } 2447 2448 return SDValue(); 2449 } 2450 2451 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 2452 DAGCombinerInfo &DCI) const { 2453 SelectionDAG &DAG = DCI.DAG; 2454 SDLoc DL(N); 2455 2456 switch (N->getOpcode()) { 2457 default: 2458 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 2459 case ISD::SETCC: 2460 return performSetCCCombine(N, DCI); 2461 case ISD::FMAXNUM: 2462 case ISD::FMINNUM: 2463 case ISD::SMAX: 2464 case ISD::SMIN: 2465 case ISD::UMAX: 2466 case ISD::UMIN: 2467 case AMDGPUISD::FMIN_LEGACY: 2468 case AMDGPUISD::FMAX_LEGACY: { 2469 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 2470 N->getValueType(0) != MVT::f64 && 2471 getTargetMachine().getOptLevel() > CodeGenOpt::None) 2472 return performMinMaxCombine(N, DCI); 2473 break; 2474 } 2475 2476 case AMDGPUISD::CVT_F32_UBYTE0: 2477 case AMDGPUISD::CVT_F32_UBYTE1: 2478 case AMDGPUISD::CVT_F32_UBYTE2: 2479 case AMDGPUISD::CVT_F32_UBYTE3: { 2480 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 2481 2482 SDValue Src = N->getOperand(0); 2483 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 2484 2485 APInt KnownZero, KnownOne; 2486 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2487 !DCI.isBeforeLegalizeOps()); 2488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2489 if (TLO.ShrinkDemandedConstant(Src, Demanded) || 2490 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) { 2491 DCI.CommitTargetLoweringOpt(TLO); 2492 } 2493 2494 break; 2495 } 2496 2497 case ISD::UINT_TO_FP: { 2498 return performUCharToFloatCombine(N, DCI); 2499 } 2500 case ISD::FADD: { 2501 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 2502 break; 2503 2504 EVT VT = N->getValueType(0); 2505 if (VT != MVT::f32) 2506 break; 2507 2508 // Only do this if we are not trying to support denormals. v_mad_f32 does 2509 // not support denormals ever. 2510 if (Subtarget->hasFP32Denormals()) 2511 break; 2512 2513 SDValue LHS = N->getOperand(0); 2514 SDValue RHS = N->getOperand(1); 2515 2516 // These should really be instruction patterns, but writing patterns with 2517 // source modiifiers is a pain. 2518 2519 // fadd (fadd (a, a), b) -> mad 2.0, a, b 2520 if (LHS.getOpcode() == ISD::FADD) { 2521 SDValue A = LHS.getOperand(0); 2522 if (A == LHS.getOperand(1)) { 2523 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 2524 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS); 2525 } 2526 } 2527 2528 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 2529 if (RHS.getOpcode() == ISD::FADD) { 2530 SDValue A = RHS.getOperand(0); 2531 if (A == RHS.getOperand(1)) { 2532 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 2533 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS); 2534 } 2535 } 2536 2537 return SDValue(); 2538 } 2539 case ISD::FSUB: { 2540 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 2541 break; 2542 2543 EVT VT = N->getValueType(0); 2544 2545 // Try to get the fneg to fold into the source modifier. This undoes generic 2546 // DAG combines and folds them into the mad. 2547 // 2548 // Only do this if we are not trying to support denormals. v_mad_f32 does 2549 // not support denormals ever. 2550 if (VT == MVT::f32 && 2551 !Subtarget->hasFP32Denormals()) { 2552 SDValue LHS = N->getOperand(0); 2553 SDValue RHS = N->getOperand(1); 2554 if (LHS.getOpcode() == ISD::FADD) { 2555 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 2556 2557 SDValue A = LHS.getOperand(0); 2558 if (A == LHS.getOperand(1)) { 2559 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 2560 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS); 2561 2562 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS); 2563 } 2564 } 2565 2566 if (RHS.getOpcode() == ISD::FADD) { 2567 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 2568 2569 SDValue A = RHS.getOperand(0); 2570 if (A == RHS.getOperand(1)) { 2571 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32); 2572 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS); 2573 } 2574 } 2575 2576 return SDValue(); 2577 } 2578 2579 break; 2580 } 2581 case ISD::LOAD: 2582 case ISD::STORE: 2583 case ISD::ATOMIC_LOAD: 2584 case ISD::ATOMIC_STORE: 2585 case ISD::ATOMIC_CMP_SWAP: 2586 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 2587 case ISD::ATOMIC_SWAP: 2588 case ISD::ATOMIC_LOAD_ADD: 2589 case ISD::ATOMIC_LOAD_SUB: 2590 case ISD::ATOMIC_LOAD_AND: 2591 case ISD::ATOMIC_LOAD_OR: 2592 case ISD::ATOMIC_LOAD_XOR: 2593 case ISD::ATOMIC_LOAD_NAND: 2594 case ISD::ATOMIC_LOAD_MIN: 2595 case ISD::ATOMIC_LOAD_MAX: 2596 case ISD::ATOMIC_LOAD_UMIN: 2597 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics. 2598 if (DCI.isBeforeLegalize()) 2599 break; 2600 2601 MemSDNode *MemNode = cast<MemSDNode>(N); 2602 SDValue Ptr = MemNode->getBasePtr(); 2603 2604 // TODO: We could also do this for multiplies. 2605 unsigned AS = MemNode->getAddressSpace(); 2606 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) { 2607 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 2608 if (NewPtr) { 2609 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end()); 2610 2611 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 2612 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0); 2613 } 2614 } 2615 break; 2616 } 2617 case ISD::AND: 2618 return performAndCombine(N, DCI); 2619 case ISD::OR: 2620 return performOrCombine(N, DCI); 2621 case AMDGPUISD::FP_CLASS: 2622 return performClassCombine(N, DCI); 2623 } 2624 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 2625 } 2626 2627 /// \brief Analyze the possible immediate value Op 2628 /// 2629 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate 2630 /// and the immediate value if it's a literal immediate 2631 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const { 2632 2633 const SIInstrInfo *TII = 2634 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 2635 2636 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) { 2637 if (TII->isInlineConstant(Node->getAPIntValue())) 2638 return 0; 2639 2640 uint64_t Val = Node->getZExtValue(); 2641 return isUInt<32>(Val) ? Val : -1; 2642 } 2643 2644 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) { 2645 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt())) 2646 return 0; 2647 2648 if (Node->getValueType(0) == MVT::f32) 2649 return FloatToBits(Node->getValueAPF().convertToFloat()); 2650 2651 return -1; 2652 } 2653 2654 return -1; 2655 } 2656 2657 /// \brief Helper function for adjustWritemask 2658 static unsigned SubIdx2Lane(unsigned Idx) { 2659 switch (Idx) { 2660 default: return 0; 2661 case AMDGPU::sub0: return 0; 2662 case AMDGPU::sub1: return 1; 2663 case AMDGPU::sub2: return 2; 2664 case AMDGPU::sub3: return 3; 2665 } 2666 } 2667 2668 /// \brief Adjust the writemask of MIMG instructions 2669 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 2670 SelectionDAG &DAG) const { 2671 SDNode *Users[4] = { }; 2672 unsigned Lane = 0; 2673 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 2674 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 2675 unsigned NewDmask = 0; 2676 2677 // Try to figure out the used register components 2678 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 2679 I != E; ++I) { 2680 2681 // Abort if we can't understand the usage 2682 if (!I->isMachineOpcode() || 2683 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 2684 return; 2685 2686 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 2687 // Note that subregs are packed, i.e. Lane==0 is the first bit set 2688 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 2689 // set, etc. 2690 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 2691 2692 // Set which texture component corresponds to the lane. 2693 unsigned Comp; 2694 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 2695 assert(Dmask); 2696 Comp = countTrailingZeros(Dmask); 2697 Dmask &= ~(1 << Comp); 2698 } 2699 2700 // Abort if we have more than one user per component 2701 if (Users[Lane]) 2702 return; 2703 2704 Users[Lane] = *I; 2705 NewDmask |= 1 << Comp; 2706 } 2707 2708 // Abort if there's no change 2709 if (NewDmask == OldDmask) 2710 return; 2711 2712 // Adjust the writemask in the node 2713 std::vector<SDValue> Ops; 2714 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 2715 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 2716 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 2717 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 2718 2719 // If we only got one lane, replace it with a copy 2720 // (if NewDmask has only one bit set...) 2721 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 2722 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 2723 MVT::i32); 2724 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 2725 SDLoc(), Users[Lane]->getValueType(0), 2726 SDValue(Node, 0), RC); 2727 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 2728 return; 2729 } 2730 2731 // Update the users of the node with the new indices 2732 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 2733 2734 SDNode *User = Users[i]; 2735 if (!User) 2736 continue; 2737 2738 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 2739 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 2740 2741 switch (Idx) { 2742 default: break; 2743 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 2744 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 2745 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 2746 } 2747 } 2748 } 2749 2750 static bool isFrameIndexOp(SDValue Op) { 2751 if (Op.getOpcode() == ISD::AssertZext) 2752 Op = Op.getOperand(0); 2753 2754 return isa<FrameIndexSDNode>(Op); 2755 } 2756 2757 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 2758 /// with frame index operands. 2759 /// LLVM assumes that inputs are to these instructions are registers. 2760 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 2761 SelectionDAG &DAG) const { 2762 2763 SmallVector<SDValue, 8> Ops; 2764 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 2765 if (!isFrameIndexOp(Node->getOperand(i))) { 2766 Ops.push_back(Node->getOperand(i)); 2767 continue; 2768 } 2769 2770 SDLoc DL(Node); 2771 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 2772 Node->getOperand(i).getValueType(), 2773 Node->getOperand(i)), 0)); 2774 } 2775 2776 DAG.UpdateNodeOperands(Node, Ops); 2777 } 2778 2779 /// \brief Fold the instructions after selecting them. 2780 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 2781 SelectionDAG &DAG) const { 2782 const SIInstrInfo *TII = 2783 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 2784 unsigned Opcode = Node->getMachineOpcode(); 2785 2786 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore()) 2787 adjustWritemask(Node, DAG); 2788 2789 if (Opcode == AMDGPU::INSERT_SUBREG || 2790 Opcode == AMDGPU::REG_SEQUENCE) { 2791 legalizeTargetIndependentNode(Node, DAG); 2792 return Node; 2793 } 2794 return Node; 2795 } 2796 2797 /// \brief Assign the register class depending on the number of 2798 /// bits set in the writemask 2799 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 2800 SDNode *Node) const { 2801 const SIInstrInfo *TII = 2802 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 2803 2804 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo(); 2805 2806 if (TII->isVOP3(MI->getOpcode())) { 2807 // Make sure constant bus requirements are respected. 2808 TII->legalizeOperandsVOP3(MRI, MI); 2809 return; 2810 } 2811 2812 if (TII->isMIMG(*MI)) { 2813 unsigned VReg = MI->getOperand(0).getReg(); 2814 unsigned DmaskIdx = MI->getNumOperands() == 12 ? 3 : 4; 2815 unsigned Writemask = MI->getOperand(DmaskIdx).getImm(); 2816 unsigned BitsSet = 0; 2817 for (unsigned i = 0; i < 4; ++i) 2818 BitsSet += Writemask & (1 << i) ? 1 : 0; 2819 2820 const TargetRegisterClass *RC; 2821 switch (BitsSet) { 2822 default: return; 2823 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 2824 case 2: RC = &AMDGPU::VReg_64RegClass; break; 2825 case 3: RC = &AMDGPU::VReg_96RegClass; break; 2826 } 2827 2828 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet); 2829 MI->setDesc(TII->get(NewOpcode)); 2830 MRI.setRegClass(VReg, RC); 2831 return; 2832 } 2833 2834 // Replace unused atomics with the no return version. 2835 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode()); 2836 if (NoRetAtomicOp != -1) { 2837 if (!Node->hasAnyUseOfValue(0)) { 2838 MI->setDesc(TII->get(NoRetAtomicOp)); 2839 MI->RemoveOperand(0); 2840 } 2841 2842 return; 2843 } 2844 } 2845 2846 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) { 2847 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 2848 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 2849 } 2850 2851 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 2852 SDLoc DL, 2853 SDValue Ptr) const { 2854 const SIInstrInfo *TII = 2855 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 2856 2857 // Build the half of the subregister with the constants before building the 2858 // full 128-bit register. If we are building multiple resource descriptors, 2859 // this will allow CSEing of the 2-component register. 2860 const SDValue Ops0[] = { 2861 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 2862 buildSMovImm32(DAG, DL, 0), 2863 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 2864 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 2865 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 2866 }; 2867 2868 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 2869 MVT::v2i32, Ops0), 0); 2870 2871 // Combine the constants and the pointer. 2872 const SDValue Ops1[] = { 2873 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 2874 Ptr, 2875 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 2876 SubRegHi, 2877 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 2878 }; 2879 2880 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 2881 } 2882 2883 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 2884 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 2885 /// of the resource descriptor) to create an offset, which is added to 2886 /// the resource pointer. 2887 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, 2888 SDLoc DL, 2889 SDValue Ptr, 2890 uint32_t RsrcDword1, 2891 uint64_t RsrcDword2And3) const { 2892 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 2893 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 2894 if (RsrcDword1) { 2895 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 2896 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 2897 0); 2898 } 2899 2900 SDValue DataLo = buildSMovImm32(DAG, DL, 2901 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 2902 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 2903 2904 const SDValue Ops[] = { 2905 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 2906 PtrLo, 2907 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 2908 PtrHi, 2909 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 2910 DataLo, 2911 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 2912 DataHi, 2913 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 2914 }; 2915 2916 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 2917 } 2918 2919 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG, 2920 const TargetRegisterClass *RC, 2921 unsigned Reg, EVT VT) const { 2922 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT); 2923 2924 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()), 2925 cast<RegisterSDNode>(VReg)->getReg(), VT); 2926 } 2927 2928 //===----------------------------------------------------------------------===// 2929 // SI Inline Assembly Support 2930 //===----------------------------------------------------------------------===// 2931 2932 std::pair<unsigned, const TargetRegisterClass *> 2933 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 2934 StringRef Constraint, 2935 MVT VT) const { 2936 2937 if (Constraint.size() == 1) { 2938 switch (Constraint[0]) { 2939 case 's': 2940 case 'r': 2941 switch (VT.getSizeInBits()) { 2942 default: 2943 return std::make_pair(0U, nullptr); 2944 case 32: 2945 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass); 2946 case 64: 2947 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 2948 case 128: 2949 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 2950 case 256: 2951 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 2952 } 2953 2954 case 'v': 2955 switch (VT.getSizeInBits()) { 2956 default: 2957 return std::make_pair(0U, nullptr); 2958 case 32: 2959 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 2960 case 64: 2961 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 2962 case 96: 2963 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 2964 case 128: 2965 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 2966 case 256: 2967 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 2968 case 512: 2969 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 2970 } 2971 } 2972 } 2973 2974 if (Constraint.size() > 1) { 2975 const TargetRegisterClass *RC = nullptr; 2976 if (Constraint[1] == 'v') { 2977 RC = &AMDGPU::VGPR_32RegClass; 2978 } else if (Constraint[1] == 's') { 2979 RC = &AMDGPU::SGPR_32RegClass; 2980 } 2981 2982 if (RC) { 2983 uint32_t Idx; 2984 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 2985 if (!Failed && Idx < RC->getNumRegs()) 2986 return std::make_pair(RC->getRegister(Idx), RC); 2987 } 2988 } 2989 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 2990 } 2991 2992 SITargetLowering::ConstraintType 2993 SITargetLowering::getConstraintType(StringRef Constraint) const { 2994 if (Constraint.size() == 1) { 2995 switch (Constraint[0]) { 2996 default: break; 2997 case 's': 2998 case 'v': 2999 return C_RegisterClass; 3000 } 3001 } 3002 return TargetLowering::getConstraintType(Constraint); 3003 } 3004