1 //===-- SIMachineScheduler.cpp - SI Scheduler Interface -------------------===// 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 /// SI Machine Scheduler interface 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "SIMachineScheduler.h" 16 #include "AMDGPU.h" 17 #include "SIInstrInfo.h" 18 #include "SIRegisterInfo.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/CodeGen/LiveInterval.h" 22 #include "llvm/CodeGen/LiveIntervals.h" 23 #include "llvm/CodeGen/MachineInstr.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/MachineScheduler.h" 26 #include "llvm/CodeGen/RegisterPressure.h" 27 #include "llvm/CodeGen/SlotIndexes.h" 28 #include "llvm/CodeGen/TargetRegisterInfo.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <algorithm> 33 #include <cassert> 34 #include <map> 35 #include <set> 36 #include <utility> 37 #include <vector> 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "machine-scheduler" 42 43 // This scheduler implements a different scheduling algorithm than 44 // GenericScheduler. 45 // 46 // There are several specific architecture behaviours that can't be modelled 47 // for GenericScheduler: 48 // . When accessing the result of an SGPR load instruction, you have to wait 49 // for all the SGPR load instructions before your current instruction to 50 // have finished. 51 // . When accessing the result of an VGPR load instruction, you have to wait 52 // for all the VGPR load instructions previous to the VGPR load instruction 53 // you are interested in to finish. 54 // . The less the register pressure, the best load latencies are hidden 55 // 56 // Moreover some specifities (like the fact a lot of instructions in the shader 57 // have few dependencies) makes the generic scheduler have some unpredictable 58 // behaviours. For example when register pressure becomes high, it can either 59 // manage to prevent register pressure from going too high, or it can 60 // increase register pressure even more than if it hadn't taken register 61 // pressure into account. 62 // 63 // Also some other bad behaviours are generated, like loading at the beginning 64 // of the shader a constant in VGPR you won't need until the end of the shader. 65 // 66 // The scheduling problem for SI can distinguish three main parts: 67 // . Hiding high latencies (texture sampling, etc) 68 // . Hiding low latencies (SGPR constant loading, etc) 69 // . Keeping register usage low for better latency hiding and general 70 // performance 71 // 72 // Some other things can also affect performance, but are hard to predict 73 // (cache usage, the fact the HW can issue several instructions from different 74 // wavefronts if different types, etc) 75 // 76 // This scheduler tries to solve the scheduling problem by dividing it into 77 // simpler sub-problems. It divides the instructions into blocks, schedules 78 // locally inside the blocks where it takes care of low latencies, and then 79 // chooses the order of the blocks by taking care of high latencies. 80 // Dividing the instructions into blocks helps control keeping register 81 // usage low. 82 // 83 // First the instructions are put into blocks. 84 // We want the blocks help control register usage and hide high latencies 85 // later. To help control register usage, we typically want all local 86 // computations, when for example you create a result that can be comsummed 87 // right away, to be contained in a block. Block inputs and outputs would 88 // typically be important results that are needed in several locations of 89 // the shader. Since we do want blocks to help hide high latencies, we want 90 // the instructions inside the block to have a minimal set of dependencies 91 // on high latencies. It will make it easy to pick blocks to hide specific 92 // high latencies. 93 // The block creation algorithm is divided into several steps, and several 94 // variants can be tried during the scheduling process. 95 // 96 // Second the order of the instructions inside the blocks is chosen. 97 // At that step we do take into account only register usage and hiding 98 // low latency instructions 99 // 100 // Third the block order is chosen, there we try to hide high latencies 101 // and keep register usage low. 102 // 103 // After the third step, a pass is done to improve the hiding of low 104 // latencies. 105 // 106 // Actually when talking about 'low latency' or 'high latency' it includes 107 // both the latency to get the cache (or global mem) data go to the register, 108 // and the bandwidth limitations. 109 // Increasing the number of active wavefronts helps hide the former, but it 110 // doesn't solve the latter, thus why even if wavefront count is high, we have 111 // to try have as many instructions hiding high latencies as possible. 112 // The OpenCL doc says for example latency of 400 cycles for a global mem access, 113 // which is hidden by 10 instructions if the wavefront count is 10. 114 115 // Some figures taken from AMD docs: 116 // Both texture and constant L1 caches are 4-way associative with 64 bytes 117 // lines. 118 // Constant cache is shared with 4 CUs. 119 // For texture sampling, the address generation unit receives 4 texture 120 // addresses per cycle, thus we could expect texture sampling latency to be 121 // equivalent to 4 instructions in the very best case (a VGPR is 64 work items, 122 // instructions in a wavefront group are executed every 4 cycles), 123 // or 16 instructions if the other wavefronts associated to the 3 other VALUs 124 // of the CU do texture sampling too. (Don't take these figures too seriously, 125 // as I'm not 100% sure of the computation) 126 // Data exports should get similar latency. 127 // For constant loading, the cache is shader with 4 CUs. 128 // The doc says "a throughput of 16B/cycle for each of the 4 Compute Unit" 129 // I guess if the other CU don't read the cache, it can go up to 64B/cycle. 130 // It means a simple s_buffer_load should take one instruction to hide, as 131 // well as a s_buffer_loadx2 and potentially a s_buffer_loadx8 if on the same 132 // cache line. 133 // 134 // As of today the driver doesn't preload the constants in cache, thus the 135 // first loads get extra latency. The doc says global memory access can be 136 // 300-600 cycles. We do not specially take that into account when scheduling 137 // As we expect the driver to be able to preload the constants soon. 138 139 // common code // 140 141 #ifndef NDEBUG 142 143 static const char *getReasonStr(SIScheduleCandReason Reason) { 144 switch (Reason) { 145 case NoCand: return "NOCAND"; 146 case RegUsage: return "REGUSAGE"; 147 case Latency: return "LATENCY"; 148 case Successor: return "SUCCESSOR"; 149 case Depth: return "DEPTH"; 150 case NodeOrder: return "ORDER"; 151 } 152 llvm_unreachable("Unknown reason!"); 153 } 154 155 #endif 156 157 namespace llvm { 158 namespace SISched { 159 static bool tryLess(int TryVal, int CandVal, 160 SISchedulerCandidate &TryCand, 161 SISchedulerCandidate &Cand, 162 SIScheduleCandReason Reason) { 163 if (TryVal < CandVal) { 164 TryCand.Reason = Reason; 165 return true; 166 } 167 if (TryVal > CandVal) { 168 if (Cand.Reason > Reason) 169 Cand.Reason = Reason; 170 return true; 171 } 172 Cand.setRepeat(Reason); 173 return false; 174 } 175 176 static bool tryGreater(int TryVal, int CandVal, 177 SISchedulerCandidate &TryCand, 178 SISchedulerCandidate &Cand, 179 SIScheduleCandReason Reason) { 180 if (TryVal > CandVal) { 181 TryCand.Reason = Reason; 182 return true; 183 } 184 if (TryVal < CandVal) { 185 if (Cand.Reason > Reason) 186 Cand.Reason = Reason; 187 return true; 188 } 189 Cand.setRepeat(Reason); 190 return false; 191 } 192 } // end namespace SISched 193 } // end namespace llvm 194 195 // SIScheduleBlock // 196 197 void SIScheduleBlock::addUnit(SUnit *SU) { 198 NodeNum2Index[SU->NodeNum] = SUnits.size(); 199 SUnits.push_back(SU); 200 } 201 202 #ifndef NDEBUG 203 void SIScheduleBlock::traceCandidate(const SISchedCandidate &Cand) { 204 205 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason); 206 dbgs() << '\n'; 207 } 208 #endif 209 210 void SIScheduleBlock::tryCandidateTopDown(SISchedCandidate &Cand, 211 SISchedCandidate &TryCand) { 212 // Initialize the candidate if needed. 213 if (!Cand.isValid()) { 214 TryCand.Reason = NodeOrder; 215 return; 216 } 217 218 if (Cand.SGPRUsage > 60 && 219 SISched::tryLess(TryCand.SGPRUsage, Cand.SGPRUsage, 220 TryCand, Cand, RegUsage)) 221 return; 222 223 // Schedule low latency instructions as top as possible. 224 // Order of priority is: 225 // . Low latency instructions which do not depend on other low latency 226 // instructions we haven't waited for 227 // . Other instructions which do not depend on low latency instructions 228 // we haven't waited for 229 // . Low latencies 230 // . All other instructions 231 // Goal is to get: low latency instructions - independent instructions 232 // - (eventually some more low latency instructions) 233 // - instructions that depend on the first low latency instructions. 234 // If in the block there is a lot of constant loads, the SGPR usage 235 // could go quite high, thus above the arbitrary limit of 60 will encourage 236 // use the already loaded constants (in order to release some SGPRs) before 237 // loading more. 238 if (SISched::tryLess(TryCand.HasLowLatencyNonWaitedParent, 239 Cand.HasLowLatencyNonWaitedParent, 240 TryCand, Cand, SIScheduleCandReason::Depth)) 241 return; 242 243 if (SISched::tryGreater(TryCand.IsLowLatency, Cand.IsLowLatency, 244 TryCand, Cand, SIScheduleCandReason::Depth)) 245 return; 246 247 if (TryCand.IsLowLatency && 248 SISched::tryLess(TryCand.LowLatencyOffset, Cand.LowLatencyOffset, 249 TryCand, Cand, SIScheduleCandReason::Depth)) 250 return; 251 252 if (SISched::tryLess(TryCand.VGPRUsage, Cand.VGPRUsage, 253 TryCand, Cand, RegUsage)) 254 return; 255 256 // Fall through to original instruction order. 257 if (TryCand.SU->NodeNum < Cand.SU->NodeNum) { 258 TryCand.Reason = NodeOrder; 259 } 260 } 261 262 SUnit* SIScheduleBlock::pickNode() { 263 SISchedCandidate TopCand; 264 265 for (SUnit* SU : TopReadySUs) { 266 SISchedCandidate TryCand; 267 std::vector<unsigned> pressure; 268 std::vector<unsigned> MaxPressure; 269 // Predict register usage after this instruction. 270 TryCand.SU = SU; 271 TopRPTracker.getDownwardPressure(SU->getInstr(), pressure, MaxPressure); 272 TryCand.SGPRUsage = pressure[DAG->getSGPRSetID()]; 273 TryCand.VGPRUsage = pressure[DAG->getVGPRSetID()]; 274 TryCand.IsLowLatency = DAG->IsLowLatencySU[SU->NodeNum]; 275 TryCand.LowLatencyOffset = DAG->LowLatencyOffset[SU->NodeNum]; 276 TryCand.HasLowLatencyNonWaitedParent = 277 HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]]; 278 tryCandidateTopDown(TopCand, TryCand); 279 if (TryCand.Reason != NoCand) 280 TopCand.setBest(TryCand); 281 } 282 283 return TopCand.SU; 284 } 285 286 287 // Schedule something valid. 288 void SIScheduleBlock::fastSchedule() { 289 TopReadySUs.clear(); 290 if (Scheduled) 291 undoSchedule(); 292 293 for (SUnit* SU : SUnits) { 294 if (!SU->NumPredsLeft) 295 TopReadySUs.push_back(SU); 296 } 297 298 while (!TopReadySUs.empty()) { 299 SUnit *SU = TopReadySUs[0]; 300 ScheduledSUnits.push_back(SU); 301 nodeScheduled(SU); 302 } 303 304 Scheduled = true; 305 } 306 307 // Returns if the register was set between first and last. 308 static bool isDefBetween(unsigned Reg, 309 SlotIndex First, SlotIndex Last, 310 const MachineRegisterInfo *MRI, 311 const LiveIntervals *LIS) { 312 for (MachineRegisterInfo::def_instr_iterator 313 UI = MRI->def_instr_begin(Reg), 314 UE = MRI->def_instr_end(); UI != UE; ++UI) { 315 const MachineInstr* MI = &*UI; 316 if (MI->isDebugValue()) 317 continue; 318 SlotIndex InstSlot = LIS->getInstructionIndex(*MI).getRegSlot(); 319 if (InstSlot >= First && InstSlot <= Last) 320 return true; 321 } 322 return false; 323 } 324 325 void SIScheduleBlock::initRegPressure(MachineBasicBlock::iterator BeginBlock, 326 MachineBasicBlock::iterator EndBlock) { 327 IntervalPressure Pressure, BotPressure; 328 RegPressureTracker RPTracker(Pressure), BotRPTracker(BotPressure); 329 LiveIntervals *LIS = DAG->getLIS(); 330 MachineRegisterInfo *MRI = DAG->getMRI(); 331 DAG->initRPTracker(TopRPTracker); 332 DAG->initRPTracker(BotRPTracker); 333 DAG->initRPTracker(RPTracker); 334 335 // Goes though all SU. RPTracker captures what had to be alive for the SUs 336 // to execute, and what is still alive at the end. 337 for (SUnit* SU : ScheduledSUnits) { 338 RPTracker.setPos(SU->getInstr()); 339 RPTracker.advance(); 340 } 341 342 // Close the RPTracker to finalize live ins/outs. 343 RPTracker.closeRegion(); 344 345 // Initialize the live ins and live outs. 346 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs); 347 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs); 348 349 // Do not Track Physical Registers, because it messes up. 350 for (const auto &RegMaskPair : RPTracker.getPressure().LiveInRegs) { 351 if (TargetRegisterInfo::isVirtualRegister(RegMaskPair.RegUnit)) 352 LiveInRegs.insert(RegMaskPair.RegUnit); 353 } 354 LiveOutRegs.clear(); 355 // There is several possibilities to distinguish: 356 // 1) Reg is not input to any instruction in the block, but is output of one 357 // 2) 1) + read in the block and not needed after it 358 // 3) 1) + read in the block but needed in another block 359 // 4) Reg is input of an instruction but another block will read it too 360 // 5) Reg is input of an instruction and then rewritten in the block. 361 // result is not read in the block (implies used in another block) 362 // 6) Reg is input of an instruction and then rewritten in the block. 363 // result is read in the block and not needed in another block 364 // 7) Reg is input of an instruction and then rewritten in the block. 365 // result is read in the block but also needed in another block 366 // LiveInRegs will contains all the regs in situation 4, 5, 6, 7 367 // We want LiveOutRegs to contain only Regs whose content will be read after 368 // in another block, and whose content was written in the current block, 369 // that is we want it to get 1, 3, 5, 7 370 // Since we made the MIs of a block to be packed all together before 371 // scheduling, then the LiveIntervals were correct, and the RPTracker was 372 // able to correctly handle 5 vs 6, 2 vs 3. 373 // (Note: This is not sufficient for RPTracker to not do mistakes for case 4) 374 // The RPTracker's LiveOutRegs has 1, 3, (some correct or incorrect)4, 5, 7 375 // Comparing to LiveInRegs is not sufficient to differenciate 4 vs 5, 7 376 // The use of findDefBetween removes the case 4. 377 for (const auto &RegMaskPair : RPTracker.getPressure().LiveOutRegs) { 378 unsigned Reg = RegMaskPair.RegUnit; 379 if (TargetRegisterInfo::isVirtualRegister(Reg) && 380 isDefBetween(Reg, LIS->getInstructionIndex(*BeginBlock).getRegSlot(), 381 LIS->getInstructionIndex(*EndBlock).getRegSlot(), MRI, 382 LIS)) { 383 LiveOutRegs.insert(Reg); 384 } 385 } 386 387 // Pressure = sum_alive_registers register size 388 // Internally llvm will represent some registers as big 128 bits registers 389 // for example, but they actually correspond to 4 actual 32 bits registers. 390 // Thus Pressure is not equal to num_alive_registers * constant. 391 LiveInPressure = TopPressure.MaxSetPressure; 392 LiveOutPressure = BotPressure.MaxSetPressure; 393 394 // Prepares TopRPTracker for top down scheduling. 395 TopRPTracker.closeTop(); 396 } 397 398 void SIScheduleBlock::schedule(MachineBasicBlock::iterator BeginBlock, 399 MachineBasicBlock::iterator EndBlock) { 400 if (!Scheduled) 401 fastSchedule(); 402 403 // PreScheduling phase to set LiveIn and LiveOut. 404 initRegPressure(BeginBlock, EndBlock); 405 undoSchedule(); 406 407 // Schedule for real now. 408 409 TopReadySUs.clear(); 410 411 for (SUnit* SU : SUnits) { 412 if (!SU->NumPredsLeft) 413 TopReadySUs.push_back(SU); 414 } 415 416 while (!TopReadySUs.empty()) { 417 SUnit *SU = pickNode(); 418 ScheduledSUnits.push_back(SU); 419 TopRPTracker.setPos(SU->getInstr()); 420 TopRPTracker.advance(); 421 nodeScheduled(SU); 422 } 423 424 // TODO: compute InternalAdditionnalPressure. 425 InternalAdditionnalPressure.resize(TopPressure.MaxSetPressure.size()); 426 427 // Check everything is right. 428 #ifndef NDEBUG 429 assert(SUnits.size() == ScheduledSUnits.size() && 430 TopReadySUs.empty()); 431 for (SUnit* SU : SUnits) { 432 assert(SU->isScheduled && 433 SU->NumPredsLeft == 0); 434 } 435 #endif 436 437 Scheduled = true; 438 } 439 440 void SIScheduleBlock::undoSchedule() { 441 for (SUnit* SU : SUnits) { 442 SU->isScheduled = false; 443 for (SDep& Succ : SU->Succs) { 444 if (BC->isSUInBlock(Succ.getSUnit(), ID)) 445 undoReleaseSucc(SU, &Succ); 446 } 447 } 448 HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0); 449 ScheduledSUnits.clear(); 450 Scheduled = false; 451 } 452 453 void SIScheduleBlock::undoReleaseSucc(SUnit *SU, SDep *SuccEdge) { 454 SUnit *SuccSU = SuccEdge->getSUnit(); 455 456 if (SuccEdge->isWeak()) { 457 ++SuccSU->WeakPredsLeft; 458 return; 459 } 460 ++SuccSU->NumPredsLeft; 461 } 462 463 void SIScheduleBlock::releaseSucc(SUnit *SU, SDep *SuccEdge) { 464 SUnit *SuccSU = SuccEdge->getSUnit(); 465 466 if (SuccEdge->isWeak()) { 467 --SuccSU->WeakPredsLeft; 468 return; 469 } 470 #ifndef NDEBUG 471 if (SuccSU->NumPredsLeft == 0) { 472 dbgs() << "*** Scheduling failed! ***\n"; 473 SuccSU->dump(DAG); 474 dbgs() << " has been released too many times!\n"; 475 llvm_unreachable(nullptr); 476 } 477 #endif 478 479 --SuccSU->NumPredsLeft; 480 } 481 482 /// Release Successors of the SU that are in the block or not. 483 void SIScheduleBlock::releaseSuccessors(SUnit *SU, bool InOrOutBlock) { 484 for (SDep& Succ : SU->Succs) { 485 SUnit *SuccSU = Succ.getSUnit(); 486 487 if (SuccSU->NodeNum >= DAG->SUnits.size()) 488 continue; 489 490 if (BC->isSUInBlock(SuccSU, ID) != InOrOutBlock) 491 continue; 492 493 releaseSucc(SU, &Succ); 494 if (SuccSU->NumPredsLeft == 0 && InOrOutBlock) 495 TopReadySUs.push_back(SuccSU); 496 } 497 } 498 499 void SIScheduleBlock::nodeScheduled(SUnit *SU) { 500 // Is in TopReadySUs 501 assert (!SU->NumPredsLeft); 502 std::vector<SUnit *>::iterator I = llvm::find(TopReadySUs, SU); 503 if (I == TopReadySUs.end()) { 504 dbgs() << "Data Structure Bug in SI Scheduler\n"; 505 llvm_unreachable(nullptr); 506 } 507 TopReadySUs.erase(I); 508 509 releaseSuccessors(SU, true); 510 // Scheduling this node will trigger a wait, 511 // thus propagate to other instructions that they do not need to wait either. 512 if (HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]]) 513 HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0); 514 515 if (DAG->IsLowLatencySU[SU->NodeNum]) { 516 for (SDep& Succ : SU->Succs) { 517 std::map<unsigned, unsigned>::iterator I = 518 NodeNum2Index.find(Succ.getSUnit()->NodeNum); 519 if (I != NodeNum2Index.end()) 520 HasLowLatencyNonWaitedParent[I->second] = 1; 521 } 522 } 523 SU->isScheduled = true; 524 } 525 526 void SIScheduleBlock::finalizeUnits() { 527 // We remove links from outside blocks to enable scheduling inside the block. 528 for (SUnit* SU : SUnits) { 529 releaseSuccessors(SU, false); 530 if (DAG->IsHighLatencySU[SU->NodeNum]) 531 HighLatencyBlock = true; 532 } 533 HasLowLatencyNonWaitedParent.resize(SUnits.size(), 0); 534 } 535 536 // we maintain ascending order of IDs 537 void SIScheduleBlock::addPred(SIScheduleBlock *Pred) { 538 unsigned PredID = Pred->getID(); 539 540 // Check if not already predecessor. 541 for (SIScheduleBlock* P : Preds) { 542 if (PredID == P->getID()) 543 return; 544 } 545 Preds.push_back(Pred); 546 547 assert(none_of(Succs, 548 [=](std::pair<SIScheduleBlock*, 549 SIScheduleBlockLinkKind> S) { 550 return PredID == S.first->getID(); 551 }) && 552 "Loop in the Block Graph!"); 553 } 554 555 void SIScheduleBlock::addSucc(SIScheduleBlock *Succ, 556 SIScheduleBlockLinkKind Kind) { 557 unsigned SuccID = Succ->getID(); 558 559 // Check if not already predecessor. 560 for (std::pair<SIScheduleBlock*, SIScheduleBlockLinkKind> &S : Succs) { 561 if (SuccID == S.first->getID()) { 562 if (S.second == SIScheduleBlockLinkKind::NoData && 563 Kind == SIScheduleBlockLinkKind::Data) 564 S.second = Kind; 565 return; 566 } 567 } 568 if (Succ->isHighLatencyBlock()) 569 ++NumHighLatencySuccessors; 570 Succs.push_back(std::make_pair(Succ, Kind)); 571 572 assert(none_of(Preds, 573 [=](SIScheduleBlock *P) { return SuccID == P->getID(); }) && 574 "Loop in the Block Graph!"); 575 } 576 577 #ifndef NDEBUG 578 void SIScheduleBlock::printDebug(bool full) { 579 dbgs() << "Block (" << ID << ")\n"; 580 if (!full) 581 return; 582 583 dbgs() << "\nContains High Latency Instruction: " 584 << HighLatencyBlock << '\n'; 585 dbgs() << "\nDepends On:\n"; 586 for (SIScheduleBlock* P : Preds) { 587 P->printDebug(false); 588 } 589 590 dbgs() << "\nSuccessors:\n"; 591 for (std::pair<SIScheduleBlock*, SIScheduleBlockLinkKind> S : Succs) { 592 if (S.second == SIScheduleBlockLinkKind::Data) 593 dbgs() << "(Data Dep) "; 594 S.first->printDebug(false); 595 } 596 597 if (Scheduled) { 598 dbgs() << "LiveInPressure " << LiveInPressure[DAG->getSGPRSetID()] << ' ' 599 << LiveInPressure[DAG->getVGPRSetID()] << '\n'; 600 dbgs() << "LiveOutPressure " << LiveOutPressure[DAG->getSGPRSetID()] << ' ' 601 << LiveOutPressure[DAG->getVGPRSetID()] << "\n\n"; 602 dbgs() << "LiveIns:\n"; 603 for (unsigned Reg : LiveInRegs) 604 dbgs() << printVRegOrUnit(Reg, DAG->getTRI()) << ' '; 605 606 dbgs() << "\nLiveOuts:\n"; 607 for (unsigned Reg : LiveOutRegs) 608 dbgs() << printVRegOrUnit(Reg, DAG->getTRI()) << ' '; 609 } 610 611 dbgs() << "\nInstructions:\n"; 612 if (!Scheduled) { 613 for (SUnit* SU : SUnits) { 614 SU->dump(DAG); 615 } 616 } else { 617 for (SUnit* SU : SUnits) { 618 SU->dump(DAG); 619 } 620 } 621 622 dbgs() << "///////////////////////\n"; 623 } 624 #endif 625 626 // SIScheduleBlockCreator // 627 628 SIScheduleBlockCreator::SIScheduleBlockCreator(SIScheduleDAGMI *DAG) : 629 DAG(DAG) { 630 } 631 632 SIScheduleBlockCreator::~SIScheduleBlockCreator() = default; 633 634 SIScheduleBlocks 635 SIScheduleBlockCreator::getBlocks(SISchedulerBlockCreatorVariant BlockVariant) { 636 std::map<SISchedulerBlockCreatorVariant, SIScheduleBlocks>::iterator B = 637 Blocks.find(BlockVariant); 638 if (B == Blocks.end()) { 639 SIScheduleBlocks Res; 640 createBlocksForVariant(BlockVariant); 641 topologicalSort(); 642 scheduleInsideBlocks(); 643 fillStats(); 644 Res.Blocks = CurrentBlocks; 645 Res.TopDownIndex2Block = TopDownIndex2Block; 646 Res.TopDownBlock2Index = TopDownBlock2Index; 647 Blocks[BlockVariant] = Res; 648 return Res; 649 } else { 650 return B->second; 651 } 652 } 653 654 bool SIScheduleBlockCreator::isSUInBlock(SUnit *SU, unsigned ID) { 655 if (SU->NodeNum >= DAG->SUnits.size()) 656 return false; 657 return CurrentBlocks[Node2CurrentBlock[SU->NodeNum]]->getID() == ID; 658 } 659 660 void SIScheduleBlockCreator::colorHighLatenciesAlone() { 661 unsigned DAGSize = DAG->SUnits.size(); 662 663 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 664 SUnit *SU = &DAG->SUnits[i]; 665 if (DAG->IsHighLatencySU[SU->NodeNum]) { 666 CurrentColoring[SU->NodeNum] = NextReservedID++; 667 } 668 } 669 } 670 671 static bool 672 hasDataDependencyPred(const SUnit &SU, const SUnit &FromSU) { 673 for (const auto &PredDep : SU.Preds) { 674 if (PredDep.getSUnit() == &FromSU && 675 PredDep.getKind() == llvm::SDep::Data) 676 return true; 677 } 678 return false; 679 } 680 681 void SIScheduleBlockCreator::colorHighLatenciesGroups() { 682 unsigned DAGSize = DAG->SUnits.size(); 683 unsigned NumHighLatencies = 0; 684 unsigned GroupSize; 685 int Color = NextReservedID; 686 unsigned Count = 0; 687 std::set<unsigned> FormingGroup; 688 689 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 690 SUnit *SU = &DAG->SUnits[i]; 691 if (DAG->IsHighLatencySU[SU->NodeNum]) 692 ++NumHighLatencies; 693 } 694 695 if (NumHighLatencies == 0) 696 return; 697 698 if (NumHighLatencies <= 6) 699 GroupSize = 2; 700 else if (NumHighLatencies <= 12) 701 GroupSize = 3; 702 else 703 GroupSize = 4; 704 705 for (unsigned SUNum : DAG->TopDownIndex2SU) { 706 const SUnit &SU = DAG->SUnits[SUNum]; 707 if (DAG->IsHighLatencySU[SU.NodeNum]) { 708 unsigned CompatibleGroup = true; 709 int ProposedColor = Color; 710 std::vector<int> AdditionalElements; 711 712 // We don't want to put in the same block 713 // two high latency instructions that depend 714 // on each other. 715 // One way would be to check canAddEdge 716 // in both directions, but that currently is not 717 // enough because there the high latency order is 718 // enforced (via links). 719 // Instead, look at the dependencies between the 720 // high latency instructions and deduce if it is 721 // a data dependency or not. 722 for (unsigned j : FormingGroup) { 723 bool HasSubGraph; 724 std::vector<int> SubGraph; 725 // By construction (topological order), if SU and 726 // DAG->SUnits[j] are linked, DAG->SUnits[j] is neccessary 727 // in the parent graph of SU. 728 #ifndef NDEBUG 729 SubGraph = DAG->GetTopo()->GetSubGraph(SU, DAG->SUnits[j], 730 HasSubGraph); 731 assert(!HasSubGraph); 732 #endif 733 SubGraph = DAG->GetTopo()->GetSubGraph(DAG->SUnits[j], SU, 734 HasSubGraph); 735 if (!HasSubGraph) 736 continue; // No dependencies between each other 737 else if (SubGraph.size() > 5) { 738 // Too many elements would be required to be added to the block. 739 CompatibleGroup = false; 740 break; 741 } 742 else { 743 // Check the type of dependency 744 for (unsigned k : SubGraph) { 745 // If in the path to join the two instructions, 746 // there is another high latency instruction, 747 // or instructions colored for another block 748 // abort the merge. 749 if (DAG->IsHighLatencySU[k] || 750 (CurrentColoring[k] != ProposedColor && 751 CurrentColoring[k] != 0)) { 752 CompatibleGroup = false; 753 break; 754 } 755 // If one of the SU in the subgraph depends on the result of SU j, 756 // there'll be a data dependency. 757 if (hasDataDependencyPred(DAG->SUnits[k], DAG->SUnits[j])) { 758 CompatibleGroup = false; 759 break; 760 } 761 } 762 if (!CompatibleGroup) 763 break; 764 // Same check for the SU 765 if (hasDataDependencyPred(SU, DAG->SUnits[j])) { 766 CompatibleGroup = false; 767 break; 768 } 769 // Add all the required instructions to the block 770 // These cannot live in another block (because they 771 // depend (order dependency) on one of the 772 // instruction in the block, and are required for the 773 // high latency instruction we add. 774 AdditionalElements.insert(AdditionalElements.end(), 775 SubGraph.begin(), SubGraph.end()); 776 } 777 } 778 if (CompatibleGroup) { 779 FormingGroup.insert(SU.NodeNum); 780 for (unsigned j : AdditionalElements) 781 CurrentColoring[j] = ProposedColor; 782 CurrentColoring[SU.NodeNum] = ProposedColor; 783 ++Count; 784 } 785 // Found one incompatible instruction, 786 // or has filled a big enough group. 787 // -> start a new one. 788 if (!CompatibleGroup) { 789 FormingGroup.clear(); 790 Color = ++NextReservedID; 791 ProposedColor = Color; 792 FormingGroup.insert(SU.NodeNum); 793 CurrentColoring[SU.NodeNum] = ProposedColor; 794 Count = 0; 795 } else if (Count == GroupSize) { 796 FormingGroup.clear(); 797 Color = ++NextReservedID; 798 ProposedColor = Color; 799 Count = 0; 800 } 801 } 802 } 803 } 804 805 void SIScheduleBlockCreator::colorComputeReservedDependencies() { 806 unsigned DAGSize = DAG->SUnits.size(); 807 std::map<std::set<unsigned>, unsigned> ColorCombinations; 808 809 CurrentTopDownReservedDependencyColoring.clear(); 810 CurrentBottomUpReservedDependencyColoring.clear(); 811 812 CurrentTopDownReservedDependencyColoring.resize(DAGSize, 0); 813 CurrentBottomUpReservedDependencyColoring.resize(DAGSize, 0); 814 815 // Traverse TopDown, and give different colors to SUs depending 816 // on which combination of High Latencies they depend on. 817 818 for (unsigned SUNum : DAG->TopDownIndex2SU) { 819 SUnit *SU = &DAG->SUnits[SUNum]; 820 std::set<unsigned> SUColors; 821 822 // Already given. 823 if (CurrentColoring[SU->NodeNum]) { 824 CurrentTopDownReservedDependencyColoring[SU->NodeNum] = 825 CurrentColoring[SU->NodeNum]; 826 continue; 827 } 828 829 for (SDep& PredDep : SU->Preds) { 830 SUnit *Pred = PredDep.getSUnit(); 831 if (PredDep.isWeak() || Pred->NodeNum >= DAGSize) 832 continue; 833 if (CurrentTopDownReservedDependencyColoring[Pred->NodeNum] > 0) 834 SUColors.insert(CurrentTopDownReservedDependencyColoring[Pred->NodeNum]); 835 } 836 // Color 0 by default. 837 if (SUColors.empty()) 838 continue; 839 // Same color than parents. 840 if (SUColors.size() == 1 && *SUColors.begin() > DAGSize) 841 CurrentTopDownReservedDependencyColoring[SU->NodeNum] = 842 *SUColors.begin(); 843 else { 844 std::map<std::set<unsigned>, unsigned>::iterator Pos = 845 ColorCombinations.find(SUColors); 846 if (Pos != ColorCombinations.end()) { 847 CurrentTopDownReservedDependencyColoring[SU->NodeNum] = Pos->second; 848 } else { 849 CurrentTopDownReservedDependencyColoring[SU->NodeNum] = 850 NextNonReservedID; 851 ColorCombinations[SUColors] = NextNonReservedID++; 852 } 853 } 854 } 855 856 ColorCombinations.clear(); 857 858 // Same as before, but BottomUp. 859 860 for (unsigned SUNum : DAG->BottomUpIndex2SU) { 861 SUnit *SU = &DAG->SUnits[SUNum]; 862 std::set<unsigned> SUColors; 863 864 // Already given. 865 if (CurrentColoring[SU->NodeNum]) { 866 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] = 867 CurrentColoring[SU->NodeNum]; 868 continue; 869 } 870 871 for (SDep& SuccDep : SU->Succs) { 872 SUnit *Succ = SuccDep.getSUnit(); 873 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize) 874 continue; 875 if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0) 876 SUColors.insert(CurrentBottomUpReservedDependencyColoring[Succ->NodeNum]); 877 } 878 // Keep color 0. 879 if (SUColors.empty()) 880 continue; 881 // Same color than parents. 882 if (SUColors.size() == 1 && *SUColors.begin() > DAGSize) 883 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] = 884 *SUColors.begin(); 885 else { 886 std::map<std::set<unsigned>, unsigned>::iterator Pos = 887 ColorCombinations.find(SUColors); 888 if (Pos != ColorCombinations.end()) { 889 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] = Pos->second; 890 } else { 891 CurrentBottomUpReservedDependencyColoring[SU->NodeNum] = 892 NextNonReservedID; 893 ColorCombinations[SUColors] = NextNonReservedID++; 894 } 895 } 896 } 897 } 898 899 void SIScheduleBlockCreator::colorAccordingToReservedDependencies() { 900 unsigned DAGSize = DAG->SUnits.size(); 901 std::map<std::pair<unsigned, unsigned>, unsigned> ColorCombinations; 902 903 // Every combination of colors given by the top down 904 // and bottom up Reserved node dependency 905 906 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 907 SUnit *SU = &DAG->SUnits[i]; 908 std::pair<unsigned, unsigned> SUColors; 909 910 // High latency instructions: already given. 911 if (CurrentColoring[SU->NodeNum]) 912 continue; 913 914 SUColors.first = CurrentTopDownReservedDependencyColoring[SU->NodeNum]; 915 SUColors.second = CurrentBottomUpReservedDependencyColoring[SU->NodeNum]; 916 917 std::map<std::pair<unsigned, unsigned>, unsigned>::iterator Pos = 918 ColorCombinations.find(SUColors); 919 if (Pos != ColorCombinations.end()) { 920 CurrentColoring[SU->NodeNum] = Pos->second; 921 } else { 922 CurrentColoring[SU->NodeNum] = NextNonReservedID; 923 ColorCombinations[SUColors] = NextNonReservedID++; 924 } 925 } 926 } 927 928 void SIScheduleBlockCreator::colorEndsAccordingToDependencies() { 929 unsigned DAGSize = DAG->SUnits.size(); 930 std::vector<int> PendingColoring = CurrentColoring; 931 932 assert(DAGSize >= 1 && 933 CurrentBottomUpReservedDependencyColoring.size() == DAGSize && 934 CurrentTopDownReservedDependencyColoring.size() == DAGSize); 935 // If there is no reserved block at all, do nothing. We don't want 936 // everything in one block. 937 if (*std::max_element(CurrentBottomUpReservedDependencyColoring.begin(), 938 CurrentBottomUpReservedDependencyColoring.end()) == 0 && 939 *std::max_element(CurrentTopDownReservedDependencyColoring.begin(), 940 CurrentTopDownReservedDependencyColoring.end()) == 0) 941 return; 942 943 for (unsigned SUNum : DAG->BottomUpIndex2SU) { 944 SUnit *SU = &DAG->SUnits[SUNum]; 945 std::set<unsigned> SUColors; 946 std::set<unsigned> SUColorsPending; 947 948 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize) 949 continue; 950 951 if (CurrentBottomUpReservedDependencyColoring[SU->NodeNum] > 0 || 952 CurrentTopDownReservedDependencyColoring[SU->NodeNum] > 0) 953 continue; 954 955 for (SDep& SuccDep : SU->Succs) { 956 SUnit *Succ = SuccDep.getSUnit(); 957 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize) 958 continue; 959 if (CurrentBottomUpReservedDependencyColoring[Succ->NodeNum] > 0 || 960 CurrentTopDownReservedDependencyColoring[Succ->NodeNum] > 0) 961 SUColors.insert(CurrentColoring[Succ->NodeNum]); 962 SUColorsPending.insert(PendingColoring[Succ->NodeNum]); 963 } 964 // If there is only one child/parent block, and that block 965 // is not among the ones we are removing in this path, then 966 // merge the instruction to that block 967 if (SUColors.size() == 1 && SUColorsPending.size() == 1) 968 PendingColoring[SU->NodeNum] = *SUColors.begin(); 969 else // TODO: Attribute new colors depending on color 970 // combination of children. 971 PendingColoring[SU->NodeNum] = NextNonReservedID++; 972 } 973 CurrentColoring = PendingColoring; 974 } 975 976 977 void SIScheduleBlockCreator::colorForceConsecutiveOrderInGroup() { 978 unsigned DAGSize = DAG->SUnits.size(); 979 unsigned PreviousColor; 980 std::set<unsigned> SeenColors; 981 982 if (DAGSize <= 1) 983 return; 984 985 PreviousColor = CurrentColoring[0]; 986 987 for (unsigned i = 1, e = DAGSize; i != e; ++i) { 988 SUnit *SU = &DAG->SUnits[i]; 989 unsigned CurrentColor = CurrentColoring[i]; 990 unsigned PreviousColorSave = PreviousColor; 991 assert(i == SU->NodeNum); 992 993 if (CurrentColor != PreviousColor) 994 SeenColors.insert(PreviousColor); 995 PreviousColor = CurrentColor; 996 997 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize) 998 continue; 999 1000 if (SeenColors.find(CurrentColor) == SeenColors.end()) 1001 continue; 1002 1003 if (PreviousColorSave != CurrentColor) 1004 CurrentColoring[i] = NextNonReservedID++; 1005 else 1006 CurrentColoring[i] = CurrentColoring[i-1]; 1007 } 1008 } 1009 1010 void SIScheduleBlockCreator::colorMergeConstantLoadsNextGroup() { 1011 unsigned DAGSize = DAG->SUnits.size(); 1012 1013 for (unsigned SUNum : DAG->BottomUpIndex2SU) { 1014 SUnit *SU = &DAG->SUnits[SUNum]; 1015 std::set<unsigned> SUColors; 1016 1017 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize) 1018 continue; 1019 1020 // No predecessor: Vgpr constant loading. 1021 // Low latency instructions usually have a predecessor (the address) 1022 if (SU->Preds.size() > 0 && !DAG->IsLowLatencySU[SU->NodeNum]) 1023 continue; 1024 1025 for (SDep& SuccDep : SU->Succs) { 1026 SUnit *Succ = SuccDep.getSUnit(); 1027 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize) 1028 continue; 1029 SUColors.insert(CurrentColoring[Succ->NodeNum]); 1030 } 1031 if (SUColors.size() == 1) 1032 CurrentColoring[SU->NodeNum] = *SUColors.begin(); 1033 } 1034 } 1035 1036 void SIScheduleBlockCreator::colorMergeIfPossibleNextGroup() { 1037 unsigned DAGSize = DAG->SUnits.size(); 1038 1039 for (unsigned SUNum : DAG->BottomUpIndex2SU) { 1040 SUnit *SU = &DAG->SUnits[SUNum]; 1041 std::set<unsigned> SUColors; 1042 1043 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize) 1044 continue; 1045 1046 for (SDep& SuccDep : SU->Succs) { 1047 SUnit *Succ = SuccDep.getSUnit(); 1048 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize) 1049 continue; 1050 SUColors.insert(CurrentColoring[Succ->NodeNum]); 1051 } 1052 if (SUColors.size() == 1) 1053 CurrentColoring[SU->NodeNum] = *SUColors.begin(); 1054 } 1055 } 1056 1057 void SIScheduleBlockCreator::colorMergeIfPossibleNextGroupOnlyForReserved() { 1058 unsigned DAGSize = DAG->SUnits.size(); 1059 1060 for (unsigned SUNum : DAG->BottomUpIndex2SU) { 1061 SUnit *SU = &DAG->SUnits[SUNum]; 1062 std::set<unsigned> SUColors; 1063 1064 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize) 1065 continue; 1066 1067 for (SDep& SuccDep : SU->Succs) { 1068 SUnit *Succ = SuccDep.getSUnit(); 1069 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize) 1070 continue; 1071 SUColors.insert(CurrentColoring[Succ->NodeNum]); 1072 } 1073 if (SUColors.size() == 1 && *SUColors.begin() <= DAGSize) 1074 CurrentColoring[SU->NodeNum] = *SUColors.begin(); 1075 } 1076 } 1077 1078 void SIScheduleBlockCreator::colorMergeIfPossibleSmallGroupsToNextGroup() { 1079 unsigned DAGSize = DAG->SUnits.size(); 1080 std::map<unsigned, unsigned> ColorCount; 1081 1082 for (unsigned SUNum : DAG->BottomUpIndex2SU) { 1083 SUnit *SU = &DAG->SUnits[SUNum]; 1084 unsigned color = CurrentColoring[SU->NodeNum]; 1085 ++ColorCount[color]; 1086 } 1087 1088 for (unsigned SUNum : DAG->BottomUpIndex2SU) { 1089 SUnit *SU = &DAG->SUnits[SUNum]; 1090 unsigned color = CurrentColoring[SU->NodeNum]; 1091 std::set<unsigned> SUColors; 1092 1093 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize) 1094 continue; 1095 1096 if (ColorCount[color] > 1) 1097 continue; 1098 1099 for (SDep& SuccDep : SU->Succs) { 1100 SUnit *Succ = SuccDep.getSUnit(); 1101 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize) 1102 continue; 1103 SUColors.insert(CurrentColoring[Succ->NodeNum]); 1104 } 1105 if (SUColors.size() == 1 && *SUColors.begin() != color) { 1106 --ColorCount[color]; 1107 CurrentColoring[SU->NodeNum] = *SUColors.begin(); 1108 ++ColorCount[*SUColors.begin()]; 1109 } 1110 } 1111 } 1112 1113 void SIScheduleBlockCreator::cutHugeBlocks() { 1114 // TODO 1115 } 1116 1117 void SIScheduleBlockCreator::regroupNoUserInstructions() { 1118 unsigned DAGSize = DAG->SUnits.size(); 1119 int GroupID = NextNonReservedID++; 1120 1121 for (unsigned SUNum : DAG->BottomUpIndex2SU) { 1122 SUnit *SU = &DAG->SUnits[SUNum]; 1123 bool hasSuccessor = false; 1124 1125 if (CurrentColoring[SU->NodeNum] <= (int)DAGSize) 1126 continue; 1127 1128 for (SDep& SuccDep : SU->Succs) { 1129 SUnit *Succ = SuccDep.getSUnit(); 1130 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize) 1131 continue; 1132 hasSuccessor = true; 1133 } 1134 if (!hasSuccessor) 1135 CurrentColoring[SU->NodeNum] = GroupID; 1136 } 1137 } 1138 1139 void SIScheduleBlockCreator::colorExports() { 1140 unsigned ExportColor = NextNonReservedID++; 1141 SmallVector<unsigned, 8> ExpGroup; 1142 1143 // Put all exports together in a block. 1144 // The block will naturally end up being scheduled last, 1145 // thus putting exports at the end of the schedule, which 1146 // is better for performance. 1147 // However we must ensure, for safety, the exports can be put 1148 // together in the same block without any other instruction. 1149 // This could happen, for example, when scheduling after regalloc 1150 // if reloading a spilled register from memory using the same 1151 // register than used in a previous export. 1152 // If that happens, do not regroup the exports. 1153 for (unsigned SUNum : DAG->TopDownIndex2SU) { 1154 const SUnit &SU = DAG->SUnits[SUNum]; 1155 if (SIInstrInfo::isEXP(*SU.getInstr())) { 1156 // Check the EXP can be added to the group safely, 1157 // ie without needing any other instruction. 1158 // The EXP is allowed to depend on other EXP 1159 // (they will be in the same group). 1160 for (unsigned j : ExpGroup) { 1161 bool HasSubGraph; 1162 std::vector<int> SubGraph; 1163 // By construction (topological order), if SU and 1164 // DAG->SUnits[j] are linked, DAG->SUnits[j] is neccessary 1165 // in the parent graph of SU. 1166 #ifndef NDEBUG 1167 SubGraph = DAG->GetTopo()->GetSubGraph(SU, DAG->SUnits[j], 1168 HasSubGraph); 1169 assert(!HasSubGraph); 1170 #endif 1171 SubGraph = DAG->GetTopo()->GetSubGraph(DAG->SUnits[j], SU, 1172 HasSubGraph); 1173 if (!HasSubGraph) 1174 continue; // No dependencies between each other 1175 1176 // SubGraph contains all the instructions required 1177 // between EXP SUnits[j] and EXP SU. 1178 for (unsigned k : SubGraph) { 1179 if (!SIInstrInfo::isEXP(*DAG->SUnits[k].getInstr())) 1180 // Other instructions than EXP would be required in the group. 1181 // Abort the groupping. 1182 return; 1183 } 1184 } 1185 1186 ExpGroup.push_back(SUNum); 1187 } 1188 } 1189 1190 // The group can be formed. Give the color. 1191 for (unsigned j : ExpGroup) 1192 CurrentColoring[j] = ExportColor; 1193 } 1194 1195 void SIScheduleBlockCreator::createBlocksForVariant(SISchedulerBlockCreatorVariant BlockVariant) { 1196 unsigned DAGSize = DAG->SUnits.size(); 1197 std::map<unsigned,unsigned> RealID; 1198 1199 CurrentBlocks.clear(); 1200 CurrentColoring.clear(); 1201 CurrentColoring.resize(DAGSize, 0); 1202 Node2CurrentBlock.clear(); 1203 1204 // Restore links previous scheduling variant has overridden. 1205 DAG->restoreSULinksLeft(); 1206 1207 NextReservedID = 1; 1208 NextNonReservedID = DAGSize + 1; 1209 1210 LLVM_DEBUG(dbgs() << "Coloring the graph\n"); 1211 1212 if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesGrouped) 1213 colorHighLatenciesGroups(); 1214 else 1215 colorHighLatenciesAlone(); 1216 colorComputeReservedDependencies(); 1217 colorAccordingToReservedDependencies(); 1218 colorEndsAccordingToDependencies(); 1219 if (BlockVariant == SISchedulerBlockCreatorVariant::LatenciesAlonePlusConsecutive) 1220 colorForceConsecutiveOrderInGroup(); 1221 regroupNoUserInstructions(); 1222 colorMergeConstantLoadsNextGroup(); 1223 colorMergeIfPossibleNextGroupOnlyForReserved(); 1224 colorExports(); 1225 1226 // Put SUs of same color into same block 1227 Node2CurrentBlock.resize(DAGSize, -1); 1228 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 1229 SUnit *SU = &DAG->SUnits[i]; 1230 unsigned Color = CurrentColoring[SU->NodeNum]; 1231 if (RealID.find(Color) == RealID.end()) { 1232 int ID = CurrentBlocks.size(); 1233 BlockPtrs.push_back(llvm::make_unique<SIScheduleBlock>(DAG, this, ID)); 1234 CurrentBlocks.push_back(BlockPtrs.rbegin()->get()); 1235 RealID[Color] = ID; 1236 } 1237 CurrentBlocks[RealID[Color]]->addUnit(SU); 1238 Node2CurrentBlock[SU->NodeNum] = RealID[Color]; 1239 } 1240 1241 // Build dependencies between blocks. 1242 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 1243 SUnit *SU = &DAG->SUnits[i]; 1244 int SUID = Node2CurrentBlock[i]; 1245 for (SDep& SuccDep : SU->Succs) { 1246 SUnit *Succ = SuccDep.getSUnit(); 1247 if (SuccDep.isWeak() || Succ->NodeNum >= DAGSize) 1248 continue; 1249 if (Node2CurrentBlock[Succ->NodeNum] != SUID) 1250 CurrentBlocks[SUID]->addSucc(CurrentBlocks[Node2CurrentBlock[Succ->NodeNum]], 1251 SuccDep.isCtrl() ? NoData : Data); 1252 } 1253 for (SDep& PredDep : SU->Preds) { 1254 SUnit *Pred = PredDep.getSUnit(); 1255 if (PredDep.isWeak() || Pred->NodeNum >= DAGSize) 1256 continue; 1257 if (Node2CurrentBlock[Pred->NodeNum] != SUID) 1258 CurrentBlocks[SUID]->addPred(CurrentBlocks[Node2CurrentBlock[Pred->NodeNum]]); 1259 } 1260 } 1261 1262 // Free root and leafs of all blocks to enable scheduling inside them. 1263 for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) { 1264 SIScheduleBlock *Block = CurrentBlocks[i]; 1265 Block->finalizeUnits(); 1266 } 1267 LLVM_DEBUG(dbgs() << "Blocks created:\n\n"; 1268 for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) { 1269 SIScheduleBlock *Block = CurrentBlocks[i]; 1270 Block->printDebug(true); 1271 }); 1272 } 1273 1274 // Two functions taken from Codegen/MachineScheduler.cpp 1275 1276 /// Non-const version. 1277 static MachineBasicBlock::iterator 1278 nextIfDebug(MachineBasicBlock::iterator I, 1279 MachineBasicBlock::const_iterator End) { 1280 for (; I != End; ++I) { 1281 if (!I->isDebugInstr()) 1282 break; 1283 } 1284 return I; 1285 } 1286 1287 void SIScheduleBlockCreator::topologicalSort() { 1288 unsigned DAGSize = CurrentBlocks.size(); 1289 std::vector<int> WorkList; 1290 1291 LLVM_DEBUG(dbgs() << "Topological Sort\n"); 1292 1293 WorkList.reserve(DAGSize); 1294 TopDownIndex2Block.resize(DAGSize); 1295 TopDownBlock2Index.resize(DAGSize); 1296 BottomUpIndex2Block.resize(DAGSize); 1297 1298 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 1299 SIScheduleBlock *Block = CurrentBlocks[i]; 1300 unsigned Degree = Block->getSuccs().size(); 1301 TopDownBlock2Index[i] = Degree; 1302 if (Degree == 0) { 1303 WorkList.push_back(i); 1304 } 1305 } 1306 1307 int Id = DAGSize; 1308 while (!WorkList.empty()) { 1309 int i = WorkList.back(); 1310 SIScheduleBlock *Block = CurrentBlocks[i]; 1311 WorkList.pop_back(); 1312 TopDownBlock2Index[i] = --Id; 1313 TopDownIndex2Block[Id] = i; 1314 for (SIScheduleBlock* Pred : Block->getPreds()) { 1315 if (!--TopDownBlock2Index[Pred->getID()]) 1316 WorkList.push_back(Pred->getID()); 1317 } 1318 } 1319 1320 #ifndef NDEBUG 1321 // Check correctness of the ordering. 1322 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 1323 SIScheduleBlock *Block = CurrentBlocks[i]; 1324 for (SIScheduleBlock* Pred : Block->getPreds()) { 1325 assert(TopDownBlock2Index[i] > TopDownBlock2Index[Pred->getID()] && 1326 "Wrong Top Down topological sorting"); 1327 } 1328 } 1329 #endif 1330 1331 BottomUpIndex2Block = std::vector<int>(TopDownIndex2Block.rbegin(), 1332 TopDownIndex2Block.rend()); 1333 } 1334 1335 void SIScheduleBlockCreator::scheduleInsideBlocks() { 1336 unsigned DAGSize = CurrentBlocks.size(); 1337 1338 LLVM_DEBUG(dbgs() << "\nScheduling Blocks\n\n"); 1339 1340 // We do schedule a valid scheduling such that a Block corresponds 1341 // to a range of instructions. 1342 LLVM_DEBUG(dbgs() << "First phase: Fast scheduling for Reg Liveness\n"); 1343 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 1344 SIScheduleBlock *Block = CurrentBlocks[i]; 1345 Block->fastSchedule(); 1346 } 1347 1348 // Note: the following code, and the part restoring previous position 1349 // is by far the most expensive operation of the Scheduler. 1350 1351 // Do not update CurrentTop. 1352 MachineBasicBlock::iterator CurrentTopFastSched = DAG->getCurrentTop(); 1353 std::vector<MachineBasicBlock::iterator> PosOld; 1354 std::vector<MachineBasicBlock::iterator> PosNew; 1355 PosOld.reserve(DAG->SUnits.size()); 1356 PosNew.reserve(DAG->SUnits.size()); 1357 1358 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 1359 int BlockIndice = TopDownIndex2Block[i]; 1360 SIScheduleBlock *Block = CurrentBlocks[BlockIndice]; 1361 std::vector<SUnit*> SUs = Block->getScheduledUnits(); 1362 1363 for (SUnit* SU : SUs) { 1364 MachineInstr *MI = SU->getInstr(); 1365 MachineBasicBlock::iterator Pos = MI; 1366 PosOld.push_back(Pos); 1367 if (&*CurrentTopFastSched == MI) { 1368 PosNew.push_back(Pos); 1369 CurrentTopFastSched = nextIfDebug(++CurrentTopFastSched, 1370 DAG->getCurrentBottom()); 1371 } else { 1372 // Update the instruction stream. 1373 DAG->getBB()->splice(CurrentTopFastSched, DAG->getBB(), MI); 1374 1375 // Update LiveIntervals. 1376 // Note: Moving all instructions and calling handleMove every time 1377 // is the most cpu intensive operation of the scheduler. 1378 // It would gain a lot if there was a way to recompute the 1379 // LiveIntervals for the entire scheduling region. 1380 DAG->getLIS()->handleMove(*MI, /*UpdateFlags=*/true); 1381 PosNew.push_back(CurrentTopFastSched); 1382 } 1383 } 1384 } 1385 1386 // Now we have Block of SUs == Block of MI. 1387 // We do the final schedule for the instructions inside the block. 1388 // The property that all the SUs of the Block are grouped together as MI 1389 // is used for correct reg usage tracking. 1390 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 1391 SIScheduleBlock *Block = CurrentBlocks[i]; 1392 std::vector<SUnit*> SUs = Block->getScheduledUnits(); 1393 Block->schedule((*SUs.begin())->getInstr(), (*SUs.rbegin())->getInstr()); 1394 } 1395 1396 LLVM_DEBUG(dbgs() << "Restoring MI Pos\n"); 1397 // Restore old ordering (which prevents a LIS->handleMove bug). 1398 for (unsigned i = PosOld.size(), e = 0; i != e; --i) { 1399 MachineBasicBlock::iterator POld = PosOld[i-1]; 1400 MachineBasicBlock::iterator PNew = PosNew[i-1]; 1401 if (PNew != POld) { 1402 // Update the instruction stream. 1403 DAG->getBB()->splice(POld, DAG->getBB(), PNew); 1404 1405 // Update LiveIntervals. 1406 DAG->getLIS()->handleMove(*POld, /*UpdateFlags=*/true); 1407 } 1408 } 1409 1410 LLVM_DEBUG(for (unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) { 1411 SIScheduleBlock *Block = CurrentBlocks[i]; 1412 Block->printDebug(true); 1413 }); 1414 } 1415 1416 void SIScheduleBlockCreator::fillStats() { 1417 unsigned DAGSize = CurrentBlocks.size(); 1418 1419 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 1420 int BlockIndice = TopDownIndex2Block[i]; 1421 SIScheduleBlock *Block = CurrentBlocks[BlockIndice]; 1422 if (Block->getPreds().empty()) 1423 Block->Depth = 0; 1424 else { 1425 unsigned Depth = 0; 1426 for (SIScheduleBlock *Pred : Block->getPreds()) { 1427 if (Depth < Pred->Depth + Pred->getCost()) 1428 Depth = Pred->Depth + Pred->getCost(); 1429 } 1430 Block->Depth = Depth; 1431 } 1432 } 1433 1434 for (unsigned i = 0, e = DAGSize; i != e; ++i) { 1435 int BlockIndice = BottomUpIndex2Block[i]; 1436 SIScheduleBlock *Block = CurrentBlocks[BlockIndice]; 1437 if (Block->getSuccs().empty()) 1438 Block->Height = 0; 1439 else { 1440 unsigned Height = 0; 1441 for (const auto &Succ : Block->getSuccs()) 1442 Height = std::max(Height, Succ.first->Height + Succ.first->getCost()); 1443 Block->Height = Height; 1444 } 1445 } 1446 } 1447 1448 // SIScheduleBlockScheduler // 1449 1450 SIScheduleBlockScheduler::SIScheduleBlockScheduler(SIScheduleDAGMI *DAG, 1451 SISchedulerBlockSchedulerVariant Variant, 1452 SIScheduleBlocks BlocksStruct) : 1453 DAG(DAG), Variant(Variant), Blocks(BlocksStruct.Blocks), 1454 LastPosWaitedHighLatency(0), NumBlockScheduled(0), VregCurrentUsage(0), 1455 SregCurrentUsage(0), maxVregUsage(0), maxSregUsage(0) { 1456 1457 // Fill the usage of every output 1458 // Warning: while by construction we always have a link between two blocks 1459 // when one needs a result from the other, the number of users of an output 1460 // is not the sum of child blocks having as input the same virtual register. 1461 // Here is an example. A produces x and y. B eats x and produces x'. 1462 // C eats x' and y. The register coalescer may have attributed the same 1463 // virtual register to x and x'. 1464 // To count accurately, we do a topological sort. In case the register is 1465 // found for several parents, we increment the usage of the one with the 1466 // highest topological index. 1467 LiveOutRegsNumUsages.resize(Blocks.size()); 1468 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) { 1469 SIScheduleBlock *Block = Blocks[i]; 1470 for (unsigned Reg : Block->getInRegs()) { 1471 bool Found = false; 1472 int topoInd = -1; 1473 for (SIScheduleBlock* Pred: Block->getPreds()) { 1474 std::set<unsigned> PredOutRegs = Pred->getOutRegs(); 1475 std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg); 1476 1477 if (RegPos != PredOutRegs.end()) { 1478 Found = true; 1479 if (topoInd < BlocksStruct.TopDownBlock2Index[Pred->getID()]) { 1480 topoInd = BlocksStruct.TopDownBlock2Index[Pred->getID()]; 1481 } 1482 } 1483 } 1484 1485 if (!Found) 1486 continue; 1487 1488 int PredID = BlocksStruct.TopDownIndex2Block[topoInd]; 1489 ++LiveOutRegsNumUsages[PredID][Reg]; 1490 } 1491 } 1492 1493 LastPosHighLatencyParentScheduled.resize(Blocks.size(), 0); 1494 BlockNumPredsLeft.resize(Blocks.size()); 1495 BlockNumSuccsLeft.resize(Blocks.size()); 1496 1497 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) { 1498 SIScheduleBlock *Block = Blocks[i]; 1499 BlockNumPredsLeft[i] = Block->getPreds().size(); 1500 BlockNumSuccsLeft[i] = Block->getSuccs().size(); 1501 } 1502 1503 #ifndef NDEBUG 1504 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) { 1505 SIScheduleBlock *Block = Blocks[i]; 1506 assert(Block->getID() == i); 1507 } 1508 #endif 1509 1510 std::set<unsigned> InRegs = DAG->getInRegs(); 1511 addLiveRegs(InRegs); 1512 1513 // Increase LiveOutRegsNumUsages for blocks 1514 // producing registers consumed in another 1515 // scheduling region. 1516 for (unsigned Reg : DAG->getOutRegs()) { 1517 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) { 1518 // Do reverse traversal 1519 int ID = BlocksStruct.TopDownIndex2Block[Blocks.size()-1-i]; 1520 SIScheduleBlock *Block = Blocks[ID]; 1521 const std::set<unsigned> &OutRegs = Block->getOutRegs(); 1522 1523 if (OutRegs.find(Reg) == OutRegs.end()) 1524 continue; 1525 1526 ++LiveOutRegsNumUsages[ID][Reg]; 1527 break; 1528 } 1529 } 1530 1531 // Fill LiveRegsConsumers for regs that were already 1532 // defined before scheduling. 1533 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) { 1534 SIScheduleBlock *Block = Blocks[i]; 1535 for (unsigned Reg : Block->getInRegs()) { 1536 bool Found = false; 1537 for (SIScheduleBlock* Pred: Block->getPreds()) { 1538 std::set<unsigned> PredOutRegs = Pred->getOutRegs(); 1539 std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg); 1540 1541 if (RegPos != PredOutRegs.end()) { 1542 Found = true; 1543 break; 1544 } 1545 } 1546 1547 if (!Found) 1548 ++LiveRegsConsumers[Reg]; 1549 } 1550 } 1551 1552 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) { 1553 SIScheduleBlock *Block = Blocks[i]; 1554 if (BlockNumPredsLeft[i] == 0) { 1555 ReadyBlocks.push_back(Block); 1556 } 1557 } 1558 1559 while (SIScheduleBlock *Block = pickBlock()) { 1560 BlocksScheduled.push_back(Block); 1561 blockScheduled(Block); 1562 } 1563 1564 LLVM_DEBUG(dbgs() << "Block Order:"; for (SIScheduleBlock *Block 1565 : BlocksScheduled) { 1566 dbgs() << ' ' << Block->getID(); 1567 } dbgs() << '\n';); 1568 } 1569 1570 bool SIScheduleBlockScheduler::tryCandidateLatency(SIBlockSchedCandidate &Cand, 1571 SIBlockSchedCandidate &TryCand) { 1572 if (!Cand.isValid()) { 1573 TryCand.Reason = NodeOrder; 1574 return true; 1575 } 1576 1577 // Try to hide high latencies. 1578 if (SISched::tryLess(TryCand.LastPosHighLatParentScheduled, 1579 Cand.LastPosHighLatParentScheduled, TryCand, Cand, Latency)) 1580 return true; 1581 // Schedule high latencies early so you can hide them better. 1582 if (SISched::tryGreater(TryCand.IsHighLatency, Cand.IsHighLatency, 1583 TryCand, Cand, Latency)) 1584 return true; 1585 if (TryCand.IsHighLatency && SISched::tryGreater(TryCand.Height, Cand.Height, 1586 TryCand, Cand, Depth)) 1587 return true; 1588 if (SISched::tryGreater(TryCand.NumHighLatencySuccessors, 1589 Cand.NumHighLatencySuccessors, 1590 TryCand, Cand, Successor)) 1591 return true; 1592 return false; 1593 } 1594 1595 bool SIScheduleBlockScheduler::tryCandidateRegUsage(SIBlockSchedCandidate &Cand, 1596 SIBlockSchedCandidate &TryCand) { 1597 if (!Cand.isValid()) { 1598 TryCand.Reason = NodeOrder; 1599 return true; 1600 } 1601 1602 if (SISched::tryLess(TryCand.VGPRUsageDiff > 0, Cand.VGPRUsageDiff > 0, 1603 TryCand, Cand, RegUsage)) 1604 return true; 1605 if (SISched::tryGreater(TryCand.NumSuccessors > 0, 1606 Cand.NumSuccessors > 0, 1607 TryCand, Cand, Successor)) 1608 return true; 1609 if (SISched::tryGreater(TryCand.Height, Cand.Height, TryCand, Cand, Depth)) 1610 return true; 1611 if (SISched::tryLess(TryCand.VGPRUsageDiff, Cand.VGPRUsageDiff, 1612 TryCand, Cand, RegUsage)) 1613 return true; 1614 return false; 1615 } 1616 1617 SIScheduleBlock *SIScheduleBlockScheduler::pickBlock() { 1618 SIBlockSchedCandidate Cand; 1619 std::vector<SIScheduleBlock*>::iterator Best; 1620 SIScheduleBlock *Block; 1621 if (ReadyBlocks.empty()) 1622 return nullptr; 1623 1624 DAG->fillVgprSgprCost(LiveRegs.begin(), LiveRegs.end(), 1625 VregCurrentUsage, SregCurrentUsage); 1626 if (VregCurrentUsage > maxVregUsage) 1627 maxVregUsage = VregCurrentUsage; 1628 if (SregCurrentUsage > maxSregUsage) 1629 maxSregUsage = SregCurrentUsage; 1630 LLVM_DEBUG(dbgs() << "Picking New Blocks\n"; dbgs() << "Available: "; 1631 for (SIScheduleBlock *Block 1632 : ReadyBlocks) dbgs() 1633 << Block->getID() << ' '; 1634 dbgs() << "\nCurrent Live:\n"; 1635 for (unsigned Reg 1636 : LiveRegs) dbgs() 1637 << printVRegOrUnit(Reg, DAG->getTRI()) << ' '; 1638 dbgs() << '\n'; 1639 dbgs() << "Current VGPRs: " << VregCurrentUsage << '\n'; 1640 dbgs() << "Current SGPRs: " << SregCurrentUsage << '\n';); 1641 1642 Cand.Block = nullptr; 1643 for (std::vector<SIScheduleBlock*>::iterator I = ReadyBlocks.begin(), 1644 E = ReadyBlocks.end(); I != E; ++I) { 1645 SIBlockSchedCandidate TryCand; 1646 TryCand.Block = *I; 1647 TryCand.IsHighLatency = TryCand.Block->isHighLatencyBlock(); 1648 TryCand.VGPRUsageDiff = 1649 checkRegUsageImpact(TryCand.Block->getInRegs(), 1650 TryCand.Block->getOutRegs())[DAG->getVGPRSetID()]; 1651 TryCand.NumSuccessors = TryCand.Block->getSuccs().size(); 1652 TryCand.NumHighLatencySuccessors = 1653 TryCand.Block->getNumHighLatencySuccessors(); 1654 TryCand.LastPosHighLatParentScheduled = 1655 (unsigned int) std::max<int> (0, 1656 LastPosHighLatencyParentScheduled[TryCand.Block->getID()] - 1657 LastPosWaitedHighLatency); 1658 TryCand.Height = TryCand.Block->Height; 1659 // Try not to increase VGPR usage too much, else we may spill. 1660 if (VregCurrentUsage > 120 || 1661 Variant != SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage) { 1662 if (!tryCandidateRegUsage(Cand, TryCand) && 1663 Variant != SISchedulerBlockSchedulerVariant::BlockRegUsage) 1664 tryCandidateLatency(Cand, TryCand); 1665 } else { 1666 if (!tryCandidateLatency(Cand, TryCand)) 1667 tryCandidateRegUsage(Cand, TryCand); 1668 } 1669 if (TryCand.Reason != NoCand) { 1670 Cand.setBest(TryCand); 1671 Best = I; 1672 LLVM_DEBUG(dbgs() << "Best Current Choice: " << Cand.Block->getID() << ' ' 1673 << getReasonStr(Cand.Reason) << '\n'); 1674 } 1675 } 1676 1677 LLVM_DEBUG(dbgs() << "Picking: " << Cand.Block->getID() << '\n'; 1678 dbgs() << "Is a block with high latency instruction: " 1679 << (Cand.IsHighLatency ? "yes\n" : "no\n"); 1680 dbgs() << "Position of last high latency dependency: " 1681 << Cand.LastPosHighLatParentScheduled << '\n'; 1682 dbgs() << "VGPRUsageDiff: " << Cand.VGPRUsageDiff << '\n'; 1683 dbgs() << '\n';); 1684 1685 Block = Cand.Block; 1686 ReadyBlocks.erase(Best); 1687 return Block; 1688 } 1689 1690 // Tracking of currently alive registers to determine VGPR Usage. 1691 1692 void SIScheduleBlockScheduler::addLiveRegs(std::set<unsigned> &Regs) { 1693 for (unsigned Reg : Regs) { 1694 // For now only track virtual registers. 1695 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 1696 continue; 1697 // If not already in the live set, then add it. 1698 (void) LiveRegs.insert(Reg); 1699 } 1700 } 1701 1702 void SIScheduleBlockScheduler::decreaseLiveRegs(SIScheduleBlock *Block, 1703 std::set<unsigned> &Regs) { 1704 for (unsigned Reg : Regs) { 1705 // For now only track virtual registers. 1706 std::set<unsigned>::iterator Pos = LiveRegs.find(Reg); 1707 assert (Pos != LiveRegs.end() && // Reg must be live. 1708 LiveRegsConsumers.find(Reg) != LiveRegsConsumers.end() && 1709 LiveRegsConsumers[Reg] >= 1); 1710 --LiveRegsConsumers[Reg]; 1711 if (LiveRegsConsumers[Reg] == 0) 1712 LiveRegs.erase(Pos); 1713 } 1714 } 1715 1716 void SIScheduleBlockScheduler::releaseBlockSuccs(SIScheduleBlock *Parent) { 1717 for (const auto &Block : Parent->getSuccs()) { 1718 if (--BlockNumPredsLeft[Block.first->getID()] == 0) 1719 ReadyBlocks.push_back(Block.first); 1720 1721 if (Parent->isHighLatencyBlock() && 1722 Block.second == SIScheduleBlockLinkKind::Data) 1723 LastPosHighLatencyParentScheduled[Block.first->getID()] = NumBlockScheduled; 1724 } 1725 } 1726 1727 void SIScheduleBlockScheduler::blockScheduled(SIScheduleBlock *Block) { 1728 decreaseLiveRegs(Block, Block->getInRegs()); 1729 addLiveRegs(Block->getOutRegs()); 1730 releaseBlockSuccs(Block); 1731 for (std::map<unsigned, unsigned>::iterator RegI = 1732 LiveOutRegsNumUsages[Block->getID()].begin(), 1733 E = LiveOutRegsNumUsages[Block->getID()].end(); RegI != E; ++RegI) { 1734 std::pair<unsigned, unsigned> RegP = *RegI; 1735 // We produce this register, thus it must not be previously alive. 1736 assert(LiveRegsConsumers.find(RegP.first) == LiveRegsConsumers.end() || 1737 LiveRegsConsumers[RegP.first] == 0); 1738 LiveRegsConsumers[RegP.first] += RegP.second; 1739 } 1740 if (LastPosHighLatencyParentScheduled[Block->getID()] > 1741 (unsigned)LastPosWaitedHighLatency) 1742 LastPosWaitedHighLatency = 1743 LastPosHighLatencyParentScheduled[Block->getID()]; 1744 ++NumBlockScheduled; 1745 } 1746 1747 std::vector<int> 1748 SIScheduleBlockScheduler::checkRegUsageImpact(std::set<unsigned> &InRegs, 1749 std::set<unsigned> &OutRegs) { 1750 std::vector<int> DiffSetPressure; 1751 DiffSetPressure.assign(DAG->getTRI()->getNumRegPressureSets(), 0); 1752 1753 for (unsigned Reg : InRegs) { 1754 // For now only track virtual registers. 1755 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 1756 continue; 1757 if (LiveRegsConsumers[Reg] > 1) 1758 continue; 1759 PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg); 1760 for (; PSetI.isValid(); ++PSetI) { 1761 DiffSetPressure[*PSetI] -= PSetI.getWeight(); 1762 } 1763 } 1764 1765 for (unsigned Reg : OutRegs) { 1766 // For now only track virtual registers. 1767 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 1768 continue; 1769 PSetIterator PSetI = DAG->getMRI()->getPressureSets(Reg); 1770 for (; PSetI.isValid(); ++PSetI) { 1771 DiffSetPressure[*PSetI] += PSetI.getWeight(); 1772 } 1773 } 1774 1775 return DiffSetPressure; 1776 } 1777 1778 // SIScheduler // 1779 1780 struct SIScheduleBlockResult 1781 SIScheduler::scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant, 1782 SISchedulerBlockSchedulerVariant ScheduleVariant) { 1783 SIScheduleBlocks Blocks = BlockCreator.getBlocks(BlockVariant); 1784 SIScheduleBlockScheduler Scheduler(DAG, ScheduleVariant, Blocks); 1785 std::vector<SIScheduleBlock*> ScheduledBlocks; 1786 struct SIScheduleBlockResult Res; 1787 1788 ScheduledBlocks = Scheduler.getBlocks(); 1789 1790 for (unsigned b = 0; b < ScheduledBlocks.size(); ++b) { 1791 SIScheduleBlock *Block = ScheduledBlocks[b]; 1792 std::vector<SUnit*> SUs = Block->getScheduledUnits(); 1793 1794 for (SUnit* SU : SUs) 1795 Res.SUs.push_back(SU->NodeNum); 1796 } 1797 1798 Res.MaxSGPRUsage = Scheduler.getSGPRUsage(); 1799 Res.MaxVGPRUsage = Scheduler.getVGPRUsage(); 1800 return Res; 1801 } 1802 1803 // SIScheduleDAGMI // 1804 1805 SIScheduleDAGMI::SIScheduleDAGMI(MachineSchedContext *C) : 1806 ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C)) { 1807 SITII = static_cast<const SIInstrInfo*>(TII); 1808 SITRI = static_cast<const SIRegisterInfo*>(TRI); 1809 1810 VGPRSetID = SITRI->getVGPRPressureSet(); 1811 SGPRSetID = SITRI->getSGPRPressureSet(); 1812 } 1813 1814 SIScheduleDAGMI::~SIScheduleDAGMI() = default; 1815 1816 // Code adapted from scheduleDAG.cpp 1817 // Does a topological sort over the SUs. 1818 // Both TopDown and BottomUp 1819 void SIScheduleDAGMI::topologicalSort() { 1820 Topo.InitDAGTopologicalSorting(); 1821 1822 TopDownIndex2SU = std::vector<int>(Topo.begin(), Topo.end()); 1823 BottomUpIndex2SU = std::vector<int>(Topo.rbegin(), Topo.rend()); 1824 } 1825 1826 // Move low latencies further from their user without 1827 // increasing SGPR usage (in general) 1828 // This is to be replaced by a better pass that would 1829 // take into account SGPR usage (based on VGPR Usage 1830 // and the corresponding wavefront count), that would 1831 // try to merge groups of loads if it make sense, etc 1832 void SIScheduleDAGMI::moveLowLatencies() { 1833 unsigned DAGSize = SUnits.size(); 1834 int LastLowLatencyUser = -1; 1835 int LastLowLatencyPos = -1; 1836 1837 for (unsigned i = 0, e = ScheduledSUnits.size(); i != e; ++i) { 1838 SUnit *SU = &SUnits[ScheduledSUnits[i]]; 1839 bool IsLowLatencyUser = false; 1840 unsigned MinPos = 0; 1841 1842 for (SDep& PredDep : SU->Preds) { 1843 SUnit *Pred = PredDep.getSUnit(); 1844 if (SITII->isLowLatencyInstruction(*Pred->getInstr())) { 1845 IsLowLatencyUser = true; 1846 } 1847 if (Pred->NodeNum >= DAGSize) 1848 continue; 1849 unsigned PredPos = ScheduledSUnitsInv[Pred->NodeNum]; 1850 if (PredPos >= MinPos) 1851 MinPos = PredPos + 1; 1852 } 1853 1854 if (SITII->isLowLatencyInstruction(*SU->getInstr())) { 1855 unsigned BestPos = LastLowLatencyUser + 1; 1856 if ((int)BestPos <= LastLowLatencyPos) 1857 BestPos = LastLowLatencyPos + 1; 1858 if (BestPos < MinPos) 1859 BestPos = MinPos; 1860 if (BestPos < i) { 1861 for (unsigned u = i; u > BestPos; --u) { 1862 ++ScheduledSUnitsInv[ScheduledSUnits[u-1]]; 1863 ScheduledSUnits[u] = ScheduledSUnits[u-1]; 1864 } 1865 ScheduledSUnits[BestPos] = SU->NodeNum; 1866 ScheduledSUnitsInv[SU->NodeNum] = BestPos; 1867 } 1868 LastLowLatencyPos = BestPos; 1869 if (IsLowLatencyUser) 1870 LastLowLatencyUser = BestPos; 1871 } else if (IsLowLatencyUser) { 1872 LastLowLatencyUser = i; 1873 // Moves COPY instructions on which depends 1874 // the low latency instructions too. 1875 } else if (SU->getInstr()->getOpcode() == AMDGPU::COPY) { 1876 bool CopyForLowLat = false; 1877 for (SDep& SuccDep : SU->Succs) { 1878 SUnit *Succ = SuccDep.getSUnit(); 1879 if (SITII->isLowLatencyInstruction(*Succ->getInstr())) { 1880 CopyForLowLat = true; 1881 } 1882 } 1883 if (!CopyForLowLat) 1884 continue; 1885 if (MinPos < i) { 1886 for (unsigned u = i; u > MinPos; --u) { 1887 ++ScheduledSUnitsInv[ScheduledSUnits[u-1]]; 1888 ScheduledSUnits[u] = ScheduledSUnits[u-1]; 1889 } 1890 ScheduledSUnits[MinPos] = SU->NodeNum; 1891 ScheduledSUnitsInv[SU->NodeNum] = MinPos; 1892 } 1893 } 1894 } 1895 } 1896 1897 void SIScheduleDAGMI::restoreSULinksLeft() { 1898 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { 1899 SUnits[i].isScheduled = false; 1900 SUnits[i].WeakPredsLeft = SUnitsLinksBackup[i].WeakPredsLeft; 1901 SUnits[i].NumPredsLeft = SUnitsLinksBackup[i].NumPredsLeft; 1902 SUnits[i].WeakSuccsLeft = SUnitsLinksBackup[i].WeakSuccsLeft; 1903 SUnits[i].NumSuccsLeft = SUnitsLinksBackup[i].NumSuccsLeft; 1904 } 1905 } 1906 1907 // Return the Vgpr and Sgpr usage corresponding to some virtual registers. 1908 template<typename _Iterator> void 1909 SIScheduleDAGMI::fillVgprSgprCost(_Iterator First, _Iterator End, 1910 unsigned &VgprUsage, unsigned &SgprUsage) { 1911 VgprUsage = 0; 1912 SgprUsage = 0; 1913 for (_Iterator RegI = First; RegI != End; ++RegI) { 1914 unsigned Reg = *RegI; 1915 // For now only track virtual registers 1916 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 1917 continue; 1918 PSetIterator PSetI = MRI.getPressureSets(Reg); 1919 for (; PSetI.isValid(); ++PSetI) { 1920 if (*PSetI == VGPRSetID) 1921 VgprUsage += PSetI.getWeight(); 1922 else if (*PSetI == SGPRSetID) 1923 SgprUsage += PSetI.getWeight(); 1924 } 1925 } 1926 } 1927 1928 void SIScheduleDAGMI::schedule() 1929 { 1930 SmallVector<SUnit*, 8> TopRoots, BotRoots; 1931 SIScheduleBlockResult Best, Temp; 1932 LLVM_DEBUG(dbgs() << "Preparing Scheduling\n"); 1933 1934 buildDAGWithRegPressure(); 1935 LLVM_DEBUG(for (SUnit &SU : SUnits) SU.dumpAll(this)); 1936 1937 topologicalSort(); 1938 findRootsAndBiasEdges(TopRoots, BotRoots); 1939 // We reuse several ScheduleDAGMI and ScheduleDAGMILive 1940 // functions, but to make them happy we must initialize 1941 // the default Scheduler implementation (even if we do not 1942 // run it) 1943 SchedImpl->initialize(this); 1944 initQueues(TopRoots, BotRoots); 1945 1946 // Fill some stats to help scheduling. 1947 1948 SUnitsLinksBackup = SUnits; 1949 IsLowLatencySU.clear(); 1950 LowLatencyOffset.clear(); 1951 IsHighLatencySU.clear(); 1952 1953 IsLowLatencySU.resize(SUnits.size(), 0); 1954 LowLatencyOffset.resize(SUnits.size(), 0); 1955 IsHighLatencySU.resize(SUnits.size(), 0); 1956 1957 for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) { 1958 SUnit *SU = &SUnits[i]; 1959 unsigned BaseLatReg; 1960 int64_t OffLatReg; 1961 if (SITII->isLowLatencyInstruction(*SU->getInstr())) { 1962 IsLowLatencySU[i] = 1; 1963 if (SITII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseLatReg, OffLatReg, 1964 TRI)) 1965 LowLatencyOffset[i] = OffLatReg; 1966 } else if (SITII->isHighLatencyInstruction(*SU->getInstr())) 1967 IsHighLatencySU[i] = 1; 1968 } 1969 1970 SIScheduler Scheduler(this); 1971 Best = Scheduler.scheduleVariant(SISchedulerBlockCreatorVariant::LatenciesAlone, 1972 SISchedulerBlockSchedulerVariant::BlockLatencyRegUsage); 1973 1974 // if VGPR usage is extremely high, try other good performing variants 1975 // which could lead to lower VGPR usage 1976 if (Best.MaxVGPRUsage > 180) { 1977 static const std::pair<SISchedulerBlockCreatorVariant, 1978 SISchedulerBlockSchedulerVariant> 1979 Variants[] = { 1980 { LatenciesAlone, BlockRegUsageLatency }, 1981 // { LatenciesAlone, BlockRegUsage }, 1982 { LatenciesGrouped, BlockLatencyRegUsage }, 1983 // { LatenciesGrouped, BlockRegUsageLatency }, 1984 // { LatenciesGrouped, BlockRegUsage }, 1985 { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage }, 1986 // { LatenciesAlonePlusConsecutive, BlockRegUsageLatency }, 1987 // { LatenciesAlonePlusConsecutive, BlockRegUsage } 1988 }; 1989 for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) { 1990 Temp = Scheduler.scheduleVariant(v.first, v.second); 1991 if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage) 1992 Best = Temp; 1993 } 1994 } 1995 // if VGPR usage is still extremely high, we may spill. Try other variants 1996 // which are less performing, but that could lead to lower VGPR usage. 1997 if (Best.MaxVGPRUsage > 200) { 1998 static const std::pair<SISchedulerBlockCreatorVariant, 1999 SISchedulerBlockSchedulerVariant> 2000 Variants[] = { 2001 // { LatenciesAlone, BlockRegUsageLatency }, 2002 { LatenciesAlone, BlockRegUsage }, 2003 // { LatenciesGrouped, BlockLatencyRegUsage }, 2004 { LatenciesGrouped, BlockRegUsageLatency }, 2005 { LatenciesGrouped, BlockRegUsage }, 2006 // { LatenciesAlonePlusConsecutive, BlockLatencyRegUsage }, 2007 { LatenciesAlonePlusConsecutive, BlockRegUsageLatency }, 2008 { LatenciesAlonePlusConsecutive, BlockRegUsage } 2009 }; 2010 for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) { 2011 Temp = Scheduler.scheduleVariant(v.first, v.second); 2012 if (Temp.MaxVGPRUsage < Best.MaxVGPRUsage) 2013 Best = Temp; 2014 } 2015 } 2016 2017 ScheduledSUnits = Best.SUs; 2018 ScheduledSUnitsInv.resize(SUnits.size()); 2019 2020 for (unsigned i = 0, e = (unsigned)SUnits.size(); i != e; ++i) { 2021 ScheduledSUnitsInv[ScheduledSUnits[i]] = i; 2022 } 2023 2024 moveLowLatencies(); 2025 2026 // Tell the outside world about the result of the scheduling. 2027 2028 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker"); 2029 TopRPTracker.setPos(CurrentTop); 2030 2031 for (std::vector<unsigned>::iterator I = ScheduledSUnits.begin(), 2032 E = ScheduledSUnits.end(); I != E; ++I) { 2033 SUnit *SU = &SUnits[*I]; 2034 2035 scheduleMI(SU, true); 2036 2037 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " 2038 << *SU->getInstr()); 2039 } 2040 2041 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone."); 2042 2043 placeDebugValues(); 2044 2045 LLVM_DEBUG({ 2046 dbgs() << "*** Final schedule for " 2047 << printMBBReference(*begin()->getParent()) << " ***\n"; 2048 dumpSchedule(); 2049 dbgs() << '\n'; 2050 }); 2051 } 2052