1 //===- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Insert wait instructions for memory reads and writes. 11 /// 12 /// Memory reads and writes are issued asynchronously, so we need to insert 13 /// S_WAITCNT instructions when we want to access any of their results or 14 /// overwrite any register that's used asynchronously. 15 /// 16 /// TODO: This pass currently keeps one timeline per hardware counter. A more 17 /// finely-grained approach that keeps one timeline per event type could 18 /// sometimes get away with generating weaker s_waitcnt instructions. For 19 /// example, when both SMEM and LDS are in flight and we need to wait for 20 /// the i-th-last LDS instruction, then an lgkmcnt(i) is actually sufficient, 21 /// but the pass will currently generate a conservative lgkmcnt(0) because 22 /// multiple event types are in flight. 23 // 24 //===----------------------------------------------------------------------===// 25 26 #include "AMDGPU.h" 27 #include "AMDGPUSubtarget.h" 28 #include "SIDefines.h" 29 #include "SIInstrInfo.h" 30 #include "SIMachineFunctionInfo.h" 31 #include "SIRegisterInfo.h" 32 #include "Utils/AMDGPUBaseInfo.h" 33 #include "llvm/ADT/DenseMap.h" 34 #include "llvm/ADT/DenseSet.h" 35 #include "llvm/ADT/MapVector.h" 36 #include "llvm/ADT/PostOrderIterator.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/SmallVector.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineFunctionPass.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineMemOperand.h" 45 #include "llvm/CodeGen/MachineOperand.h" 46 #include "llvm/CodeGen/MachinePostDominators.h" 47 #include "llvm/CodeGen/MachineRegisterInfo.h" 48 #include "llvm/InitializePasses.h" 49 #include "llvm/IR/DebugLoc.h" 50 #include "llvm/Pass.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/DebugCounter.h" 53 #include "llvm/Support/ErrorHandling.h" 54 #include "llvm/Support/raw_ostream.h" 55 #include <algorithm> 56 #include <cassert> 57 #include <cstdint> 58 #include <cstring> 59 #include <memory> 60 #include <utility> 61 62 using namespace llvm; 63 64 #define DEBUG_TYPE "si-insert-waitcnts" 65 66 DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE"-forceexp", 67 "Force emit s_waitcnt expcnt(0) instrs"); 68 DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE"-forcelgkm", 69 "Force emit s_waitcnt lgkmcnt(0) instrs"); 70 DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE"-forcevm", 71 "Force emit s_waitcnt vmcnt(0) instrs"); 72 73 static cl::opt<bool> ForceEmitZeroFlag( 74 "amdgpu-waitcnt-forcezero", 75 cl::desc("Force all waitcnt instrs to be emitted as s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"), 76 cl::init(false), cl::Hidden); 77 78 namespace { 79 80 template <typename EnumT> 81 class enum_iterator 82 : public iterator_facade_base<enum_iterator<EnumT>, 83 std::forward_iterator_tag, const EnumT> { 84 EnumT Value; 85 public: 86 enum_iterator() = default; 87 enum_iterator(EnumT Value) : Value(Value) {} 88 89 enum_iterator &operator++() { 90 Value = static_cast<EnumT>(Value + 1); 91 return *this; 92 } 93 94 bool operator==(const enum_iterator &RHS) const { return Value == RHS.Value; } 95 96 EnumT operator*() const { return Value; } 97 }; 98 99 // Class of object that encapsulates latest instruction counter score 100 // associated with the operand. Used for determining whether 101 // s_waitcnt instruction needs to be emited. 102 103 #define CNT_MASK(t) (1u << (t)) 104 105 enum InstCounterType { VM_CNT = 0, LGKM_CNT, EXP_CNT, VS_CNT, NUM_INST_CNTS }; 106 107 iterator_range<enum_iterator<InstCounterType>> inst_counter_types() { 108 return make_range(enum_iterator<InstCounterType>(VM_CNT), 109 enum_iterator<InstCounterType>(NUM_INST_CNTS)); 110 } 111 112 using RegInterval = std::pair<int, int>; 113 114 struct { 115 unsigned VmcntMax; 116 unsigned ExpcntMax; 117 unsigned LgkmcntMax; 118 unsigned VscntMax; 119 } HardwareLimits; 120 121 struct { 122 unsigned VGPR0; 123 unsigned VGPRL; 124 unsigned SGPR0; 125 unsigned SGPRL; 126 } RegisterEncoding; 127 128 enum WaitEventType { 129 VMEM_ACCESS, // vector-memory read & write 130 VMEM_READ_ACCESS, // vector-memory read 131 VMEM_WRITE_ACCESS,// vector-memory write 132 LDS_ACCESS, // lds read & write 133 GDS_ACCESS, // gds read & write 134 SQ_MESSAGE, // send message 135 SMEM_ACCESS, // scalar-memory read & write 136 EXP_GPR_LOCK, // export holding on its data src 137 GDS_GPR_LOCK, // GDS holding on its data and addr src 138 EXP_POS_ACCESS, // write to export position 139 EXP_PARAM_ACCESS, // write to export parameter 140 VMW_GPR_LOCK, // vector-memory write holding on its data src 141 NUM_WAIT_EVENTS, 142 }; 143 144 static const unsigned WaitEventMaskForInst[NUM_INST_CNTS] = { 145 (1 << VMEM_ACCESS) | (1 << VMEM_READ_ACCESS), 146 (1 << SMEM_ACCESS) | (1 << LDS_ACCESS) | (1 << GDS_ACCESS) | 147 (1 << SQ_MESSAGE), 148 (1 << EXP_GPR_LOCK) | (1 << GDS_GPR_LOCK) | (1 << VMW_GPR_LOCK) | 149 (1 << EXP_PARAM_ACCESS) | (1 << EXP_POS_ACCESS), 150 (1 << VMEM_WRITE_ACCESS) 151 }; 152 153 // The mapping is: 154 // 0 .. SQ_MAX_PGM_VGPRS-1 real VGPRs 155 // SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1 extra VGPR-like slots 156 // NUM_ALL_VGPRS .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs 157 // We reserve a fixed number of VGPR slots in the scoring tables for 158 // special tokens like SCMEM_LDS (needed for buffer load to LDS). 159 enum RegisterMapping { 160 SQ_MAX_PGM_VGPRS = 256, // Maximum programmable VGPRs across all targets. 161 SQ_MAX_PGM_SGPRS = 256, // Maximum programmable SGPRs across all targets. 162 NUM_EXTRA_VGPRS = 1, // A reserved slot for DS. 163 EXTRA_VGPR_LDS = 0, // This is a placeholder the Shader algorithm uses. 164 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_EXTRA_VGPRS, // Where SGPR starts. 165 }; 166 167 // Enumerate different types of result-returning VMEM operations. Although 168 // s_waitcnt orders them all with a single vmcnt counter, in the absence of 169 // s_waitcnt only instructions of the same VmemType are guaranteed to write 170 // their results in order -- so there is no need to insert an s_waitcnt between 171 // two instructions of the same type that write the same vgpr. 172 enum VmemType { 173 // BUF instructions and MIMG instructions without a sampler. 174 VMEM_NOSAMPLER, 175 // MIMG instructions with a sampler. 176 VMEM_SAMPLER, 177 }; 178 179 VmemType getVmemType(const MachineInstr &Inst) { 180 assert(SIInstrInfo::isVMEM(Inst)); 181 if (!SIInstrInfo::isMIMG(Inst)) 182 return VMEM_NOSAMPLER; 183 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Inst.getOpcode()); 184 return AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode)->Sampler 185 ? VMEM_SAMPLER 186 : VMEM_NOSAMPLER; 187 } 188 189 void addWait(AMDGPU::Waitcnt &Wait, InstCounterType T, unsigned Count) { 190 switch (T) { 191 case VM_CNT: 192 Wait.VmCnt = std::min(Wait.VmCnt, Count); 193 break; 194 case EXP_CNT: 195 Wait.ExpCnt = std::min(Wait.ExpCnt, Count); 196 break; 197 case LGKM_CNT: 198 Wait.LgkmCnt = std::min(Wait.LgkmCnt, Count); 199 break; 200 case VS_CNT: 201 Wait.VsCnt = std::min(Wait.VsCnt, Count); 202 break; 203 default: 204 llvm_unreachable("bad InstCounterType"); 205 } 206 } 207 208 // This objects maintains the current score brackets of each wait counter, and 209 // a per-register scoreboard for each wait counter. 210 // 211 // We also maintain the latest score for every event type that can change the 212 // waitcnt in order to know if there are multiple types of events within 213 // the brackets. When multiple types of event happen in the bracket, 214 // wait count may get decreased out of order, therefore we need to put in 215 // "s_waitcnt 0" before use. 216 class WaitcntBrackets { 217 public: 218 WaitcntBrackets(const GCNSubtarget *SubTarget) : ST(SubTarget) {} 219 220 static unsigned getWaitCountMax(InstCounterType T) { 221 switch (T) { 222 case VM_CNT: 223 return HardwareLimits.VmcntMax; 224 case LGKM_CNT: 225 return HardwareLimits.LgkmcntMax; 226 case EXP_CNT: 227 return HardwareLimits.ExpcntMax; 228 case VS_CNT: 229 return HardwareLimits.VscntMax; 230 default: 231 break; 232 } 233 return 0; 234 } 235 236 unsigned getScoreLB(InstCounterType T) const { 237 assert(T < NUM_INST_CNTS); 238 return ScoreLBs[T]; 239 } 240 241 unsigned getScoreUB(InstCounterType T) const { 242 assert(T < NUM_INST_CNTS); 243 return ScoreUBs[T]; 244 } 245 246 // Mapping from event to counter. 247 InstCounterType eventCounter(WaitEventType E) { 248 if (WaitEventMaskForInst[VM_CNT] & (1 << E)) 249 return VM_CNT; 250 if (WaitEventMaskForInst[LGKM_CNT] & (1 << E)) 251 return LGKM_CNT; 252 if (WaitEventMaskForInst[VS_CNT] & (1 << E)) 253 return VS_CNT; 254 assert(WaitEventMaskForInst[EXP_CNT] & (1 << E)); 255 return EXP_CNT; 256 } 257 258 unsigned getRegScore(int GprNo, InstCounterType T) { 259 if (GprNo < NUM_ALL_VGPRS) { 260 return VgprScores[T][GprNo]; 261 } 262 assert(T == LGKM_CNT); 263 return SgprScores[GprNo - NUM_ALL_VGPRS]; 264 } 265 266 bool merge(const WaitcntBrackets &Other); 267 268 RegInterval getRegInterval(const MachineInstr *MI, const SIInstrInfo *TII, 269 const MachineRegisterInfo *MRI, 270 const SIRegisterInfo *TRI, unsigned OpNo) const; 271 272 bool counterOutOfOrder(InstCounterType T) const; 273 bool simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const; 274 bool simplifyWaitcnt(InstCounterType T, unsigned &Count) const; 275 void determineWait(InstCounterType T, unsigned ScoreToWait, 276 AMDGPU::Waitcnt &Wait) const; 277 void applyWaitcnt(const AMDGPU::Waitcnt &Wait); 278 void applyWaitcnt(InstCounterType T, unsigned Count); 279 void updateByEvent(const SIInstrInfo *TII, const SIRegisterInfo *TRI, 280 const MachineRegisterInfo *MRI, WaitEventType E, 281 MachineInstr &MI); 282 283 bool hasPending() const { return PendingEvents != 0; } 284 bool hasPendingEvent(WaitEventType E) const { 285 return PendingEvents & (1 << E); 286 } 287 288 bool hasMixedPendingEvents(InstCounterType T) const { 289 unsigned Events = PendingEvents & WaitEventMaskForInst[T]; 290 // Return true if more than one bit is set in Events. 291 return Events & (Events - 1); 292 } 293 294 bool hasPendingFlat() const { 295 return ((LastFlat[LGKM_CNT] > ScoreLBs[LGKM_CNT] && 296 LastFlat[LGKM_CNT] <= ScoreUBs[LGKM_CNT]) || 297 (LastFlat[VM_CNT] > ScoreLBs[VM_CNT] && 298 LastFlat[VM_CNT] <= ScoreUBs[VM_CNT])); 299 } 300 301 void setPendingFlat() { 302 LastFlat[VM_CNT] = ScoreUBs[VM_CNT]; 303 LastFlat[LGKM_CNT] = ScoreUBs[LGKM_CNT]; 304 } 305 306 // Return true if there might be pending writes to the specified vgpr by VMEM 307 // instructions with types different from V. 308 bool hasOtherPendingVmemTypes(int GprNo, VmemType V) const { 309 assert(GprNo < NUM_ALL_VGPRS); 310 return VgprVmemTypes[GprNo] & ~(1 << V); 311 } 312 313 void clearVgprVmemTypes(int GprNo) { 314 assert(GprNo < NUM_ALL_VGPRS); 315 VgprVmemTypes[GprNo] = 0; 316 } 317 318 void print(raw_ostream &); 319 void dump() { print(dbgs()); } 320 321 private: 322 struct MergeInfo { 323 unsigned OldLB; 324 unsigned OtherLB; 325 unsigned MyShift; 326 unsigned OtherShift; 327 }; 328 static bool mergeScore(const MergeInfo &M, unsigned &Score, 329 unsigned OtherScore); 330 331 void setScoreLB(InstCounterType T, unsigned Val) { 332 assert(T < NUM_INST_CNTS); 333 ScoreLBs[T] = Val; 334 } 335 336 void setScoreUB(InstCounterType T, unsigned Val) { 337 assert(T < NUM_INST_CNTS); 338 ScoreUBs[T] = Val; 339 if (T == EXP_CNT) { 340 unsigned UB = ScoreUBs[T] - getWaitCountMax(EXP_CNT); 341 if (ScoreLBs[T] < UB && UB < ScoreUBs[T]) 342 ScoreLBs[T] = UB; 343 } 344 } 345 346 void setRegScore(int GprNo, InstCounterType T, unsigned Val) { 347 if (GprNo < NUM_ALL_VGPRS) { 348 VgprUB = std::max(VgprUB, GprNo); 349 VgprScores[T][GprNo] = Val; 350 } else { 351 assert(T == LGKM_CNT); 352 SgprUB = std::max(SgprUB, GprNo - NUM_ALL_VGPRS); 353 SgprScores[GprNo - NUM_ALL_VGPRS] = Val; 354 } 355 } 356 357 void setExpScore(const MachineInstr *MI, const SIInstrInfo *TII, 358 const SIRegisterInfo *TRI, const MachineRegisterInfo *MRI, 359 unsigned OpNo, unsigned Val); 360 361 const GCNSubtarget *ST = nullptr; 362 unsigned ScoreLBs[NUM_INST_CNTS] = {0}; 363 unsigned ScoreUBs[NUM_INST_CNTS] = {0}; 364 unsigned PendingEvents = 0; 365 // Remember the last flat memory operation. 366 unsigned LastFlat[NUM_INST_CNTS] = {0}; 367 // wait_cnt scores for every vgpr. 368 // Keep track of the VgprUB and SgprUB to make merge at join efficient. 369 int VgprUB = -1; 370 int SgprUB = -1; 371 unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}}; 372 // Wait cnt scores for every sgpr, only lgkmcnt is relevant. 373 unsigned SgprScores[SQ_MAX_PGM_SGPRS] = {0}; 374 // Bitmask of the VmemTypes of VMEM instructions that might have a pending 375 // write to each vgpr. 376 unsigned char VgprVmemTypes[NUM_ALL_VGPRS] = {0}; 377 }; 378 379 class SIInsertWaitcnts : public MachineFunctionPass { 380 private: 381 const GCNSubtarget *ST = nullptr; 382 const SIInstrInfo *TII = nullptr; 383 const SIRegisterInfo *TRI = nullptr; 384 const MachineRegisterInfo *MRI = nullptr; 385 AMDGPU::IsaVersion IV; 386 387 DenseSet<MachineInstr *> TrackedWaitcntSet; 388 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses; 389 MachinePostDominatorTree *PDT; 390 391 struct BlockInfo { 392 MachineBasicBlock *MBB; 393 std::unique_ptr<WaitcntBrackets> Incoming; 394 bool Dirty = true; 395 396 explicit BlockInfo(MachineBasicBlock *MBB) : MBB(MBB) {} 397 }; 398 399 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos; 400 401 // ForceEmitZeroWaitcnts: force all waitcnts insts to be s_waitcnt 0 402 // because of amdgpu-waitcnt-forcezero flag 403 bool ForceEmitZeroWaitcnts; 404 bool ForceEmitWaitcnt[NUM_INST_CNTS]; 405 406 public: 407 static char ID; 408 409 SIInsertWaitcnts() : MachineFunctionPass(ID) { 410 (void)ForceExpCounter; 411 (void)ForceLgkmCounter; 412 (void)ForceVMCounter; 413 } 414 415 bool runOnMachineFunction(MachineFunction &MF) override; 416 417 StringRef getPassName() const override { 418 return "SI insert wait instructions"; 419 } 420 421 void getAnalysisUsage(AnalysisUsage &AU) const override { 422 AU.setPreservesCFG(); 423 AU.addRequired<MachinePostDominatorTree>(); 424 MachineFunctionPass::getAnalysisUsage(AU); 425 } 426 427 bool isForceEmitWaitcnt() const { 428 for (auto T : inst_counter_types()) 429 if (ForceEmitWaitcnt[T]) 430 return true; 431 return false; 432 } 433 434 void setForceEmitWaitcnt() { 435 // For non-debug builds, ForceEmitWaitcnt has been initialized to false; 436 // For debug builds, get the debug counter info and adjust if need be 437 #ifndef NDEBUG 438 if (DebugCounter::isCounterSet(ForceExpCounter) && 439 DebugCounter::shouldExecute(ForceExpCounter)) { 440 ForceEmitWaitcnt[EXP_CNT] = true; 441 } else { 442 ForceEmitWaitcnt[EXP_CNT] = false; 443 } 444 445 if (DebugCounter::isCounterSet(ForceLgkmCounter) && 446 DebugCounter::shouldExecute(ForceLgkmCounter)) { 447 ForceEmitWaitcnt[LGKM_CNT] = true; 448 } else { 449 ForceEmitWaitcnt[LGKM_CNT] = false; 450 } 451 452 if (DebugCounter::isCounterSet(ForceVMCounter) && 453 DebugCounter::shouldExecute(ForceVMCounter)) { 454 ForceEmitWaitcnt[VM_CNT] = true; 455 } else { 456 ForceEmitWaitcnt[VM_CNT] = false; 457 } 458 #endif // NDEBUG 459 } 460 461 bool mayAccessLDSThroughFlat(const MachineInstr &MI) const; 462 bool generateWaitcntInstBefore(MachineInstr &MI, 463 WaitcntBrackets &ScoreBrackets, 464 MachineInstr *OldWaitcntInstr); 465 void updateEventWaitcntAfter(MachineInstr &Inst, 466 WaitcntBrackets *ScoreBrackets); 467 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block, 468 WaitcntBrackets &ScoreBrackets); 469 }; 470 471 } // end anonymous namespace 472 473 RegInterval WaitcntBrackets::getRegInterval(const MachineInstr *MI, 474 const SIInstrInfo *TII, 475 const MachineRegisterInfo *MRI, 476 const SIRegisterInfo *TRI, 477 unsigned OpNo) const { 478 const MachineOperand &Op = MI->getOperand(OpNo); 479 assert(Op.isReg()); 480 if (!TRI->isInAllocatableClass(Op.getReg()) || TRI->isAGPR(*MRI, Op.getReg())) 481 return {-1, -1}; 482 483 // A use via a PW operand does not need a waitcnt. 484 // A partial write is not a WAW. 485 assert(!Op.getSubReg() || !Op.isUndef()); 486 487 RegInterval Result; 488 489 unsigned Reg = TRI->getEncodingValue(Op.getReg()); 490 491 if (TRI->isVGPR(*MRI, Op.getReg())) { 492 assert(Reg >= RegisterEncoding.VGPR0 && Reg <= RegisterEncoding.VGPRL); 493 Result.first = Reg - RegisterEncoding.VGPR0; 494 assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS); 495 } else if (TRI->isSGPRReg(*MRI, Op.getReg())) { 496 assert(Reg >= RegisterEncoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS); 497 Result.first = Reg - RegisterEncoding.SGPR0 + NUM_ALL_VGPRS; 498 assert(Result.first >= NUM_ALL_VGPRS && 499 Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS); 500 } 501 // TODO: Handle TTMP 502 // else if (TRI->isTTMP(*MRI, Reg.getReg())) ... 503 else 504 return {-1, -1}; 505 506 const TargetRegisterClass *RC = TII->getOpRegClass(*MI, OpNo); 507 unsigned Size = TRI->getRegSizeInBits(*RC); 508 Result.second = Result.first + ((Size + 16) / 32); 509 510 return Result; 511 } 512 513 void WaitcntBrackets::setExpScore(const MachineInstr *MI, 514 const SIInstrInfo *TII, 515 const SIRegisterInfo *TRI, 516 const MachineRegisterInfo *MRI, unsigned OpNo, 517 unsigned Val) { 518 RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo); 519 assert(TRI->isVGPR(*MRI, MI->getOperand(OpNo).getReg())); 520 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) { 521 setRegScore(RegNo, EXP_CNT, Val); 522 } 523 } 524 525 void WaitcntBrackets::updateByEvent(const SIInstrInfo *TII, 526 const SIRegisterInfo *TRI, 527 const MachineRegisterInfo *MRI, 528 WaitEventType E, MachineInstr &Inst) { 529 InstCounterType T = eventCounter(E); 530 unsigned CurrScore = getScoreUB(T) + 1; 531 if (CurrScore == 0) 532 report_fatal_error("InsertWaitcnt score wraparound"); 533 // PendingEvents and ScoreUB need to be update regardless if this event 534 // changes the score of a register or not. 535 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message. 536 PendingEvents |= 1 << E; 537 setScoreUB(T, CurrScore); 538 539 if (T == EXP_CNT) { 540 // Put score on the source vgprs. If this is a store, just use those 541 // specific register(s). 542 if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) { 543 int AddrOpIdx = 544 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr); 545 // All GDS operations must protect their address register (same as 546 // export.) 547 if (AddrOpIdx != -1) { 548 setExpScore(&Inst, TII, TRI, MRI, AddrOpIdx, CurrScore); 549 } 550 551 if (Inst.mayStore()) { 552 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(), 553 AMDGPU::OpName::data0) != -1) { 554 setExpScore( 555 &Inst, TII, TRI, MRI, 556 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0), 557 CurrScore); 558 } 559 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(), 560 AMDGPU::OpName::data1) != -1) { 561 setExpScore(&Inst, TII, TRI, MRI, 562 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), 563 AMDGPU::OpName::data1), 564 CurrScore); 565 } 566 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1 && 567 Inst.getOpcode() != AMDGPU::DS_GWS_INIT && 568 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V && 569 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR && 570 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P && 571 Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER && 572 Inst.getOpcode() != AMDGPU::DS_APPEND && 573 Inst.getOpcode() != AMDGPU::DS_CONSUME && 574 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) { 575 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) { 576 const MachineOperand &Op = Inst.getOperand(I); 577 if (Op.isReg() && !Op.isDef() && TRI->isVGPR(*MRI, Op.getReg())) { 578 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore); 579 } 580 } 581 } 582 } else if (TII->isFLAT(Inst)) { 583 if (Inst.mayStore()) { 584 setExpScore( 585 &Inst, TII, TRI, MRI, 586 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data), 587 CurrScore); 588 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) { 589 setExpScore( 590 &Inst, TII, TRI, MRI, 591 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data), 592 CurrScore); 593 } 594 } else if (TII->isMIMG(Inst)) { 595 if (Inst.mayStore()) { 596 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore); 597 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) { 598 setExpScore( 599 &Inst, TII, TRI, MRI, 600 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data), 601 CurrScore); 602 } 603 } else if (TII->isMTBUF(Inst)) { 604 if (Inst.mayStore()) { 605 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore); 606 } 607 } else if (TII->isMUBUF(Inst)) { 608 if (Inst.mayStore()) { 609 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore); 610 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) { 611 setExpScore( 612 &Inst, TII, TRI, MRI, 613 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data), 614 CurrScore); 615 } 616 } else { 617 if (TII->isEXP(Inst)) { 618 // For export the destination registers are really temps that 619 // can be used as the actual source after export patching, so 620 // we need to treat them like sources and set the EXP_CNT 621 // score. 622 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) { 623 MachineOperand &DefMO = Inst.getOperand(I); 624 if (DefMO.isReg() && DefMO.isDef() && 625 TRI->isVGPR(*MRI, DefMO.getReg())) { 626 setRegScore(TRI->getEncodingValue(DefMO.getReg()), EXP_CNT, 627 CurrScore); 628 } 629 } 630 } 631 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) { 632 MachineOperand &MO = Inst.getOperand(I); 633 if (MO.isReg() && !MO.isDef() && TRI->isVGPR(*MRI, MO.getReg())) { 634 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore); 635 } 636 } 637 } 638 #if 0 // TODO: check if this is handled by MUBUF code above. 639 } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD || 640 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 || 641 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) { 642 MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data); 643 unsigned OpNo;//TODO: find the OpNo for this operand; 644 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo); 645 for (int RegNo = Interval.first; RegNo < Interval.second; 646 ++RegNo) { 647 setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore); 648 } 649 #endif 650 } else { 651 // Match the score to the destination registers. 652 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) { 653 auto &Op = Inst.getOperand(I); 654 if (!Op.isReg() || !Op.isDef()) 655 continue; 656 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I); 657 if (T == VM_CNT) { 658 if (Interval.first >= NUM_ALL_VGPRS) 659 continue; 660 if (SIInstrInfo::isVMEM(Inst)) { 661 VmemType V = getVmemType(Inst); 662 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) 663 VgprVmemTypes[RegNo] |= 1 << V; 664 } 665 } 666 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) { 667 setRegScore(RegNo, T, CurrScore); 668 } 669 } 670 if (TII->isDS(Inst) && Inst.mayStore()) { 671 setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore); 672 } 673 } 674 } 675 676 void WaitcntBrackets::print(raw_ostream &OS) { 677 OS << '\n'; 678 for (auto T : inst_counter_types()) { 679 unsigned LB = getScoreLB(T); 680 unsigned UB = getScoreUB(T); 681 682 switch (T) { 683 case VM_CNT: 684 OS << " VM_CNT(" << UB - LB << "): "; 685 break; 686 case LGKM_CNT: 687 OS << " LGKM_CNT(" << UB - LB << "): "; 688 break; 689 case EXP_CNT: 690 OS << " EXP_CNT(" << UB - LB << "): "; 691 break; 692 case VS_CNT: 693 OS << " VS_CNT(" << UB - LB << "): "; 694 break; 695 default: 696 OS << " UNKNOWN(" << UB - LB << "): "; 697 break; 698 } 699 700 if (LB < UB) { 701 // Print vgpr scores. 702 for (int J = 0; J <= VgprUB; J++) { 703 unsigned RegScore = getRegScore(J, T); 704 if (RegScore <= LB) 705 continue; 706 unsigned RelScore = RegScore - LB - 1; 707 if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) { 708 OS << RelScore << ":v" << J << " "; 709 } else { 710 OS << RelScore << ":ds "; 711 } 712 } 713 // Also need to print sgpr scores for lgkm_cnt. 714 if (T == LGKM_CNT) { 715 for (int J = 0; J <= SgprUB; J++) { 716 unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT); 717 if (RegScore <= LB) 718 continue; 719 unsigned RelScore = RegScore - LB - 1; 720 OS << RelScore << ":s" << J << " "; 721 } 722 } 723 } 724 OS << '\n'; 725 } 726 OS << '\n'; 727 } 728 729 /// Simplify the waitcnt, in the sense of removing redundant counts, and return 730 /// whether a waitcnt instruction is needed at all. 731 bool WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const { 732 return simplifyWaitcnt(VM_CNT, Wait.VmCnt) | 733 simplifyWaitcnt(EXP_CNT, Wait.ExpCnt) | 734 simplifyWaitcnt(LGKM_CNT, Wait.LgkmCnt) | 735 simplifyWaitcnt(VS_CNT, Wait.VsCnt); 736 } 737 738 bool WaitcntBrackets::simplifyWaitcnt(InstCounterType T, 739 unsigned &Count) const { 740 const unsigned LB = getScoreLB(T); 741 const unsigned UB = getScoreUB(T); 742 if (Count < UB && UB - Count > LB) 743 return true; 744 745 Count = ~0u; 746 return false; 747 } 748 749 void WaitcntBrackets::determineWait(InstCounterType T, unsigned ScoreToWait, 750 AMDGPU::Waitcnt &Wait) const { 751 // If the score of src_operand falls within the bracket, we need an 752 // s_waitcnt instruction. 753 const unsigned LB = getScoreLB(T); 754 const unsigned UB = getScoreUB(T); 755 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) { 756 if ((T == VM_CNT || T == LGKM_CNT) && 757 hasPendingFlat() && 758 !ST->hasFlatLgkmVMemCountInOrder()) { 759 // If there is a pending FLAT operation, and this is a VMem or LGKM 760 // waitcnt and the target can report early completion, then we need 761 // to force a waitcnt 0. 762 addWait(Wait, T, 0); 763 } else if (counterOutOfOrder(T)) { 764 // Counter can get decremented out-of-order when there 765 // are multiple types event in the bracket. Also emit an s_wait counter 766 // with a conservative value of 0 for the counter. 767 addWait(Wait, T, 0); 768 } else { 769 // If a counter has been maxed out avoid overflow by waiting for 770 // MAX(CounterType) - 1 instead. 771 unsigned NeededWait = std::min(UB - ScoreToWait, getWaitCountMax(T) - 1); 772 addWait(Wait, T, NeededWait); 773 } 774 } 775 } 776 777 void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) { 778 applyWaitcnt(VM_CNT, Wait.VmCnt); 779 applyWaitcnt(EXP_CNT, Wait.ExpCnt); 780 applyWaitcnt(LGKM_CNT, Wait.LgkmCnt); 781 applyWaitcnt(VS_CNT, Wait.VsCnt); 782 } 783 784 void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) { 785 const unsigned UB = getScoreUB(T); 786 if (Count >= UB) 787 return; 788 if (Count != 0) { 789 if (counterOutOfOrder(T)) 790 return; 791 setScoreLB(T, std::max(getScoreLB(T), UB - Count)); 792 } else { 793 setScoreLB(T, UB); 794 PendingEvents &= ~WaitEventMaskForInst[T]; 795 } 796 } 797 798 // Where there are multiple types of event in the bracket of a counter, 799 // the decrement may go out of order. 800 bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const { 801 // Scalar memory read always can go out of order. 802 if (T == LGKM_CNT && hasPendingEvent(SMEM_ACCESS)) 803 return true; 804 return hasMixedPendingEvents(T); 805 } 806 807 INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false, 808 false) 809 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) 810 INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false, 811 false) 812 813 char SIInsertWaitcnts::ID = 0; 814 815 char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID; 816 817 FunctionPass *llvm::createSIInsertWaitcntsPass() { 818 return new SIInsertWaitcnts(); 819 } 820 821 static bool readsVCCZ(const MachineInstr &MI) { 822 unsigned Opc = MI.getOpcode(); 823 return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) && 824 !MI.getOperand(1).isUndef(); 825 } 826 827 /// \returns true if the callee inserts an s_waitcnt 0 on function entry. 828 static bool callWaitsOnFunctionEntry(const MachineInstr &MI) { 829 // Currently all conventions wait, but this may not always be the case. 830 // 831 // TODO: If IPRA is enabled, and the callee is isSafeForNoCSROpt, it may make 832 // senses to omit the wait and do it in the caller. 833 return true; 834 } 835 836 /// \returns true if the callee is expected to wait for any outstanding waits 837 /// before returning. 838 static bool callWaitsOnFunctionReturn(const MachineInstr &MI) { 839 return true; 840 } 841 842 /// Generate s_waitcnt instruction to be placed before cur_Inst. 843 /// Instructions of a given type are returned in order, 844 /// but instructions of different types can complete out of order. 845 /// We rely on this in-order completion 846 /// and simply assign a score to the memory access instructions. 847 /// We keep track of the active "score bracket" to determine 848 /// if an access of a memory read requires an s_waitcnt 849 /// and if so what the value of each counter is. 850 /// The "score bracket" is bound by the lower bound and upper bound 851 /// scores (*_score_LB and *_score_ub respectively). 852 bool SIInsertWaitcnts::generateWaitcntInstBefore( 853 MachineInstr &MI, WaitcntBrackets &ScoreBrackets, 854 MachineInstr *OldWaitcntInstr) { 855 setForceEmitWaitcnt(); 856 bool IsForceEmitWaitcnt = isForceEmitWaitcnt(); 857 858 if (MI.isMetaInstruction()) 859 return false; 860 861 AMDGPU::Waitcnt Wait; 862 863 // See if this instruction has a forced S_WAITCNT VM. 864 // TODO: Handle other cases of NeedsWaitcntVmBefore() 865 if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 || 866 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC || 867 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL || 868 MI.getOpcode() == AMDGPU::BUFFER_GL0_INV || 869 MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) { 870 Wait.VmCnt = 0; 871 } 872 873 // All waits must be resolved at call return. 874 // NOTE: this could be improved with knowledge of all call sites or 875 // with knowledge of the called routines. 876 if (MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG || 877 MI.getOpcode() == AMDGPU::S_SETPC_B64_return || 878 (MI.isReturn() && MI.isCall() && !callWaitsOnFunctionEntry(MI))) { 879 Wait = Wait.combined(AMDGPU::Waitcnt::allZero(ST->hasVscnt())); 880 } 881 // Resolve vm waits before gs-done. 882 else if ((MI.getOpcode() == AMDGPU::S_SENDMSG || 883 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) && 884 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) == 885 AMDGPU::SendMsg::ID_GS_DONE)) { 886 Wait.VmCnt = 0; 887 } 888 #if 0 // TODO: the following blocks of logic when we have fence. 889 else if (MI.getOpcode() == SC_FENCE) { 890 const unsigned int group_size = 891 context->shader_info->GetMaxThreadGroupSize(); 892 // group_size == 0 means thread group size is unknown at compile time 893 const bool group_is_multi_wave = 894 (group_size == 0 || group_size > target_info->GetWaveFrontSize()); 895 const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence(); 896 897 for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) { 898 SCRegType src_type = Inst->GetSrcType(i); 899 switch (src_type) { 900 case SCMEM_LDS: 901 if (group_is_multi_wave || 902 context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) { 903 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT, 904 ScoreBrackets->getScoreUB(LGKM_CNT)); 905 // LDS may have to wait for VM_CNT after buffer load to LDS 906 if (target_info->HasBufferLoadToLDS()) { 907 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT, 908 ScoreBrackets->getScoreUB(VM_CNT)); 909 } 910 } 911 break; 912 913 case SCMEM_GDS: 914 if (group_is_multi_wave || fence_is_global) { 915 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT, 916 ScoreBrackets->getScoreUB(EXP_CNT)); 917 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT, 918 ScoreBrackets->getScoreUB(LGKM_CNT)); 919 } 920 break; 921 922 case SCMEM_UAV: 923 case SCMEM_TFBUF: 924 case SCMEM_RING: 925 case SCMEM_SCATTER: 926 if (group_is_multi_wave || fence_is_global) { 927 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT, 928 ScoreBrackets->getScoreUB(EXP_CNT)); 929 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT, 930 ScoreBrackets->getScoreUB(VM_CNT)); 931 } 932 break; 933 934 case SCMEM_SCRATCH: 935 default: 936 break; 937 } 938 } 939 } 940 #endif 941 942 // Export & GDS instructions do not read the EXEC mask until after the export 943 // is granted (which can occur well after the instruction is issued). 944 // The shader program must flush all EXP operations on the export-count 945 // before overwriting the EXEC mask. 946 else { 947 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) { 948 // Export and GDS are tracked individually, either may trigger a waitcnt 949 // for EXEC. 950 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) || 951 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) || 952 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) || 953 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) { 954 Wait.ExpCnt = 0; 955 } 956 } 957 958 if (MI.isCall() && callWaitsOnFunctionEntry(MI)) { 959 // The function is going to insert a wait on everything in its prolog. 960 // This still needs to be careful if the call target is a load (e.g. a GOT 961 // load). We also need to check WAW depenancy with saved PC. 962 Wait = AMDGPU::Waitcnt(); 963 964 int CallAddrOpIdx = 965 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0); 966 967 if (MI.getOperand(CallAddrOpIdx).isReg()) { 968 RegInterval CallAddrOpInterval = 969 ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, CallAddrOpIdx); 970 971 for (int RegNo = CallAddrOpInterval.first; 972 RegNo < CallAddrOpInterval.second; ++RegNo) 973 ScoreBrackets.determineWait( 974 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait); 975 976 int RtnAddrOpIdx = 977 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::dst); 978 if (RtnAddrOpIdx != -1) { 979 RegInterval RtnAddrOpInterval = 980 ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, RtnAddrOpIdx); 981 982 for (int RegNo = RtnAddrOpInterval.first; 983 RegNo < RtnAddrOpInterval.second; ++RegNo) 984 ScoreBrackets.determineWait( 985 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait); 986 } 987 } 988 } else { 989 // FIXME: Should not be relying on memoperands. 990 // Look at the source operands of every instruction to see if 991 // any of them results from a previous memory operation that affects 992 // its current usage. If so, an s_waitcnt instruction needs to be 993 // emitted. 994 // If the source operand was defined by a load, add the s_waitcnt 995 // instruction. 996 // 997 // Two cases are handled for destination operands: 998 // 1) If the destination operand was defined by a load, add the s_waitcnt 999 // instruction to guarantee the right WAW order. 1000 // 2) If a destination operand that was used by a recent export/store ins, 1001 // add s_waitcnt on exp_cnt to guarantee the WAR order. 1002 for (const MachineMemOperand *Memop : MI.memoperands()) { 1003 const Value *Ptr = Memop->getValue(); 1004 if (Memop->isStore() && SLoadAddresses.count(Ptr)) { 1005 addWait(Wait, LGKM_CNT, 0); 1006 if (PDT->dominates(MI.getParent(), SLoadAddresses.find(Ptr)->second)) 1007 SLoadAddresses.erase(Ptr); 1008 } 1009 unsigned AS = Memop->getAddrSpace(); 1010 if (AS != AMDGPUAS::LOCAL_ADDRESS) 1011 continue; 1012 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS; 1013 // VM_CNT is only relevant to vgpr or LDS. 1014 ScoreBrackets.determineWait( 1015 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait); 1016 if (Memop->isStore()) { 1017 ScoreBrackets.determineWait( 1018 EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait); 1019 } 1020 } 1021 1022 // Loop over use and def operands. 1023 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { 1024 MachineOperand &Op = MI.getOperand(I); 1025 if (!Op.isReg()) 1026 continue; 1027 RegInterval Interval = 1028 ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I); 1029 1030 const bool IsVGPR = TRI->isVGPR(*MRI, Op.getReg()); 1031 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) { 1032 if (IsVGPR) { 1033 // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the 1034 // previous write and this write are the same type of VMEM 1035 // instruction, in which case they're guaranteed to write their 1036 // results in order anyway. 1037 if (Op.isUse() || !SIInstrInfo::isVMEM(MI) || 1038 ScoreBrackets.hasOtherPendingVmemTypes(RegNo, 1039 getVmemType(MI))) { 1040 ScoreBrackets.determineWait( 1041 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait); 1042 ScoreBrackets.clearVgprVmemTypes(RegNo); 1043 } 1044 if (Op.isDef()) { 1045 ScoreBrackets.determineWait( 1046 EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait); 1047 } 1048 } 1049 ScoreBrackets.determineWait( 1050 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait); 1051 } 1052 } 1053 } 1054 } 1055 1056 // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0 1057 // occurs before the instruction. Doing it here prevents any additional 1058 // S_WAITCNTs from being emitted if the instruction was marked as 1059 // requiring a WAITCNT beforehand. 1060 if (MI.getOpcode() == AMDGPU::S_BARRIER && 1061 !ST->hasAutoWaitcntBeforeBarrier()) { 1062 Wait = Wait.combined(AMDGPU::Waitcnt::allZero(ST->hasVscnt())); 1063 } 1064 1065 // TODO: Remove this work-around, enable the assert for Bug 457939 1066 // after fixing the scheduler. Also, the Shader Compiler code is 1067 // independent of target. 1068 if (readsVCCZ(MI) && ST->hasReadVCCZBug()) { 1069 if (ScoreBrackets.getScoreLB(LGKM_CNT) < 1070 ScoreBrackets.getScoreUB(LGKM_CNT) && 1071 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) { 1072 Wait.LgkmCnt = 0; 1073 } 1074 } 1075 1076 // Early-out if no wait is indicated. 1077 if (!ScoreBrackets.simplifyWaitcnt(Wait) && !IsForceEmitWaitcnt) { 1078 bool Modified = false; 1079 if (OldWaitcntInstr) { 1080 for (auto II = OldWaitcntInstr->getIterator(), NextI = std::next(II); 1081 &*II != &MI; II = NextI, ++NextI) { 1082 if (II->isDebugInstr()) 1083 continue; 1084 1085 if (TrackedWaitcntSet.count(&*II)) { 1086 TrackedWaitcntSet.erase(&*II); 1087 II->eraseFromParent(); 1088 Modified = true; 1089 } else if (II->getOpcode() == AMDGPU::S_WAITCNT) { 1090 int64_t Imm = II->getOperand(0).getImm(); 1091 ScoreBrackets.applyWaitcnt(AMDGPU::decodeWaitcnt(IV, Imm)); 1092 } else { 1093 assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT); 1094 assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL); 1095 auto W = TII->getNamedOperand(*II, AMDGPU::OpName::simm16)->getImm(); 1096 ScoreBrackets.applyWaitcnt(AMDGPU::Waitcnt(~0u, ~0u, ~0u, W)); 1097 } 1098 } 1099 } 1100 return Modified; 1101 } 1102 1103 if (ForceEmitZeroWaitcnts) 1104 Wait = AMDGPU::Waitcnt::allZero(ST->hasVscnt()); 1105 1106 if (ForceEmitWaitcnt[VM_CNT]) 1107 Wait.VmCnt = 0; 1108 if (ForceEmitWaitcnt[EXP_CNT]) 1109 Wait.ExpCnt = 0; 1110 if (ForceEmitWaitcnt[LGKM_CNT]) 1111 Wait.LgkmCnt = 0; 1112 if (ForceEmitWaitcnt[VS_CNT]) 1113 Wait.VsCnt = 0; 1114 1115 ScoreBrackets.applyWaitcnt(Wait); 1116 1117 AMDGPU::Waitcnt OldWait; 1118 bool Modified = false; 1119 1120 if (OldWaitcntInstr) { 1121 for (auto II = OldWaitcntInstr->getIterator(), NextI = std::next(II); 1122 &*II != &MI; II = NextI, NextI++) { 1123 if (II->isDebugInstr()) 1124 continue; 1125 1126 if (II->getOpcode() == AMDGPU::S_WAITCNT) { 1127 unsigned IEnc = II->getOperand(0).getImm(); 1128 AMDGPU::Waitcnt IWait = AMDGPU::decodeWaitcnt(IV, IEnc); 1129 OldWait = OldWait.combined(IWait); 1130 if (!TrackedWaitcntSet.count(&*II)) 1131 Wait = Wait.combined(IWait); 1132 unsigned NewEnc = AMDGPU::encodeWaitcnt(IV, Wait); 1133 if (IEnc != NewEnc) { 1134 II->getOperand(0).setImm(NewEnc); 1135 Modified = true; 1136 } 1137 Wait.VmCnt = ~0u; 1138 Wait.LgkmCnt = ~0u; 1139 Wait.ExpCnt = ~0u; 1140 } else { 1141 assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT); 1142 assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL); 1143 1144 unsigned ICnt = TII->getNamedOperand(*II, AMDGPU::OpName::simm16) 1145 ->getImm(); 1146 OldWait.VsCnt = std::min(OldWait.VsCnt, ICnt); 1147 if (!TrackedWaitcntSet.count(&*II)) 1148 Wait.VsCnt = std::min(Wait.VsCnt, ICnt); 1149 if (Wait.VsCnt != ICnt) { 1150 TII->getNamedOperand(*II, AMDGPU::OpName::simm16)->setImm(Wait.VsCnt); 1151 Modified = true; 1152 } 1153 Wait.VsCnt = ~0u; 1154 } 1155 1156 LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n" 1157 << "Old Instr: " << MI 1158 << "New Instr: " << *II << '\n'); 1159 1160 if (!Wait.hasWait()) 1161 return Modified; 1162 } 1163 } 1164 1165 if (Wait.VmCnt != ~0u || Wait.LgkmCnt != ~0u || Wait.ExpCnt != ~0u) { 1166 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait); 1167 auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(), 1168 MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 1169 .addImm(Enc); 1170 TrackedWaitcntSet.insert(SWaitInst); 1171 Modified = true; 1172 1173 LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n" 1174 << "Old Instr: " << MI 1175 << "New Instr: " << *SWaitInst << '\n'); 1176 } 1177 1178 if (Wait.VsCnt != ~0u) { 1179 assert(ST->hasVscnt()); 1180 1181 auto SWaitInst = 1182 BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(), 1183 TII->get(AMDGPU::S_WAITCNT_VSCNT)) 1184 .addReg(AMDGPU::SGPR_NULL, RegState::Undef) 1185 .addImm(Wait.VsCnt); 1186 TrackedWaitcntSet.insert(SWaitInst); 1187 Modified = true; 1188 1189 LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n" 1190 << "Old Instr: " << MI 1191 << "New Instr: " << *SWaitInst << '\n'); 1192 } 1193 1194 return Modified; 1195 } 1196 1197 // This is a flat memory operation. Check to see if it has memory 1198 // tokens for both LDS and Memory, and if so mark it as a flat. 1199 bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const { 1200 if (MI.memoperands_empty()) 1201 return true; 1202 1203 for (const MachineMemOperand *Memop : MI.memoperands()) { 1204 unsigned AS = Memop->getAddrSpace(); 1205 if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) 1206 return true; 1207 } 1208 1209 return false; 1210 } 1211 1212 void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst, 1213 WaitcntBrackets *ScoreBrackets) { 1214 // Now look at the instruction opcode. If it is a memory access 1215 // instruction, update the upper-bound of the appropriate counter's 1216 // bracket and the destination operand scores. 1217 // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere. 1218 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) { 1219 if (TII->isAlwaysGDS(Inst.getOpcode()) || 1220 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) { 1221 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst); 1222 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst); 1223 } else { 1224 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst); 1225 } 1226 } else if (TII->isFLAT(Inst)) { 1227 assert(Inst.mayLoadOrStore()); 1228 1229 if (TII->usesVM_CNT(Inst)) { 1230 if (!ST->hasVscnt()) 1231 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst); 1232 else if (Inst.mayLoad() && 1233 AMDGPU::getAtomicRetOp(Inst.getOpcode()) == -1) 1234 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst); 1235 else 1236 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst); 1237 } 1238 1239 if (TII->usesLGKM_CNT(Inst)) { 1240 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst); 1241 1242 // This is a flat memory operation, so note it - it will require 1243 // that both the VM and LGKM be flushed to zero if it is pending when 1244 // a VM or LGKM dependency occurs. 1245 if (mayAccessLDSThroughFlat(Inst)) 1246 ScoreBrackets->setPendingFlat(); 1247 } 1248 } else if (SIInstrInfo::isVMEM(Inst) && 1249 // TODO: get a better carve out. 1250 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1 && 1251 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_SC && 1252 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_VOL && 1253 Inst.getOpcode() != AMDGPU::BUFFER_GL0_INV && 1254 Inst.getOpcode() != AMDGPU::BUFFER_GL1_INV) { 1255 if (!ST->hasVscnt()) 1256 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst); 1257 else if ((Inst.mayLoad() && 1258 AMDGPU::getAtomicRetOp(Inst.getOpcode()) == -1) || 1259 /* IMAGE_GET_RESINFO / IMAGE_GET_LOD */ 1260 (TII->isMIMG(Inst) && !Inst.mayLoad() && !Inst.mayStore())) 1261 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst); 1262 else if (Inst.mayStore()) 1263 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst); 1264 1265 if (ST->vmemWriteNeedsExpWaitcnt() && 1266 (Inst.mayStore() || AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1)) { 1267 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst); 1268 } 1269 } else if (TII->isSMRD(Inst)) { 1270 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst); 1271 } else if (Inst.isCall()) { 1272 if (callWaitsOnFunctionReturn(Inst)) { 1273 // Act as a wait on everything 1274 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt::allZero(ST->hasVscnt())); 1275 } else { 1276 // May need to way wait for anything. 1277 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt()); 1278 } 1279 } else { 1280 switch (Inst.getOpcode()) { 1281 case AMDGPU::S_SENDMSG: 1282 case AMDGPU::S_SENDMSGHALT: 1283 ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst); 1284 break; 1285 case AMDGPU::EXP: 1286 case AMDGPU::EXP_DONE: { 1287 int Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm(); 1288 if (Imm >= 32 && Imm <= 63) 1289 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst); 1290 else if (Imm >= 12 && Imm <= 15) 1291 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst); 1292 else 1293 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst); 1294 break; 1295 } 1296 case AMDGPU::S_MEMTIME: 1297 case AMDGPU::S_MEMREALTIME: 1298 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst); 1299 break; 1300 default: 1301 break; 1302 } 1303 } 1304 } 1305 1306 bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score, 1307 unsigned OtherScore) { 1308 unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift; 1309 unsigned OtherShifted = 1310 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift; 1311 Score = std::max(MyShifted, OtherShifted); 1312 return OtherShifted > MyShifted; 1313 } 1314 1315 /// Merge the pending events and associater score brackets of \p Other into 1316 /// this brackets status. 1317 /// 1318 /// Returns whether the merge resulted in a change that requires tighter waits 1319 /// (i.e. the merged brackets strictly dominate the original brackets). 1320 bool WaitcntBrackets::merge(const WaitcntBrackets &Other) { 1321 bool StrictDom = false; 1322 1323 VgprUB = std::max(VgprUB, Other.VgprUB); 1324 SgprUB = std::max(SgprUB, Other.SgprUB); 1325 1326 for (auto T : inst_counter_types()) { 1327 // Merge event flags for this counter 1328 const bool OldOutOfOrder = counterOutOfOrder(T); 1329 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[T]; 1330 const unsigned OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T]; 1331 if (OtherEvents & ~OldEvents) 1332 StrictDom = true; 1333 PendingEvents |= OtherEvents; 1334 1335 // Merge scores for this counter 1336 const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T]; 1337 const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T]; 1338 const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending); 1339 if (NewUB < ScoreLBs[T]) 1340 report_fatal_error("waitcnt score overflow"); 1341 1342 MergeInfo M; 1343 M.OldLB = ScoreLBs[T]; 1344 M.OtherLB = Other.ScoreLBs[T]; 1345 M.MyShift = NewUB - ScoreUBs[T]; 1346 M.OtherShift = NewUB - Other.ScoreUBs[T]; 1347 1348 ScoreUBs[T] = NewUB; 1349 1350 StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]); 1351 1352 bool RegStrictDom = false; 1353 for (int J = 0; J <= VgprUB; J++) { 1354 RegStrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]); 1355 } 1356 1357 if (T == VM_CNT) { 1358 for (int J = 0; J <= VgprUB; J++) { 1359 unsigned char NewVmemTypes = VgprVmemTypes[J] | Other.VgprVmemTypes[J]; 1360 RegStrictDom |= NewVmemTypes != VgprVmemTypes[J]; 1361 VgprVmemTypes[J] = NewVmemTypes; 1362 } 1363 } 1364 1365 if (T == LGKM_CNT) { 1366 for (int J = 0; J <= SgprUB; J++) { 1367 RegStrictDom |= mergeScore(M, SgprScores[J], Other.SgprScores[J]); 1368 } 1369 } 1370 1371 if (RegStrictDom && !OldOutOfOrder) 1372 StrictDom = true; 1373 } 1374 1375 return StrictDom; 1376 } 1377 1378 // Generate s_waitcnt instructions where needed. 1379 bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF, 1380 MachineBasicBlock &Block, 1381 WaitcntBrackets &ScoreBrackets) { 1382 bool Modified = false; 1383 1384 LLVM_DEBUG({ 1385 dbgs() << "*** Block" << Block.getNumber() << " ***"; 1386 ScoreBrackets.dump(); 1387 }); 1388 1389 // Assume VCCZ is correct at basic block boundaries, unless and until we need 1390 // to handle cases where that is not true. 1391 bool VCCZCorrect = true; 1392 1393 // Walk over the instructions. 1394 MachineInstr *OldWaitcntInstr = nullptr; 1395 1396 for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(), 1397 E = Block.instr_end(); 1398 Iter != E;) { 1399 MachineInstr &Inst = *Iter; 1400 1401 // Track pre-existing waitcnts from earlier iterations. 1402 if (Inst.getOpcode() == AMDGPU::S_WAITCNT || 1403 (Inst.getOpcode() == AMDGPU::S_WAITCNT_VSCNT && 1404 Inst.getOperand(0).isReg() && 1405 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL)) { 1406 if (!OldWaitcntInstr) 1407 OldWaitcntInstr = &Inst; 1408 ++Iter; 1409 continue; 1410 } 1411 1412 // We might need to restore vccz to its correct value for either of two 1413 // different reasons; see ST->hasReadVCCZBug() and 1414 // ST->partialVCCWritesUpdateVCCZ(). 1415 bool RestoreVCCZ = false; 1416 if (readsVCCZ(Inst)) { 1417 if (!VCCZCorrect) 1418 RestoreVCCZ = true; 1419 else if (ST->hasReadVCCZBug()) { 1420 // There is a hardware bug on CI/SI where SMRD instruction may corrupt 1421 // vccz bit, so when we detect that an instruction may read from a 1422 // corrupt vccz bit, we need to: 1423 // 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD 1424 // operations to complete. 1425 // 2. Restore the correct value of vccz by writing the current value 1426 // of vcc back to vcc. 1427 if (ScoreBrackets.getScoreLB(LGKM_CNT) < 1428 ScoreBrackets.getScoreUB(LGKM_CNT) && 1429 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) { 1430 RestoreVCCZ = true; 1431 } 1432 } 1433 } 1434 1435 if (TII->isSMRD(Inst)) { 1436 for (const MachineMemOperand *Memop : Inst.memoperands()) { 1437 const Value *Ptr = Memop->getValue(); 1438 SLoadAddresses.insert(std::make_pair(Ptr, Inst.getParent())); 1439 } 1440 } 1441 1442 if (!ST->partialVCCWritesUpdateVCCZ()) { 1443 // Up to gfx9, writes to vcc_lo and vcc_hi don't update vccz. 1444 // Writes to vcc will fix it. 1445 if (Inst.definesRegister(AMDGPU::VCC_LO) || 1446 Inst.definesRegister(AMDGPU::VCC_HI)) 1447 VCCZCorrect = false; 1448 else if (Inst.definesRegister(AMDGPU::VCC)) 1449 VCCZCorrect = true; 1450 } 1451 1452 // Generate an s_waitcnt instruction to be placed before 1453 // cur_Inst, if needed. 1454 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr); 1455 OldWaitcntInstr = nullptr; 1456 1457 updateEventWaitcntAfter(Inst, &ScoreBrackets); 1458 1459 #if 0 // TODO: implement resource type check controlled by options with ub = LB. 1460 // If this instruction generates a S_SETVSKIP because it is an 1461 // indexed resource, and we are on Tahiti, then it will also force 1462 // an S_WAITCNT vmcnt(0) 1463 if (RequireCheckResourceType(Inst, context)) { 1464 // Force the score to as if an S_WAITCNT vmcnt(0) is emitted. 1465 ScoreBrackets->setScoreLB(VM_CNT, 1466 ScoreBrackets->getScoreUB(VM_CNT)); 1467 } 1468 #endif 1469 1470 LLVM_DEBUG({ 1471 Inst.print(dbgs()); 1472 ScoreBrackets.dump(); 1473 }); 1474 1475 // TODO: Remove this work-around after fixing the scheduler and enable the 1476 // assert above. 1477 if (RestoreVCCZ) { 1478 // Restore the vccz bit. Any time a value is written to vcc, the vcc 1479 // bit is updated, so we can restore the bit by reading the value of 1480 // vcc and then writing it back to the register. 1481 BuildMI(Block, Inst, Inst.getDebugLoc(), 1482 TII->get(ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64), 1483 TRI->getVCC()) 1484 .addReg(TRI->getVCC()); 1485 VCCZCorrect = true; 1486 Modified = true; 1487 } 1488 1489 ++Iter; 1490 } 1491 1492 return Modified; 1493 } 1494 1495 bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) { 1496 ST = &MF.getSubtarget<GCNSubtarget>(); 1497 TII = ST->getInstrInfo(); 1498 TRI = &TII->getRegisterInfo(); 1499 MRI = &MF.getRegInfo(); 1500 IV = AMDGPU::getIsaVersion(ST->getCPU()); 1501 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1502 PDT = &getAnalysis<MachinePostDominatorTree>(); 1503 1504 ForceEmitZeroWaitcnts = ForceEmitZeroFlag; 1505 for (auto T : inst_counter_types()) 1506 ForceEmitWaitcnt[T] = false; 1507 1508 HardwareLimits.VmcntMax = AMDGPU::getVmcntBitMask(IV); 1509 HardwareLimits.ExpcntMax = AMDGPU::getExpcntBitMask(IV); 1510 HardwareLimits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV); 1511 HardwareLimits.VscntMax = ST->hasVscnt() ? 63 : 0; 1512 1513 unsigned NumVGPRsMax = ST->getAddressableNumVGPRs(); 1514 unsigned NumSGPRsMax = ST->getAddressableNumSGPRs(); 1515 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS); 1516 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS); 1517 1518 RegisterEncoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0); 1519 RegisterEncoding.VGPRL = RegisterEncoding.VGPR0 + NumVGPRsMax - 1; 1520 RegisterEncoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0); 1521 RegisterEncoding.SGPRL = RegisterEncoding.SGPR0 + NumSGPRsMax - 1; 1522 1523 TrackedWaitcntSet.clear(); 1524 BlockInfos.clear(); 1525 1526 // Keep iterating over the blocks in reverse post order, inserting and 1527 // updating s_waitcnt where needed, until a fix point is reached. 1528 for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF)) 1529 BlockInfos.insert({MBB, BlockInfo(MBB)}); 1530 1531 std::unique_ptr<WaitcntBrackets> Brackets; 1532 bool Modified = false; 1533 bool Repeat; 1534 do { 1535 Repeat = false; 1536 1537 for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE; 1538 ++BII) { 1539 BlockInfo &BI = BII->second; 1540 if (!BI.Dirty) 1541 continue; 1542 1543 if (BI.Incoming) { 1544 if (!Brackets) 1545 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming); 1546 else 1547 *Brackets = *BI.Incoming; 1548 } else { 1549 if (!Brackets) 1550 Brackets = std::make_unique<WaitcntBrackets>(ST); 1551 else 1552 *Brackets = WaitcntBrackets(ST); 1553 } 1554 1555 Modified |= insertWaitcntInBlock(MF, *BI.MBB, *Brackets); 1556 BI.Dirty = false; 1557 1558 if (Brackets->hasPending()) { 1559 BlockInfo *MoveBracketsToSucc = nullptr; 1560 for (MachineBasicBlock *Succ : BI.MBB->successors()) { 1561 auto SuccBII = BlockInfos.find(Succ); 1562 BlockInfo &SuccBI = SuccBII->second; 1563 if (!SuccBI.Incoming) { 1564 SuccBI.Dirty = true; 1565 if (SuccBII <= BII) 1566 Repeat = true; 1567 if (!MoveBracketsToSucc) { 1568 MoveBracketsToSucc = &SuccBI; 1569 } else { 1570 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets); 1571 } 1572 } else if (SuccBI.Incoming->merge(*Brackets)) { 1573 SuccBI.Dirty = true; 1574 if (SuccBII <= BII) 1575 Repeat = true; 1576 } 1577 } 1578 if (MoveBracketsToSucc) 1579 MoveBracketsToSucc->Incoming = std::move(Brackets); 1580 } 1581 } 1582 } while (Repeat); 1583 1584 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks; 1585 1586 bool HaveScalarStores = false; 1587 1588 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; 1589 ++BI) { 1590 MachineBasicBlock &MBB = *BI; 1591 1592 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; 1593 ++I) { 1594 if (!HaveScalarStores && TII->isScalarStore(*I)) 1595 HaveScalarStores = true; 1596 1597 if (I->getOpcode() == AMDGPU::S_ENDPGM || 1598 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) 1599 EndPgmBlocks.push_back(&MBB); 1600 } 1601 } 1602 1603 if (HaveScalarStores) { 1604 // If scalar writes are used, the cache must be flushed or else the next 1605 // wave to reuse the same scratch memory can be clobbered. 1606 // 1607 // Insert s_dcache_wb at wave termination points if there were any scalar 1608 // stores, and only if the cache hasn't already been flushed. This could be 1609 // improved by looking across blocks for flushes in postdominating blocks 1610 // from the stores but an explicitly requested flush is probably very rare. 1611 for (MachineBasicBlock *MBB : EndPgmBlocks) { 1612 bool SeenDCacheWB = false; 1613 1614 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; 1615 ++I) { 1616 if (I->getOpcode() == AMDGPU::S_DCACHE_WB) 1617 SeenDCacheWB = true; 1618 else if (TII->isScalarStore(*I)) 1619 SeenDCacheWB = false; 1620 1621 // FIXME: It would be better to insert this before a waitcnt if any. 1622 if ((I->getOpcode() == AMDGPU::S_ENDPGM || 1623 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) && 1624 !SeenDCacheWB) { 1625 Modified = true; 1626 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB)); 1627 } 1628 } 1629 } 1630 } 1631 1632 if (!MFI->isEntryFunction()) { 1633 // Wait for any outstanding memory operations that the input registers may 1634 // depend on. We can't track them and it's better to the wait after the 1635 // costly call sequence. 1636 1637 // TODO: Could insert earlier and schedule more liberally with operations 1638 // that only use caller preserved registers. 1639 MachineBasicBlock &EntryBB = MF.front(); 1640 MachineBasicBlock::iterator I = EntryBB.begin(); 1641 for (MachineBasicBlock::iterator E = EntryBB.end(); 1642 I != E && (I->isPHI() || I->isMetaInstruction()); ++I) 1643 ; 1644 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(0); 1645 if (ST->hasVscnt()) 1646 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT_VSCNT)) 1647 .addReg(AMDGPU::SGPR_NULL, RegState::Undef) 1648 .addImm(0); 1649 1650 Modified = true; 1651 } 1652 1653 return Modified; 1654 } 1655