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