1 //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===// 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 // MachineScheduler schedules machine instructions after phi elimination. It 10 // preserves LiveIntervals so it can be invoked before register allocation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/MachineScheduler.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/BitVector.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/PriorityQueue.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/ADT/iterator_range.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/LiveInterval.h" 25 #include "llvm/CodeGen/LiveIntervals.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineDominators.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineFunctionPass.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineLoopInfo.h" 32 #include "llvm/CodeGen/MachineOperand.h" 33 #include "llvm/CodeGen/MachinePassRegistry.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/Passes.h" 36 #include "llvm/CodeGen/RegisterClassInfo.h" 37 #include "llvm/CodeGen/RegisterPressure.h" 38 #include "llvm/CodeGen/ScheduleDAG.h" 39 #include "llvm/CodeGen/ScheduleDAGInstrs.h" 40 #include "llvm/CodeGen/ScheduleDAGMutation.h" 41 #include "llvm/CodeGen/ScheduleDFS.h" 42 #include "llvm/CodeGen/ScheduleHazardRecognizer.h" 43 #include "llvm/CodeGen/SlotIndexes.h" 44 #include "llvm/CodeGen/TargetFrameLowering.h" 45 #include "llvm/CodeGen/TargetInstrInfo.h" 46 #include "llvm/CodeGen/TargetLowering.h" 47 #include "llvm/CodeGen/TargetPassConfig.h" 48 #include "llvm/CodeGen/TargetRegisterInfo.h" 49 #include "llvm/CodeGen/TargetSchedule.h" 50 #include "llvm/CodeGen/TargetSubtargetInfo.h" 51 #include "llvm/Config/llvm-config.h" 52 #include "llvm/InitializePasses.h" 53 #include "llvm/MC/LaneBitmask.h" 54 #include "llvm/Pass.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Compiler.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/ErrorHandling.h" 59 #include "llvm/Support/GraphWriter.h" 60 #include "llvm/Support/MachineValueType.h" 61 #include "llvm/Support/raw_ostream.h" 62 #include <algorithm> 63 #include <cassert> 64 #include <cstdint> 65 #include <iterator> 66 #include <limits> 67 #include <memory> 68 #include <string> 69 #include <tuple> 70 #include <utility> 71 #include <vector> 72 73 using namespace llvm; 74 75 #define DEBUG_TYPE "machine-scheduler" 76 77 STATISTIC(NumClustered, "Number of load/store pairs clustered"); 78 79 namespace llvm { 80 81 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden, 82 cl::desc("Force top-down list scheduling")); 83 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden, 84 cl::desc("Force bottom-up list scheduling")); 85 cl::opt<bool> 86 DumpCriticalPathLength("misched-dcpl", cl::Hidden, 87 cl::desc("Print critical path length to stdout")); 88 89 cl::opt<bool> VerifyScheduling( 90 "verify-misched", cl::Hidden, 91 cl::desc("Verify machine instrs before and after machine scheduling")); 92 93 } // end namespace llvm 94 95 #ifndef NDEBUG 96 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden, 97 cl::desc("Pop up a window to show MISched dags after they are processed")); 98 99 /// In some situations a few uninteresting nodes depend on nearly all other 100 /// nodes in the graph, provide a cutoff to hide them. 101 static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden, 102 cl::desc("Hide nodes with more predecessor/successor than cutoff")); 103 104 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden, 105 cl::desc("Stop scheduling after N instructions"), cl::init(~0U)); 106 107 static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden, 108 cl::desc("Only schedule this function")); 109 static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden, 110 cl::desc("Only schedule this MBB#")); 111 static cl::opt<bool> PrintDAGs("misched-print-dags", cl::Hidden, 112 cl::desc("Print schedule DAGs")); 113 #else 114 static const bool ViewMISchedDAGs = false; 115 static const bool PrintDAGs = false; 116 #endif // NDEBUG 117 118 /// Avoid quadratic complexity in unusually large basic blocks by limiting the 119 /// size of the ready lists. 120 static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden, 121 cl::desc("Limit ready list to N instructions"), cl::init(256)); 122 123 static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden, 124 cl::desc("Enable register pressure scheduling."), cl::init(true)); 125 126 static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden, 127 cl::desc("Enable cyclic critical path analysis."), cl::init(true)); 128 129 static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden, 130 cl::desc("Enable memop clustering."), 131 cl::init(true)); 132 133 // DAG subtrees must have at least this many nodes. 134 static const unsigned MinSubtreeSize = 8; 135 136 // Pin the vtables to this file. 137 void MachineSchedStrategy::anchor() {} 138 139 void ScheduleDAGMutation::anchor() {} 140 141 //===----------------------------------------------------------------------===// 142 // Machine Instruction Scheduling Pass and Registry 143 //===----------------------------------------------------------------------===// 144 145 MachineSchedContext::MachineSchedContext() { 146 RegClassInfo = new RegisterClassInfo(); 147 } 148 149 MachineSchedContext::~MachineSchedContext() { 150 delete RegClassInfo; 151 } 152 153 namespace { 154 155 /// Base class for a machine scheduler class that can run at any point. 156 class MachineSchedulerBase : public MachineSchedContext, 157 public MachineFunctionPass { 158 public: 159 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {} 160 161 void print(raw_ostream &O, const Module* = nullptr) const override; 162 163 protected: 164 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags); 165 }; 166 167 /// MachineScheduler runs after coalescing and before register allocation. 168 class MachineScheduler : public MachineSchedulerBase { 169 public: 170 MachineScheduler(); 171 172 void getAnalysisUsage(AnalysisUsage &AU) const override; 173 174 bool runOnMachineFunction(MachineFunction&) override; 175 176 static char ID; // Class identification, replacement for typeinfo 177 178 protected: 179 ScheduleDAGInstrs *createMachineScheduler(); 180 }; 181 182 /// PostMachineScheduler runs after shortly before code emission. 183 class PostMachineScheduler : public MachineSchedulerBase { 184 public: 185 PostMachineScheduler(); 186 187 void getAnalysisUsage(AnalysisUsage &AU) const override; 188 189 bool runOnMachineFunction(MachineFunction&) override; 190 191 static char ID; // Class identification, replacement for typeinfo 192 193 protected: 194 ScheduleDAGInstrs *createPostMachineScheduler(); 195 }; 196 197 } // end anonymous namespace 198 199 char MachineScheduler::ID = 0; 200 201 char &llvm::MachineSchedulerID = MachineScheduler::ID; 202 203 INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE, 204 "Machine Instruction Scheduler", false, false) 205 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 206 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 207 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 208 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 209 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 210 INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE, 211 "Machine Instruction Scheduler", false, false) 212 213 MachineScheduler::MachineScheduler() : MachineSchedulerBase(ID) { 214 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry()); 215 } 216 217 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const { 218 AU.setPreservesCFG(); 219 AU.addRequired<MachineDominatorTree>(); 220 AU.addRequired<MachineLoopInfo>(); 221 AU.addRequired<AAResultsWrapperPass>(); 222 AU.addRequired<TargetPassConfig>(); 223 AU.addRequired<SlotIndexes>(); 224 AU.addPreserved<SlotIndexes>(); 225 AU.addRequired<LiveIntervals>(); 226 AU.addPreserved<LiveIntervals>(); 227 MachineFunctionPass::getAnalysisUsage(AU); 228 } 229 230 char PostMachineScheduler::ID = 0; 231 232 char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID; 233 234 INITIALIZE_PASS(PostMachineScheduler, "postmisched", 235 "PostRA Machine Instruction Scheduler", false, false) 236 237 PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(ID) { 238 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry()); 239 } 240 241 void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const { 242 AU.setPreservesCFG(); 243 AU.addRequired<MachineDominatorTree>(); 244 AU.addRequired<MachineLoopInfo>(); 245 AU.addRequired<AAResultsWrapperPass>(); 246 AU.addRequired<TargetPassConfig>(); 247 MachineFunctionPass::getAnalysisUsage(AU); 248 } 249 250 MachinePassRegistry<MachineSchedRegistry::ScheduleDAGCtor> 251 MachineSchedRegistry::Registry; 252 253 /// A dummy default scheduler factory indicates whether the scheduler 254 /// is overridden on the command line. 255 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) { 256 return nullptr; 257 } 258 259 /// MachineSchedOpt allows command line selection of the scheduler. 260 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false, 261 RegisterPassParser<MachineSchedRegistry>> 262 MachineSchedOpt("misched", 263 cl::init(&useDefaultMachineSched), cl::Hidden, 264 cl::desc("Machine instruction scheduler to use")); 265 266 static MachineSchedRegistry 267 DefaultSchedRegistry("default", "Use the target's default scheduler choice.", 268 useDefaultMachineSched); 269 270 static cl::opt<bool> EnableMachineSched( 271 "enable-misched", 272 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true), 273 cl::Hidden); 274 275 static cl::opt<bool> EnablePostRAMachineSched( 276 "enable-post-misched", 277 cl::desc("Enable the post-ra machine instruction scheduling pass."), 278 cl::init(true), cl::Hidden); 279 280 /// Decrement this iterator until reaching the top or a non-debug instr. 281 static MachineBasicBlock::const_iterator 282 priorNonDebug(MachineBasicBlock::const_iterator I, 283 MachineBasicBlock::const_iterator Beg) { 284 assert(I != Beg && "reached the top of the region, cannot decrement"); 285 while (--I != Beg) { 286 if (!I->isDebugInstr()) 287 break; 288 } 289 return I; 290 } 291 292 /// Non-const version. 293 static MachineBasicBlock::iterator 294 priorNonDebug(MachineBasicBlock::iterator I, 295 MachineBasicBlock::const_iterator Beg) { 296 return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg) 297 .getNonConstIterator(); 298 } 299 300 /// If this iterator is a debug value, increment until reaching the End or a 301 /// non-debug instruction. 302 static MachineBasicBlock::const_iterator 303 nextIfDebug(MachineBasicBlock::const_iterator I, 304 MachineBasicBlock::const_iterator End) { 305 for(; I != End; ++I) { 306 if (!I->isDebugInstr()) 307 break; 308 } 309 return I; 310 } 311 312 /// Non-const version. 313 static MachineBasicBlock::iterator 314 nextIfDebug(MachineBasicBlock::iterator I, 315 MachineBasicBlock::const_iterator End) { 316 return nextIfDebug(MachineBasicBlock::const_iterator(I), End) 317 .getNonConstIterator(); 318 } 319 320 /// Instantiate a ScheduleDAGInstrs that will be owned by the caller. 321 ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() { 322 // Select the scheduler, or set the default. 323 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt; 324 if (Ctor != useDefaultMachineSched) 325 return Ctor(this); 326 327 // Get the default scheduler set by the target for this function. 328 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this); 329 if (Scheduler) 330 return Scheduler; 331 332 // Default to GenericScheduler. 333 return createGenericSchedLive(this); 334 } 335 336 /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by 337 /// the caller. We don't have a command line option to override the postRA 338 /// scheduler. The Target must configure it. 339 ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() { 340 // Get the postRA scheduler set by the target for this function. 341 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this); 342 if (Scheduler) 343 return Scheduler; 344 345 // Default to GenericScheduler. 346 return createGenericSchedPostRA(this); 347 } 348 349 /// Top-level MachineScheduler pass driver. 350 /// 351 /// Visit blocks in function order. Divide each block into scheduling regions 352 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is 353 /// consistent with the DAG builder, which traverses the interior of the 354 /// scheduling regions bottom-up. 355 /// 356 /// This design avoids exposing scheduling boundaries to the DAG builder, 357 /// simplifying the DAG builder's support for "special" target instructions. 358 /// At the same time the design allows target schedulers to operate across 359 /// scheduling boundaries, for example to bundle the boundary instructions 360 /// without reordering them. This creates complexity, because the target 361 /// scheduler must update the RegionBegin and RegionEnd positions cached by 362 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler 363 /// design would be to split blocks at scheduling boundaries, but LLVM has a 364 /// general bias against block splitting purely for implementation simplicity. 365 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) { 366 if (skipFunction(mf.getFunction())) 367 return false; 368 369 if (EnableMachineSched.getNumOccurrences()) { 370 if (!EnableMachineSched) 371 return false; 372 } else if (!mf.getSubtarget().enableMachineScheduler()) 373 return false; 374 375 LLVM_DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs())); 376 377 // Initialize the context of the pass. 378 MF = &mf; 379 MLI = &getAnalysis<MachineLoopInfo>(); 380 MDT = &getAnalysis<MachineDominatorTree>(); 381 PassConfig = &getAnalysis<TargetPassConfig>(); 382 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 383 384 LIS = &getAnalysis<LiveIntervals>(); 385 386 if (VerifyScheduling) { 387 LLVM_DEBUG(LIS->dump()); 388 MF->verify(this, "Before machine scheduling."); 389 } 390 RegClassInfo->runOnMachineFunction(*MF); 391 392 // Instantiate the selected scheduler for this target, function, and 393 // optimization level. 394 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler()); 395 scheduleRegions(*Scheduler, false); 396 397 LLVM_DEBUG(LIS->dump()); 398 if (VerifyScheduling) 399 MF->verify(this, "After machine scheduling."); 400 return true; 401 } 402 403 bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) { 404 if (skipFunction(mf.getFunction())) 405 return false; 406 407 if (EnablePostRAMachineSched.getNumOccurrences()) { 408 if (!EnablePostRAMachineSched) 409 return false; 410 } else if (!mf.getSubtarget().enablePostRAMachineScheduler()) { 411 LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n"); 412 return false; 413 } 414 LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs())); 415 416 // Initialize the context of the pass. 417 MF = &mf; 418 MLI = &getAnalysis<MachineLoopInfo>(); 419 PassConfig = &getAnalysis<TargetPassConfig>(); 420 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 421 422 if (VerifyScheduling) 423 MF->verify(this, "Before post machine scheduling."); 424 425 // Instantiate the selected scheduler for this target, function, and 426 // optimization level. 427 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler()); 428 scheduleRegions(*Scheduler, true); 429 430 if (VerifyScheduling) 431 MF->verify(this, "After post machine scheduling."); 432 return true; 433 } 434 435 /// Return true of the given instruction should not be included in a scheduling 436 /// region. 437 /// 438 /// MachineScheduler does not currently support scheduling across calls. To 439 /// handle calls, the DAG builder needs to be modified to create register 440 /// anti/output dependencies on the registers clobbered by the call's regmask 441 /// operand. In PreRA scheduling, the stack pointer adjustment already prevents 442 /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce 443 /// the boundary, but there would be no benefit to postRA scheduling across 444 /// calls this late anyway. 445 static bool isSchedBoundary(MachineBasicBlock::iterator MI, 446 MachineBasicBlock *MBB, 447 MachineFunction *MF, 448 const TargetInstrInfo *TII) { 449 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF); 450 } 451 452 /// A region of an MBB for scheduling. 453 namespace { 454 struct SchedRegion { 455 /// RegionBegin is the first instruction in the scheduling region, and 456 /// RegionEnd is either MBB->end() or the scheduling boundary after the 457 /// last instruction in the scheduling region. These iterators cannot refer 458 /// to instructions outside of the identified scheduling region because 459 /// those may be reordered before scheduling this region. 460 MachineBasicBlock::iterator RegionBegin; 461 MachineBasicBlock::iterator RegionEnd; 462 unsigned NumRegionInstrs; 463 464 SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E, 465 unsigned N) : 466 RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {} 467 }; 468 } // end anonymous namespace 469 470 using MBBRegionsVector = SmallVector<SchedRegion, 16>; 471 472 static void 473 getSchedRegions(MachineBasicBlock *MBB, 474 MBBRegionsVector &Regions, 475 bool RegionsTopDown) { 476 MachineFunction *MF = MBB->getParent(); 477 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 478 479 MachineBasicBlock::iterator I = nullptr; 480 for(MachineBasicBlock::iterator RegionEnd = MBB->end(); 481 RegionEnd != MBB->begin(); RegionEnd = I) { 482 483 // Avoid decrementing RegionEnd for blocks with no terminator. 484 if (RegionEnd != MBB->end() || 485 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) { 486 --RegionEnd; 487 } 488 489 // The next region starts above the previous region. Look backward in the 490 // instruction stream until we find the nearest boundary. 491 unsigned NumRegionInstrs = 0; 492 I = RegionEnd; 493 for (;I != MBB->begin(); --I) { 494 MachineInstr &MI = *std::prev(I); 495 if (isSchedBoundary(&MI, &*MBB, MF, TII)) 496 break; 497 if (!MI.isDebugInstr()) { 498 // MBB::size() uses instr_iterator to count. Here we need a bundle to 499 // count as a single instruction. 500 ++NumRegionInstrs; 501 } 502 } 503 504 // It's possible we found a scheduling region that only has debug 505 // instructions. Don't bother scheduling these. 506 if (NumRegionInstrs != 0) 507 Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs)); 508 } 509 510 if (RegionsTopDown) 511 std::reverse(Regions.begin(), Regions.end()); 512 } 513 514 /// Main driver for both MachineScheduler and PostMachineScheduler. 515 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler, 516 bool FixKillFlags) { 517 // Visit all machine basic blocks. 518 // 519 // TODO: Visit blocks in global postorder or postorder within the bottom-up 520 // loop tree. Then we can optionally compute global RegPressure. 521 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end(); 522 MBB != MBBEnd; ++MBB) { 523 524 Scheduler.startBlock(&*MBB); 525 526 #ifndef NDEBUG 527 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName()) 528 continue; 529 if (SchedOnlyBlock.getNumOccurrences() 530 && (int)SchedOnlyBlock != MBB->getNumber()) 531 continue; 532 #endif 533 534 // Break the block into scheduling regions [I, RegionEnd). RegionEnd 535 // points to the scheduling boundary at the bottom of the region. The DAG 536 // does not include RegionEnd, but the region does (i.e. the next 537 // RegionEnd is above the previous RegionBegin). If the current block has 538 // no terminator then RegionEnd == MBB->end() for the bottom region. 539 // 540 // All the regions of MBB are first found and stored in MBBRegions, which 541 // will be processed (MBB) top-down if initialized with true. 542 // 543 // The Scheduler may insert instructions during either schedule() or 544 // exitRegion(), even for empty regions. So the local iterators 'I' and 545 // 'RegionEnd' are invalid across these calls. Instructions must not be 546 // added to other regions than the current one without updating MBBRegions. 547 548 MBBRegionsVector MBBRegions; 549 getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown()); 550 for (MBBRegionsVector::iterator R = MBBRegions.begin(); 551 R != MBBRegions.end(); ++R) { 552 MachineBasicBlock::iterator I = R->RegionBegin; 553 MachineBasicBlock::iterator RegionEnd = R->RegionEnd; 554 unsigned NumRegionInstrs = R->NumRegionInstrs; 555 556 // Notify the scheduler of the region, even if we may skip scheduling 557 // it. Perhaps it still needs to be bundled. 558 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs); 559 560 // Skip empty scheduling regions (0 or 1 schedulable instructions). 561 if (I == RegionEnd || I == std::prev(RegionEnd)) { 562 // Close the current region. Bundle the terminator if needed. 563 // This invalidates 'RegionEnd' and 'I'. 564 Scheduler.exitRegion(); 565 continue; 566 } 567 LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n"); 568 LLVM_DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB) 569 << " " << MBB->getName() << "\n From: " << *I 570 << " To: "; 571 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd; 572 else dbgs() << "End"; 573 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n'); 574 if (DumpCriticalPathLength) { 575 errs() << MF->getName(); 576 errs() << ":%bb. " << MBB->getNumber(); 577 errs() << " " << MBB->getName() << " \n"; 578 } 579 580 // Schedule a region: possibly reorder instructions. 581 // This invalidates the original region iterators. 582 Scheduler.schedule(); 583 584 // Close the current region. 585 Scheduler.exitRegion(); 586 } 587 Scheduler.finishBlock(); 588 // FIXME: Ideally, no further passes should rely on kill flags. However, 589 // thumb2 size reduction is currently an exception, so the PostMIScheduler 590 // needs to do this. 591 if (FixKillFlags) 592 Scheduler.fixupKills(*MBB); 593 } 594 Scheduler.finalizeSchedule(); 595 } 596 597 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const { 598 // unimplemented 599 } 600 601 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 602 LLVM_DUMP_METHOD void ReadyQueue::dump() const { 603 dbgs() << "Queue " << Name << ": "; 604 for (const SUnit *SU : Queue) 605 dbgs() << SU->NodeNum << " "; 606 dbgs() << "\n"; 607 } 608 #endif 609 610 //===----------------------------------------------------------------------===// 611 // ScheduleDAGMI - Basic machine instruction scheduling. This is 612 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for 613 // virtual registers. 614 // ===----------------------------------------------------------------------===/ 615 616 // Provide a vtable anchor. 617 ScheduleDAGMI::~ScheduleDAGMI() = default; 618 619 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When 620 /// NumPredsLeft reaches zero, release the successor node. 621 /// 622 /// FIXME: Adjust SuccSU height based on MinLatency. 623 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) { 624 SUnit *SuccSU = SuccEdge->getSUnit(); 625 626 if (SuccEdge->isWeak()) { 627 --SuccSU->WeakPredsLeft; 628 if (SuccEdge->isCluster()) 629 NextClusterSucc = SuccSU; 630 return; 631 } 632 #ifndef NDEBUG 633 if (SuccSU->NumPredsLeft == 0) { 634 dbgs() << "*** Scheduling failed! ***\n"; 635 dumpNode(*SuccSU); 636 dbgs() << " has been released too many times!\n"; 637 llvm_unreachable(nullptr); 638 } 639 #endif 640 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However, 641 // CurrCycle may have advanced since then. 642 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency()) 643 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency(); 644 645 --SuccSU->NumPredsLeft; 646 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) 647 SchedImpl->releaseTopNode(SuccSU); 648 } 649 650 /// releaseSuccessors - Call releaseSucc on each of SU's successors. 651 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) { 652 for (SDep &Succ : SU->Succs) 653 releaseSucc(SU, &Succ); 654 } 655 656 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When 657 /// NumSuccsLeft reaches zero, release the predecessor node. 658 /// 659 /// FIXME: Adjust PredSU height based on MinLatency. 660 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) { 661 SUnit *PredSU = PredEdge->getSUnit(); 662 663 if (PredEdge->isWeak()) { 664 --PredSU->WeakSuccsLeft; 665 if (PredEdge->isCluster()) 666 NextClusterPred = PredSU; 667 return; 668 } 669 #ifndef NDEBUG 670 if (PredSU->NumSuccsLeft == 0) { 671 dbgs() << "*** Scheduling failed! ***\n"; 672 dumpNode(*PredSU); 673 dbgs() << " has been released too many times!\n"; 674 llvm_unreachable(nullptr); 675 } 676 #endif 677 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However, 678 // CurrCycle may have advanced since then. 679 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency()) 680 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency(); 681 682 --PredSU->NumSuccsLeft; 683 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) 684 SchedImpl->releaseBottomNode(PredSU); 685 } 686 687 /// releasePredecessors - Call releasePred on each of SU's predecessors. 688 void ScheduleDAGMI::releasePredecessors(SUnit *SU) { 689 for (SDep &Pred : SU->Preds) 690 releasePred(SU, &Pred); 691 } 692 693 void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) { 694 ScheduleDAGInstrs::startBlock(bb); 695 SchedImpl->enterMBB(bb); 696 } 697 698 void ScheduleDAGMI::finishBlock() { 699 SchedImpl->leaveMBB(); 700 ScheduleDAGInstrs::finishBlock(); 701 } 702 703 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after 704 /// crossing a scheduling boundary. [begin, end) includes all instructions in 705 /// the region, including the boundary itself and single-instruction regions 706 /// that don't get scheduled. 707 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb, 708 MachineBasicBlock::iterator begin, 709 MachineBasicBlock::iterator end, 710 unsigned regioninstrs) 711 { 712 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs); 713 714 SchedImpl->initPolicy(begin, end, regioninstrs); 715 } 716 717 /// This is normally called from the main scheduler loop but may also be invoked 718 /// by the scheduling strategy to perform additional code motion. 719 void ScheduleDAGMI::moveInstruction( 720 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) { 721 // Advance RegionBegin if the first instruction moves down. 722 if (&*RegionBegin == MI) 723 ++RegionBegin; 724 725 // Update the instruction stream. 726 BB->splice(InsertPos, BB, MI); 727 728 // Update LiveIntervals 729 if (LIS) 730 LIS->handleMove(*MI, /*UpdateFlags=*/true); 731 732 // Recede RegionBegin if an instruction moves above the first. 733 if (RegionBegin == InsertPos) 734 RegionBegin = MI; 735 } 736 737 bool ScheduleDAGMI::checkSchedLimit() { 738 #ifndef NDEBUG 739 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) { 740 CurrentTop = CurrentBottom; 741 return false; 742 } 743 ++NumInstrsScheduled; 744 #endif 745 return true; 746 } 747 748 /// Per-region scheduling driver, called back from 749 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that 750 /// does not consider liveness or register pressure. It is useful for PostRA 751 /// scheduling and potentially other custom schedulers. 752 void ScheduleDAGMI::schedule() { 753 LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n"); 754 LLVM_DEBUG(SchedImpl->dumpPolicy()); 755 756 // Build the DAG. 757 buildSchedGraph(AA); 758 759 postprocessDAG(); 760 761 SmallVector<SUnit*, 8> TopRoots, BotRoots; 762 findRootsAndBiasEdges(TopRoots, BotRoots); 763 764 LLVM_DEBUG(dump()); 765 if (PrintDAGs) dump(); 766 if (ViewMISchedDAGs) viewGraph(); 767 768 // Initialize the strategy before modifying the DAG. 769 // This may initialize a DFSResult to be used for queue priority. 770 SchedImpl->initialize(this); 771 772 // Initialize ready queues now that the DAG and priority data are finalized. 773 initQueues(TopRoots, BotRoots); 774 775 bool IsTopNode = false; 776 while (true) { 777 LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n"); 778 SUnit *SU = SchedImpl->pickNode(IsTopNode); 779 if (!SU) break; 780 781 assert(!SU->isScheduled && "Node already scheduled"); 782 if (!checkSchedLimit()) 783 break; 784 785 MachineInstr *MI = SU->getInstr(); 786 if (IsTopNode) { 787 assert(SU->isTopReady() && "node still has unscheduled dependencies"); 788 if (&*CurrentTop == MI) 789 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom); 790 else 791 moveInstruction(MI, CurrentTop); 792 } else { 793 assert(SU->isBottomReady() && "node still has unscheduled dependencies"); 794 MachineBasicBlock::iterator priorII = 795 priorNonDebug(CurrentBottom, CurrentTop); 796 if (&*priorII == MI) 797 CurrentBottom = priorII; 798 else { 799 if (&*CurrentTop == MI) 800 CurrentTop = nextIfDebug(++CurrentTop, priorII); 801 moveInstruction(MI, CurrentBottom); 802 CurrentBottom = MI; 803 } 804 } 805 // Notify the scheduling strategy before updating the DAG. 806 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues 807 // runs, it can then use the accurate ReadyCycle time to determine whether 808 // newly released nodes can move to the readyQ. 809 SchedImpl->schedNode(SU, IsTopNode); 810 811 updateQueues(SU, IsTopNode); 812 } 813 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone."); 814 815 placeDebugValues(); 816 817 LLVM_DEBUG({ 818 dbgs() << "*** Final schedule for " 819 << printMBBReference(*begin()->getParent()) << " ***\n"; 820 dumpSchedule(); 821 dbgs() << '\n'; 822 }); 823 } 824 825 /// Apply each ScheduleDAGMutation step in order. 826 void ScheduleDAGMI::postprocessDAG() { 827 for (auto &m : Mutations) 828 m->apply(this); 829 } 830 831 void ScheduleDAGMI:: 832 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots, 833 SmallVectorImpl<SUnit*> &BotRoots) { 834 for (SUnit &SU : SUnits) { 835 assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits"); 836 837 // Order predecessors so DFSResult follows the critical path. 838 SU.biasCriticalPath(); 839 840 // A SUnit is ready to top schedule if it has no predecessors. 841 if (!SU.NumPredsLeft) 842 TopRoots.push_back(&SU); 843 // A SUnit is ready to bottom schedule if it has no successors. 844 if (!SU.NumSuccsLeft) 845 BotRoots.push_back(&SU); 846 } 847 ExitSU.biasCriticalPath(); 848 } 849 850 /// Identify DAG roots and setup scheduler queues. 851 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots, 852 ArrayRef<SUnit*> BotRoots) { 853 NextClusterSucc = nullptr; 854 NextClusterPred = nullptr; 855 856 // Release all DAG roots for scheduling, not including EntrySU/ExitSU. 857 // 858 // Nodes with unreleased weak edges can still be roots. 859 // Release top roots in forward order. 860 for (SUnit *SU : TopRoots) 861 SchedImpl->releaseTopNode(SU); 862 863 // Release bottom roots in reverse order so the higher priority nodes appear 864 // first. This is more natural and slightly more efficient. 865 for (SmallVectorImpl<SUnit*>::const_reverse_iterator 866 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) { 867 SchedImpl->releaseBottomNode(*I); 868 } 869 870 releaseSuccessors(&EntrySU); 871 releasePredecessors(&ExitSU); 872 873 SchedImpl->registerRoots(); 874 875 // Advance past initial DebugValues. 876 CurrentTop = nextIfDebug(RegionBegin, RegionEnd); 877 CurrentBottom = RegionEnd; 878 } 879 880 /// Update scheduler queues after scheduling an instruction. 881 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) { 882 // Release dependent instructions for scheduling. 883 if (IsTopNode) 884 releaseSuccessors(SU); 885 else 886 releasePredecessors(SU); 887 888 SU->isScheduled = true; 889 } 890 891 /// Reinsert any remaining debug_values, just like the PostRA scheduler. 892 void ScheduleDAGMI::placeDebugValues() { 893 // If first instruction was a DBG_VALUE then put it back. 894 if (FirstDbgValue) { 895 BB->splice(RegionBegin, BB, FirstDbgValue); 896 RegionBegin = FirstDbgValue; 897 } 898 899 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator 900 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) { 901 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI); 902 MachineInstr *DbgValue = P.first; 903 MachineBasicBlock::iterator OrigPrevMI = P.second; 904 if (&*RegionBegin == DbgValue) 905 ++RegionBegin; 906 BB->splice(++OrigPrevMI, BB, DbgValue); 907 if (OrigPrevMI == std::prev(RegionEnd)) 908 RegionEnd = DbgValue; 909 } 910 DbgValues.clear(); 911 FirstDbgValue = nullptr; 912 } 913 914 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 915 LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const { 916 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) { 917 if (SUnit *SU = getSUnit(&(*MI))) 918 dumpNode(*SU); 919 else 920 dbgs() << "Missing SUnit\n"; 921 } 922 } 923 #endif 924 925 //===----------------------------------------------------------------------===// 926 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals 927 // preservation. 928 //===----------------------------------------------------------------------===// 929 930 ScheduleDAGMILive::~ScheduleDAGMILive() { 931 delete DFSResult; 932 } 933 934 void ScheduleDAGMILive::collectVRegUses(SUnit &SU) { 935 const MachineInstr &MI = *SU.getInstr(); 936 for (const MachineOperand &MO : MI.operands()) { 937 if (!MO.isReg()) 938 continue; 939 if (!MO.readsReg()) 940 continue; 941 if (TrackLaneMasks && !MO.isUse()) 942 continue; 943 944 Register Reg = MO.getReg(); 945 if (!Register::isVirtualRegister(Reg)) 946 continue; 947 948 // Ignore re-defs. 949 if (TrackLaneMasks) { 950 bool FoundDef = false; 951 for (const MachineOperand &MO2 : MI.operands()) { 952 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) { 953 FoundDef = true; 954 break; 955 } 956 } 957 if (FoundDef) 958 continue; 959 } 960 961 // Record this local VReg use. 962 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg); 963 for (; UI != VRegUses.end(); ++UI) { 964 if (UI->SU == &SU) 965 break; 966 } 967 if (UI == VRegUses.end()) 968 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU)); 969 } 970 } 971 972 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after 973 /// crossing a scheduling boundary. [begin, end) includes all instructions in 974 /// the region, including the boundary itself and single-instruction regions 975 /// that don't get scheduled. 976 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb, 977 MachineBasicBlock::iterator begin, 978 MachineBasicBlock::iterator end, 979 unsigned regioninstrs) 980 { 981 // ScheduleDAGMI initializes SchedImpl's per-region policy. 982 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs); 983 984 // For convenience remember the end of the liveness region. 985 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd); 986 987 SUPressureDiffs.clear(); 988 989 ShouldTrackPressure = SchedImpl->shouldTrackPressure(); 990 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks(); 991 992 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) && 993 "ShouldTrackLaneMasks requires ShouldTrackPressure"); 994 } 995 996 // Setup the register pressure trackers for the top scheduled and bottom 997 // scheduled regions. 998 void ScheduleDAGMILive::initRegPressure() { 999 VRegUses.clear(); 1000 VRegUses.setUniverse(MRI.getNumVirtRegs()); 1001 for (SUnit &SU : SUnits) 1002 collectVRegUses(SU); 1003 1004 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin, 1005 ShouldTrackLaneMasks, false); 1006 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd, 1007 ShouldTrackLaneMasks, false); 1008 1009 // Close the RPTracker to finalize live ins. 1010 RPTracker.closeRegion(); 1011 1012 LLVM_DEBUG(RPTracker.dump()); 1013 1014 // Initialize the live ins and live outs. 1015 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs); 1016 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs); 1017 1018 // Close one end of the tracker so we can call 1019 // getMaxUpward/DownwardPressureDelta before advancing across any 1020 // instructions. This converts currently live regs into live ins/outs. 1021 TopRPTracker.closeTop(); 1022 BotRPTracker.closeBottom(); 1023 1024 BotRPTracker.initLiveThru(RPTracker); 1025 if (!BotRPTracker.getLiveThru().empty()) { 1026 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru()); 1027 LLVM_DEBUG(dbgs() << "Live Thru: "; 1028 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI)); 1029 }; 1030 1031 // For each live out vreg reduce the pressure change associated with other 1032 // uses of the same vreg below the live-out reaching def. 1033 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs); 1034 1035 // Account for liveness generated by the region boundary. 1036 if (LiveRegionEnd != RegionEnd) { 1037 SmallVector<RegisterMaskPair, 8> LiveUses; 1038 BotRPTracker.recede(&LiveUses); 1039 updatePressureDiffs(LiveUses); 1040 } 1041 1042 LLVM_DEBUG(dbgs() << "Top Pressure:\n"; 1043 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI); 1044 dbgs() << "Bottom Pressure:\n"; 1045 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);); 1046 1047 assert((BotRPTracker.getPos() == RegionEnd || 1048 (RegionEnd->isDebugInstr() && 1049 BotRPTracker.getPos() == priorNonDebug(RegionEnd, RegionBegin))) && 1050 "Can't find the region bottom"); 1051 1052 // Cache the list of excess pressure sets in this region. This will also track 1053 // the max pressure in the scheduled code for these sets. 1054 RegionCriticalPSets.clear(); 1055 const std::vector<unsigned> &RegionPressure = 1056 RPTracker.getPressure().MaxSetPressure; 1057 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) { 1058 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i); 1059 if (RegionPressure[i] > Limit) { 1060 LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit 1061 << " Actual " << RegionPressure[i] << "\n"); 1062 RegionCriticalPSets.push_back(PressureChange(i)); 1063 } 1064 } 1065 LLVM_DEBUG(dbgs() << "Excess PSets: "; 1066 for (const PressureChange &RCPS 1067 : RegionCriticalPSets) dbgs() 1068 << TRI->getRegPressureSetName(RCPS.getPSet()) << " "; 1069 dbgs() << "\n"); 1070 } 1071 1072 void ScheduleDAGMILive:: 1073 updateScheduledPressure(const SUnit *SU, 1074 const std::vector<unsigned> &NewMaxPressure) { 1075 const PressureDiff &PDiff = getPressureDiff(SU); 1076 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size(); 1077 for (const PressureChange &PC : PDiff) { 1078 if (!PC.isValid()) 1079 break; 1080 unsigned ID = PC.getPSet(); 1081 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID) 1082 ++CritIdx; 1083 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) { 1084 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc() 1085 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max()) 1086 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]); 1087 } 1088 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID); 1089 if (NewMaxPressure[ID] >= Limit - 2) { 1090 LLVM_DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": " 1091 << NewMaxPressure[ID] 1092 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") 1093 << Limit << "(+ " << BotRPTracker.getLiveThru()[ID] 1094 << " livethru)\n"); 1095 } 1096 } 1097 } 1098 1099 /// Update the PressureDiff array for liveness after scheduling this 1100 /// instruction. 1101 void ScheduleDAGMILive::updatePressureDiffs( 1102 ArrayRef<RegisterMaskPair> LiveUses) { 1103 for (const RegisterMaskPair &P : LiveUses) { 1104 unsigned Reg = P.RegUnit; 1105 /// FIXME: Currently assuming single-use physregs. 1106 if (!Register::isVirtualRegister(Reg)) 1107 continue; 1108 1109 if (ShouldTrackLaneMasks) { 1110 // If the register has just become live then other uses won't change 1111 // this fact anymore => decrement pressure. 1112 // If the register has just become dead then other uses make it come 1113 // back to life => increment pressure. 1114 bool Decrement = P.LaneMask.any(); 1115 1116 for (const VReg2SUnit &V2SU 1117 : make_range(VRegUses.find(Reg), VRegUses.end())) { 1118 SUnit &SU = *V2SU.SU; 1119 if (SU.isScheduled || &SU == &ExitSU) 1120 continue; 1121 1122 PressureDiff &PDiff = getPressureDiff(&SU); 1123 PDiff.addPressureChange(Reg, Decrement, &MRI); 1124 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") " 1125 << printReg(Reg, TRI) << ':' 1126 << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr(); 1127 dbgs() << " to "; PDiff.dump(*TRI);); 1128 } 1129 } else { 1130 assert(P.LaneMask.any()); 1131 LLVM_DEBUG(dbgs() << " LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n"); 1132 // This may be called before CurrentBottom has been initialized. However, 1133 // BotRPTracker must have a valid position. We want the value live into the 1134 // instruction or live out of the block, so ask for the previous 1135 // instruction's live-out. 1136 const LiveInterval &LI = LIS->getInterval(Reg); 1137 VNInfo *VNI; 1138 MachineBasicBlock::const_iterator I = 1139 nextIfDebug(BotRPTracker.getPos(), BB->end()); 1140 if (I == BB->end()) 1141 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB)); 1142 else { 1143 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I)); 1144 VNI = LRQ.valueIn(); 1145 } 1146 // RegisterPressureTracker guarantees that readsReg is true for LiveUses. 1147 assert(VNI && "No live value at use."); 1148 for (const VReg2SUnit &V2SU 1149 : make_range(VRegUses.find(Reg), VRegUses.end())) { 1150 SUnit *SU = V2SU.SU; 1151 // If this use comes before the reaching def, it cannot be a last use, 1152 // so decrease its pressure change. 1153 if (!SU->isScheduled && SU != &ExitSU) { 1154 LiveQueryResult LRQ = 1155 LI.Query(LIS->getInstructionIndex(*SU->getInstr())); 1156 if (LRQ.valueIn() == VNI) { 1157 PressureDiff &PDiff = getPressureDiff(SU); 1158 PDiff.addPressureChange(Reg, true, &MRI); 1159 LLVM_DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") " 1160 << *SU->getInstr(); 1161 dbgs() << " to "; PDiff.dump(*TRI);); 1162 } 1163 } 1164 } 1165 } 1166 } 1167 } 1168 1169 void ScheduleDAGMILive::dump() const { 1170 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1171 if (EntrySU.getInstr() != nullptr) 1172 dumpNodeAll(EntrySU); 1173 for (const SUnit &SU : SUnits) { 1174 dumpNodeAll(SU); 1175 if (ShouldTrackPressure) { 1176 dbgs() << " Pressure Diff : "; 1177 getPressureDiff(&SU).dump(*TRI); 1178 } 1179 dbgs() << " Single Issue : "; 1180 if (SchedModel.mustBeginGroup(SU.getInstr()) && 1181 SchedModel.mustEndGroup(SU.getInstr())) 1182 dbgs() << "true;"; 1183 else 1184 dbgs() << "false;"; 1185 dbgs() << '\n'; 1186 } 1187 if (ExitSU.getInstr() != nullptr) 1188 dumpNodeAll(ExitSU); 1189 #endif 1190 } 1191 1192 /// schedule - Called back from MachineScheduler::runOnMachineFunction 1193 /// after setting up the current scheduling region. [RegionBegin, RegionEnd) 1194 /// only includes instructions that have DAG nodes, not scheduling boundaries. 1195 /// 1196 /// This is a skeletal driver, with all the functionality pushed into helpers, 1197 /// so that it can be easily extended by experimental schedulers. Generally, 1198 /// implementing MachineSchedStrategy should be sufficient to implement a new 1199 /// scheduling algorithm. However, if a scheduler further subclasses 1200 /// ScheduleDAGMILive then it will want to override this virtual method in order 1201 /// to update any specialized state. 1202 void ScheduleDAGMILive::schedule() { 1203 LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n"); 1204 LLVM_DEBUG(SchedImpl->dumpPolicy()); 1205 buildDAGWithRegPressure(); 1206 1207 postprocessDAG(); 1208 1209 SmallVector<SUnit*, 8> TopRoots, BotRoots; 1210 findRootsAndBiasEdges(TopRoots, BotRoots); 1211 1212 // Initialize the strategy before modifying the DAG. 1213 // This may initialize a DFSResult to be used for queue priority. 1214 SchedImpl->initialize(this); 1215 1216 LLVM_DEBUG(dump()); 1217 if (PrintDAGs) dump(); 1218 if (ViewMISchedDAGs) viewGraph(); 1219 1220 // Initialize ready queues now that the DAG and priority data are finalized. 1221 initQueues(TopRoots, BotRoots); 1222 1223 bool IsTopNode = false; 1224 while (true) { 1225 LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n"); 1226 SUnit *SU = SchedImpl->pickNode(IsTopNode); 1227 if (!SU) break; 1228 1229 assert(!SU->isScheduled && "Node already scheduled"); 1230 if (!checkSchedLimit()) 1231 break; 1232 1233 scheduleMI(SU, IsTopNode); 1234 1235 if (DFSResult) { 1236 unsigned SubtreeID = DFSResult->getSubtreeID(SU); 1237 if (!ScheduledTrees.test(SubtreeID)) { 1238 ScheduledTrees.set(SubtreeID); 1239 DFSResult->scheduleTree(SubtreeID); 1240 SchedImpl->scheduleTree(SubtreeID); 1241 } 1242 } 1243 1244 // Notify the scheduling strategy after updating the DAG. 1245 SchedImpl->schedNode(SU, IsTopNode); 1246 1247 updateQueues(SU, IsTopNode); 1248 } 1249 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone."); 1250 1251 placeDebugValues(); 1252 1253 LLVM_DEBUG({ 1254 dbgs() << "*** Final schedule for " 1255 << printMBBReference(*begin()->getParent()) << " ***\n"; 1256 dumpSchedule(); 1257 dbgs() << '\n'; 1258 }); 1259 } 1260 1261 /// Build the DAG and setup three register pressure trackers. 1262 void ScheduleDAGMILive::buildDAGWithRegPressure() { 1263 if (!ShouldTrackPressure) { 1264 RPTracker.reset(); 1265 RegionCriticalPSets.clear(); 1266 buildSchedGraph(AA); 1267 return; 1268 } 1269 1270 // Initialize the register pressure tracker used by buildSchedGraph. 1271 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd, 1272 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true); 1273 1274 // Account for liveness generate by the region boundary. 1275 if (LiveRegionEnd != RegionEnd) 1276 RPTracker.recede(); 1277 1278 // Build the DAG, and compute current register pressure. 1279 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks); 1280 1281 // Initialize top/bottom trackers after computing region pressure. 1282 initRegPressure(); 1283 } 1284 1285 void ScheduleDAGMILive::computeDFSResult() { 1286 if (!DFSResult) 1287 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize); 1288 DFSResult->clear(); 1289 ScheduledTrees.clear(); 1290 DFSResult->resize(SUnits.size()); 1291 DFSResult->compute(SUnits); 1292 ScheduledTrees.resize(DFSResult->getNumSubtrees()); 1293 } 1294 1295 /// Compute the max cyclic critical path through the DAG. The scheduling DAG 1296 /// only provides the critical path for single block loops. To handle loops that 1297 /// span blocks, we could use the vreg path latencies provided by 1298 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently 1299 /// available for use in the scheduler. 1300 /// 1301 /// The cyclic path estimation identifies a def-use pair that crosses the back 1302 /// edge and considers the depth and height of the nodes. For example, consider 1303 /// the following instruction sequence where each instruction has unit latency 1304 /// and defines an eponymous virtual register: 1305 /// 1306 /// a->b(a,c)->c(b)->d(c)->exit 1307 /// 1308 /// The cyclic critical path is a two cycles: b->c->b 1309 /// The acyclic critical path is four cycles: a->b->c->d->exit 1310 /// LiveOutHeight = height(c) = len(c->d->exit) = 2 1311 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3 1312 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4 1313 /// LiveInDepth = depth(b) = len(a->b) = 1 1314 /// 1315 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2 1316 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2 1317 /// CyclicCriticalPath = min(2, 2) = 2 1318 /// 1319 /// This could be relevant to PostRA scheduling, but is currently implemented 1320 /// assuming LiveIntervals. 1321 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() { 1322 // This only applies to single block loop. 1323 if (!BB->isSuccessor(BB)) 1324 return 0; 1325 1326 unsigned MaxCyclicLatency = 0; 1327 // Visit each live out vreg def to find def/use pairs that cross iterations. 1328 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) { 1329 unsigned Reg = P.RegUnit; 1330 if (!Register::isVirtualRegister(Reg)) 1331 continue; 1332 const LiveInterval &LI = LIS->getInterval(Reg); 1333 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB)); 1334 if (!DefVNI) 1335 continue; 1336 1337 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def); 1338 const SUnit *DefSU = getSUnit(DefMI); 1339 if (!DefSU) 1340 continue; 1341 1342 unsigned LiveOutHeight = DefSU->getHeight(); 1343 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency; 1344 // Visit all local users of the vreg def. 1345 for (const VReg2SUnit &V2SU 1346 : make_range(VRegUses.find(Reg), VRegUses.end())) { 1347 SUnit *SU = V2SU.SU; 1348 if (SU == &ExitSU) 1349 continue; 1350 1351 // Only consider uses of the phi. 1352 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr())); 1353 if (!LRQ.valueIn()->isPHIDef()) 1354 continue; 1355 1356 // Assume that a path spanning two iterations is a cycle, which could 1357 // overestimate in strange cases. This allows cyclic latency to be 1358 // estimated as the minimum slack of the vreg's depth or height. 1359 unsigned CyclicLatency = 0; 1360 if (LiveOutDepth > SU->getDepth()) 1361 CyclicLatency = LiveOutDepth - SU->getDepth(); 1362 1363 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency; 1364 if (LiveInHeight > LiveOutHeight) { 1365 if (LiveInHeight - LiveOutHeight < CyclicLatency) 1366 CyclicLatency = LiveInHeight - LiveOutHeight; 1367 } else 1368 CyclicLatency = 0; 1369 1370 LLVM_DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU(" 1371 << SU->NodeNum << ") = " << CyclicLatency << "c\n"); 1372 if (CyclicLatency > MaxCyclicLatency) 1373 MaxCyclicLatency = CyclicLatency; 1374 } 1375 } 1376 LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n"); 1377 return MaxCyclicLatency; 1378 } 1379 1380 /// Release ExitSU predecessors and setup scheduler queues. Re-position 1381 /// the Top RP tracker in case the region beginning has changed. 1382 void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots, 1383 ArrayRef<SUnit*> BotRoots) { 1384 ScheduleDAGMI::initQueues(TopRoots, BotRoots); 1385 if (ShouldTrackPressure) { 1386 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker"); 1387 TopRPTracker.setPos(CurrentTop); 1388 } 1389 } 1390 1391 /// Move an instruction and update register pressure. 1392 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) { 1393 // Move the instruction to its new location in the instruction stream. 1394 MachineInstr *MI = SU->getInstr(); 1395 1396 if (IsTopNode) { 1397 assert(SU->isTopReady() && "node still has unscheduled dependencies"); 1398 if (&*CurrentTop == MI) 1399 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom); 1400 else { 1401 moveInstruction(MI, CurrentTop); 1402 TopRPTracker.setPos(MI); 1403 } 1404 1405 if (ShouldTrackPressure) { 1406 // Update top scheduled pressure. 1407 RegisterOperands RegOpers; 1408 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false); 1409 if (ShouldTrackLaneMasks) { 1410 // Adjust liveness and add missing dead+read-undef flags. 1411 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot(); 1412 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI); 1413 } else { 1414 // Adjust for missing dead-def flags. 1415 RegOpers.detectDeadDefs(*MI, *LIS); 1416 } 1417 1418 TopRPTracker.advance(RegOpers); 1419 assert(TopRPTracker.getPos() == CurrentTop && "out of sync"); 1420 LLVM_DEBUG(dbgs() << "Top Pressure:\n"; dumpRegSetPressure( 1421 TopRPTracker.getRegSetPressureAtPos(), TRI);); 1422 1423 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure); 1424 } 1425 } else { 1426 assert(SU->isBottomReady() && "node still has unscheduled dependencies"); 1427 MachineBasicBlock::iterator priorII = 1428 priorNonDebug(CurrentBottom, CurrentTop); 1429 if (&*priorII == MI) 1430 CurrentBottom = priorII; 1431 else { 1432 if (&*CurrentTop == MI) { 1433 CurrentTop = nextIfDebug(++CurrentTop, priorII); 1434 TopRPTracker.setPos(CurrentTop); 1435 } 1436 moveInstruction(MI, CurrentBottom); 1437 CurrentBottom = MI; 1438 BotRPTracker.setPos(CurrentBottom); 1439 } 1440 if (ShouldTrackPressure) { 1441 RegisterOperands RegOpers; 1442 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false); 1443 if (ShouldTrackLaneMasks) { 1444 // Adjust liveness and add missing dead+read-undef flags. 1445 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot(); 1446 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI); 1447 } else { 1448 // Adjust for missing dead-def flags. 1449 RegOpers.detectDeadDefs(*MI, *LIS); 1450 } 1451 1452 if (BotRPTracker.getPos() != CurrentBottom) 1453 BotRPTracker.recedeSkipDebugValues(); 1454 SmallVector<RegisterMaskPair, 8> LiveUses; 1455 BotRPTracker.recede(RegOpers, &LiveUses); 1456 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync"); 1457 LLVM_DEBUG(dbgs() << "Bottom Pressure:\n"; dumpRegSetPressure( 1458 BotRPTracker.getRegSetPressureAtPos(), TRI);); 1459 1460 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure); 1461 updatePressureDiffs(LiveUses); 1462 } 1463 } 1464 } 1465 1466 //===----------------------------------------------------------------------===// 1467 // BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores. 1468 //===----------------------------------------------------------------------===// 1469 1470 namespace { 1471 1472 /// Post-process the DAG to create cluster edges between neighboring 1473 /// loads or between neighboring stores. 1474 class BaseMemOpClusterMutation : public ScheduleDAGMutation { 1475 struct MemOpInfo { 1476 SUnit *SU; 1477 SmallVector<const MachineOperand *, 4> BaseOps; 1478 int64_t Offset; 1479 unsigned Width; 1480 1481 MemOpInfo(SUnit *SU, ArrayRef<const MachineOperand *> BaseOps, 1482 int64_t Offset, unsigned Width) 1483 : SU(SU), BaseOps(BaseOps.begin(), BaseOps.end()), Offset(Offset), 1484 Width(Width) {} 1485 1486 static bool Compare(const MachineOperand *const &A, 1487 const MachineOperand *const &B) { 1488 if (A->getType() != B->getType()) 1489 return A->getType() < B->getType(); 1490 if (A->isReg()) 1491 return A->getReg() < B->getReg(); 1492 if (A->isFI()) { 1493 const MachineFunction &MF = *A->getParent()->getParent()->getParent(); 1494 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering(); 1495 bool StackGrowsDown = TFI.getStackGrowthDirection() == 1496 TargetFrameLowering::StackGrowsDown; 1497 return StackGrowsDown ? A->getIndex() > B->getIndex() 1498 : A->getIndex() < B->getIndex(); 1499 } 1500 1501 llvm_unreachable("MemOpClusterMutation only supports register or frame " 1502 "index bases."); 1503 } 1504 1505 bool operator<(const MemOpInfo &RHS) const { 1506 // FIXME: Don't compare everything twice. Maybe use C++20 three way 1507 // comparison instead when it's available. 1508 if (std::lexicographical_compare(BaseOps.begin(), BaseOps.end(), 1509 RHS.BaseOps.begin(), RHS.BaseOps.end(), 1510 Compare)) 1511 return true; 1512 if (std::lexicographical_compare(RHS.BaseOps.begin(), RHS.BaseOps.end(), 1513 BaseOps.begin(), BaseOps.end(), Compare)) 1514 return false; 1515 if (Offset != RHS.Offset) 1516 return Offset < RHS.Offset; 1517 return SU->NodeNum < RHS.SU->NodeNum; 1518 } 1519 }; 1520 1521 const TargetInstrInfo *TII; 1522 const TargetRegisterInfo *TRI; 1523 bool IsLoad; 1524 1525 public: 1526 BaseMemOpClusterMutation(const TargetInstrInfo *tii, 1527 const TargetRegisterInfo *tri, bool IsLoad) 1528 : TII(tii), TRI(tri), IsLoad(IsLoad) {} 1529 1530 void apply(ScheduleDAGInstrs *DAGInstrs) override; 1531 1532 protected: 1533 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGInstrs *DAG); 1534 }; 1535 1536 class StoreClusterMutation : public BaseMemOpClusterMutation { 1537 public: 1538 StoreClusterMutation(const TargetInstrInfo *tii, 1539 const TargetRegisterInfo *tri) 1540 : BaseMemOpClusterMutation(tii, tri, false) {} 1541 }; 1542 1543 class LoadClusterMutation : public BaseMemOpClusterMutation { 1544 public: 1545 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri) 1546 : BaseMemOpClusterMutation(tii, tri, true) {} 1547 }; 1548 1549 } // end anonymous namespace 1550 1551 namespace llvm { 1552 1553 std::unique_ptr<ScheduleDAGMutation> 1554 createLoadClusterDAGMutation(const TargetInstrInfo *TII, 1555 const TargetRegisterInfo *TRI) { 1556 return EnableMemOpCluster ? std::make_unique<LoadClusterMutation>(TII, TRI) 1557 : nullptr; 1558 } 1559 1560 std::unique_ptr<ScheduleDAGMutation> 1561 createStoreClusterDAGMutation(const TargetInstrInfo *TII, 1562 const TargetRegisterInfo *TRI) { 1563 return EnableMemOpCluster ? std::make_unique<StoreClusterMutation>(TII, TRI) 1564 : nullptr; 1565 } 1566 1567 } // end namespace llvm 1568 1569 void BaseMemOpClusterMutation::clusterNeighboringMemOps( 1570 ArrayRef<SUnit *> MemOps, ScheduleDAGInstrs *DAG) { 1571 SmallVector<MemOpInfo, 32> MemOpRecords; 1572 for (SUnit *SU : MemOps) { 1573 const MachineInstr &MI = *SU->getInstr(); 1574 SmallVector<const MachineOperand *, 4> BaseOps; 1575 int64_t Offset; 1576 bool OffsetIsScalable; 1577 unsigned Width; 1578 if (TII->getMemOperandsWithOffsetWidth(MI, BaseOps, Offset, 1579 OffsetIsScalable, Width, TRI)) { 1580 MemOpRecords.push_back(MemOpInfo(SU, BaseOps, Offset, Width)); 1581 1582 LLVM_DEBUG(dbgs() << "Num BaseOps: " << BaseOps.size() << ", Offset: " 1583 << Offset << ", OffsetIsScalable: " << OffsetIsScalable 1584 << ", Width: " << Width << "\n"); 1585 } 1586 #ifndef NDEBUG 1587 for (auto *Op : BaseOps) 1588 assert(Op); 1589 #endif 1590 } 1591 if (MemOpRecords.size() < 2) 1592 return; 1593 1594 llvm::sort(MemOpRecords); 1595 1596 // At this point, `MemOpRecords` array must hold atleast two mem ops. Try to 1597 // cluster mem ops collected within `MemOpRecords` array. 1598 unsigned ClusterLength = 1; 1599 unsigned CurrentClusterBytes = MemOpRecords[0].Width; 1600 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) { 1601 // Decision to cluster mem ops is taken based on target dependent logic 1602 auto MemOpa = MemOpRecords[Idx]; 1603 auto MemOpb = MemOpRecords[Idx + 1]; 1604 ++ClusterLength; 1605 CurrentClusterBytes += MemOpb.Width; 1606 if (!TII->shouldClusterMemOps(MemOpa.BaseOps, MemOpb.BaseOps, ClusterLength, 1607 CurrentClusterBytes)) { 1608 // Current mem ops pair could not be clustered, reset cluster length, and 1609 // go to next pair 1610 ClusterLength = 1; 1611 CurrentClusterBytes = MemOpb.Width; 1612 continue; 1613 } 1614 1615 SUnit *SUa = MemOpa.SU; 1616 SUnit *SUb = MemOpb.SU; 1617 if (SUa->NodeNum > SUb->NodeNum) 1618 std::swap(SUa, SUb); 1619 1620 // FIXME: Is this check really required? 1621 if (!DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) { 1622 ClusterLength = 1; 1623 CurrentClusterBytes = MemOpb.Width; 1624 continue; 1625 } 1626 1627 LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU(" 1628 << SUb->NodeNum << ")\n"); 1629 ++NumClustered; 1630 1631 if (IsLoad) { 1632 // Copy successor edges from SUa to SUb. Interleaving computation 1633 // dependent on SUa can prevent load combining due to register reuse. 1634 // Predecessor edges do not need to be copied from SUb to SUa since 1635 // nearby loads should have effectively the same inputs. 1636 for (const SDep &Succ : SUa->Succs) { 1637 if (Succ.getSUnit() == SUb) 1638 continue; 1639 LLVM_DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum 1640 << ")\n"); 1641 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial)); 1642 } 1643 } else { 1644 // Copy predecessor edges from SUb to SUa to avoid the SUnits that 1645 // SUb dependent on scheduled in-between SUb and SUa. Successor edges 1646 // do not need to be copied from SUa to SUb since no one will depend 1647 // on stores. 1648 // Notice that, we don't need to care about the memory dependency as 1649 // we won't try to cluster them if they have any memory dependency. 1650 for (const SDep &Pred : SUb->Preds) { 1651 if (Pred.getSUnit() == SUa) 1652 continue; 1653 LLVM_DEBUG(dbgs() << " Copy Pred SU(" << Pred.getSUnit()->NodeNum 1654 << ")\n"); 1655 DAG->addEdge(SUa, SDep(Pred.getSUnit(), SDep::Artificial)); 1656 } 1657 } 1658 1659 LLVM_DEBUG(dbgs() << " Curr cluster length: " << ClusterLength 1660 << ", Curr cluster bytes: " << CurrentClusterBytes 1661 << "\n"); 1662 } 1663 } 1664 1665 /// Callback from DAG postProcessing to create cluster edges for loads. 1666 void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAG) { 1667 // Map DAG NodeNum to a set of dependent MemOps in store chain. 1668 DenseMap<unsigned, SmallVector<SUnit *, 4>> StoreChains; 1669 for (SUnit &SU : DAG->SUnits) { 1670 if ((IsLoad && !SU.getInstr()->mayLoad()) || 1671 (!IsLoad && !SU.getInstr()->mayStore())) 1672 continue; 1673 1674 unsigned ChainPredID = DAG->SUnits.size(); 1675 for (const SDep &Pred : SU.Preds) { 1676 // We only want to cluster the mem ops that have the same ctrl(non-data) 1677 // pred so that they didn't have ctrl dependency for each other. But for 1678 // store instrs, we can still cluster them if the pred is load instr. 1679 if ((Pred.isCtrl() && 1680 (IsLoad || 1681 (Pred.getSUnit() && Pred.getSUnit()->getInstr()->mayStore()))) && 1682 !Pred.isArtificial()) { 1683 ChainPredID = Pred.getSUnit()->NodeNum; 1684 break; 1685 } 1686 } 1687 // Insert the SU to corresponding store chain. 1688 auto &Chain = StoreChains.FindAndConstruct(ChainPredID).second; 1689 Chain.push_back(&SU); 1690 } 1691 1692 // Iterate over the store chains. 1693 for (auto &SCD : StoreChains) 1694 clusterNeighboringMemOps(SCD.second, DAG); 1695 } 1696 1697 //===----------------------------------------------------------------------===// 1698 // CopyConstrain - DAG post-processing to encourage copy elimination. 1699 //===----------------------------------------------------------------------===// 1700 1701 namespace { 1702 1703 /// Post-process the DAG to create weak edges from all uses of a copy to 1704 /// the one use that defines the copy's source vreg, most likely an induction 1705 /// variable increment. 1706 class CopyConstrain : public ScheduleDAGMutation { 1707 // Transient state. 1708 SlotIndex RegionBeginIdx; 1709 1710 // RegionEndIdx is the slot index of the last non-debug instruction in the 1711 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx. 1712 SlotIndex RegionEndIdx; 1713 1714 public: 1715 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {} 1716 1717 void apply(ScheduleDAGInstrs *DAGInstrs) override; 1718 1719 protected: 1720 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG); 1721 }; 1722 1723 } // end anonymous namespace 1724 1725 namespace llvm { 1726 1727 std::unique_ptr<ScheduleDAGMutation> 1728 createCopyConstrainDAGMutation(const TargetInstrInfo *TII, 1729 const TargetRegisterInfo *TRI) { 1730 return std::make_unique<CopyConstrain>(TII, TRI); 1731 } 1732 1733 } // end namespace llvm 1734 1735 /// constrainLocalCopy handles two possibilities: 1736 /// 1) Local src: 1737 /// I0: = dst 1738 /// I1: src = ... 1739 /// I2: = dst 1740 /// I3: dst = src (copy) 1741 /// (create pred->succ edges I0->I1, I2->I1) 1742 /// 1743 /// 2) Local copy: 1744 /// I0: dst = src (copy) 1745 /// I1: = dst 1746 /// I2: src = ... 1747 /// I3: = dst 1748 /// (create pred->succ edges I1->I2, I3->I2) 1749 /// 1750 /// Although the MachineScheduler is currently constrained to single blocks, 1751 /// this algorithm should handle extended blocks. An EBB is a set of 1752 /// contiguously numbered blocks such that the previous block in the EBB is 1753 /// always the single predecessor. 1754 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) { 1755 LiveIntervals *LIS = DAG->getLIS(); 1756 MachineInstr *Copy = CopySU->getInstr(); 1757 1758 // Check for pure vreg copies. 1759 const MachineOperand &SrcOp = Copy->getOperand(1); 1760 Register SrcReg = SrcOp.getReg(); 1761 if (!Register::isVirtualRegister(SrcReg) || !SrcOp.readsReg()) 1762 return; 1763 1764 const MachineOperand &DstOp = Copy->getOperand(0); 1765 Register DstReg = DstOp.getReg(); 1766 if (!Register::isVirtualRegister(DstReg) || DstOp.isDead()) 1767 return; 1768 1769 // Check if either the dest or source is local. If it's live across a back 1770 // edge, it's not local. Note that if both vregs are live across the back 1771 // edge, we cannot successfully contrain the copy without cyclic scheduling. 1772 // If both the copy's source and dest are local live intervals, then we 1773 // should treat the dest as the global for the purpose of adding 1774 // constraints. This adds edges from source's other uses to the copy. 1775 unsigned LocalReg = SrcReg; 1776 unsigned GlobalReg = DstReg; 1777 LiveInterval *LocalLI = &LIS->getInterval(LocalReg); 1778 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) { 1779 LocalReg = DstReg; 1780 GlobalReg = SrcReg; 1781 LocalLI = &LIS->getInterval(LocalReg); 1782 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) 1783 return; 1784 } 1785 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg); 1786 1787 // Find the global segment after the start of the local LI. 1788 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex()); 1789 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a 1790 // local live range. We could create edges from other global uses to the local 1791 // start, but the coalescer should have already eliminated these cases, so 1792 // don't bother dealing with it. 1793 if (GlobalSegment == GlobalLI->end()) 1794 return; 1795 1796 // If GlobalSegment is killed at the LocalLI->start, the call to find() 1797 // returned the next global segment. But if GlobalSegment overlaps with 1798 // LocalLI->start, then advance to the next segment. If a hole in GlobalLI 1799 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole. 1800 if (GlobalSegment->contains(LocalLI->beginIndex())) 1801 ++GlobalSegment; 1802 1803 if (GlobalSegment == GlobalLI->end()) 1804 return; 1805 1806 // Check if GlobalLI contains a hole in the vicinity of LocalLI. 1807 if (GlobalSegment != GlobalLI->begin()) { 1808 // Two address defs have no hole. 1809 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end, 1810 GlobalSegment->start)) { 1811 return; 1812 } 1813 // If the prior global segment may be defined by the same two-address 1814 // instruction that also defines LocalLI, then can't make a hole here. 1815 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start, 1816 LocalLI->beginIndex())) { 1817 return; 1818 } 1819 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise 1820 // it would be a disconnected component in the live range. 1821 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() && 1822 "Disconnected LRG within the scheduling region."); 1823 } 1824 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start); 1825 if (!GlobalDef) 1826 return; 1827 1828 SUnit *GlobalSU = DAG->getSUnit(GlobalDef); 1829 if (!GlobalSU) 1830 return; 1831 1832 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by 1833 // constraining the uses of the last local def to precede GlobalDef. 1834 SmallVector<SUnit*,8> LocalUses; 1835 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex()); 1836 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def); 1837 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef); 1838 for (const SDep &Succ : LastLocalSU->Succs) { 1839 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg) 1840 continue; 1841 if (Succ.getSUnit() == GlobalSU) 1842 continue; 1843 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit())) 1844 return; 1845 LocalUses.push_back(Succ.getSUnit()); 1846 } 1847 // Open the top of the GlobalLI hole by constraining any earlier global uses 1848 // to precede the start of LocalLI. 1849 SmallVector<SUnit*,8> GlobalUses; 1850 MachineInstr *FirstLocalDef = 1851 LIS->getInstructionFromIndex(LocalLI->beginIndex()); 1852 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef); 1853 for (const SDep &Pred : GlobalSU->Preds) { 1854 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg) 1855 continue; 1856 if (Pred.getSUnit() == FirstLocalSU) 1857 continue; 1858 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit())) 1859 return; 1860 GlobalUses.push_back(Pred.getSUnit()); 1861 } 1862 LLVM_DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n"); 1863 // Add the weak edges. 1864 for (SmallVectorImpl<SUnit*>::const_iterator 1865 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) { 1866 LLVM_DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU(" 1867 << GlobalSU->NodeNum << ")\n"); 1868 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak)); 1869 } 1870 for (SmallVectorImpl<SUnit*>::const_iterator 1871 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) { 1872 LLVM_DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU(" 1873 << FirstLocalSU->NodeNum << ")\n"); 1874 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak)); 1875 } 1876 } 1877 1878 /// Callback from DAG postProcessing to create weak edges to encourage 1879 /// copy elimination. 1880 void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) { 1881 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs); 1882 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals"); 1883 1884 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end()); 1885 if (FirstPos == DAG->end()) 1886 return; 1887 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos); 1888 RegionEndIdx = DAG->getLIS()->getInstructionIndex( 1889 *priorNonDebug(DAG->end(), DAG->begin())); 1890 1891 for (SUnit &SU : DAG->SUnits) { 1892 if (!SU.getInstr()->isCopy()) 1893 continue; 1894 1895 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG)); 1896 } 1897 } 1898 1899 //===----------------------------------------------------------------------===// 1900 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler 1901 // and possibly other custom schedulers. 1902 //===----------------------------------------------------------------------===// 1903 1904 static const unsigned InvalidCycle = ~0U; 1905 1906 SchedBoundary::~SchedBoundary() { delete HazardRec; } 1907 1908 /// Given a Count of resource usage and a Latency value, return true if a 1909 /// SchedBoundary becomes resource limited. 1910 /// If we are checking after scheduling a node, we should return true when 1911 /// we just reach the resource limit. 1912 static bool checkResourceLimit(unsigned LFactor, unsigned Count, 1913 unsigned Latency, bool AfterSchedNode) { 1914 int ResCntFactor = (int)(Count - (Latency * LFactor)); 1915 if (AfterSchedNode) 1916 return ResCntFactor >= (int)LFactor; 1917 else 1918 return ResCntFactor > (int)LFactor; 1919 } 1920 1921 void SchedBoundary::reset() { 1922 // A new HazardRec is created for each DAG and owned by SchedBoundary. 1923 // Destroying and reconstructing it is very expensive though. So keep 1924 // invalid, placeholder HazardRecs. 1925 if (HazardRec && HazardRec->isEnabled()) { 1926 delete HazardRec; 1927 HazardRec = nullptr; 1928 } 1929 Available.clear(); 1930 Pending.clear(); 1931 CheckPending = false; 1932 CurrCycle = 0; 1933 CurrMOps = 0; 1934 MinReadyCycle = std::numeric_limits<unsigned>::max(); 1935 ExpectedLatency = 0; 1936 DependentLatency = 0; 1937 RetiredMOps = 0; 1938 MaxExecutedResCount = 0; 1939 ZoneCritResIdx = 0; 1940 IsResourceLimited = false; 1941 ReservedCycles.clear(); 1942 ReservedCyclesIndex.clear(); 1943 #ifndef NDEBUG 1944 // Track the maximum number of stall cycles that could arise either from the 1945 // latency of a DAG edge or the number of cycles that a processor resource is 1946 // reserved (SchedBoundary::ReservedCycles). 1947 MaxObservedStall = 0; 1948 #endif 1949 // Reserve a zero-count for invalid CritResIdx. 1950 ExecutedResCounts.resize(1); 1951 assert(!ExecutedResCounts[0] && "nonzero count for bad resource"); 1952 } 1953 1954 void SchedRemainder:: 1955 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) { 1956 reset(); 1957 if (!SchedModel->hasInstrSchedModel()) 1958 return; 1959 RemainingCounts.resize(SchedModel->getNumProcResourceKinds()); 1960 for (SUnit &SU : DAG->SUnits) { 1961 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU); 1962 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC) 1963 * SchedModel->getMicroOpFactor(); 1964 for (TargetSchedModel::ProcResIter 1965 PI = SchedModel->getWriteProcResBegin(SC), 1966 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 1967 unsigned PIdx = PI->ProcResourceIdx; 1968 unsigned Factor = SchedModel->getResourceFactor(PIdx); 1969 RemainingCounts[PIdx] += (Factor * PI->Cycles); 1970 } 1971 } 1972 } 1973 1974 void SchedBoundary:: 1975 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) { 1976 reset(); 1977 DAG = dag; 1978 SchedModel = smodel; 1979 Rem = rem; 1980 if (SchedModel->hasInstrSchedModel()) { 1981 unsigned ResourceCount = SchedModel->getNumProcResourceKinds(); 1982 ReservedCyclesIndex.resize(ResourceCount); 1983 ExecutedResCounts.resize(ResourceCount); 1984 unsigned NumUnits = 0; 1985 1986 for (unsigned i = 0; i < ResourceCount; ++i) { 1987 ReservedCyclesIndex[i] = NumUnits; 1988 NumUnits += SchedModel->getProcResource(i)->NumUnits; 1989 } 1990 1991 ReservedCycles.resize(NumUnits, InvalidCycle); 1992 } 1993 } 1994 1995 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat 1996 /// these "soft stalls" differently than the hard stall cycles based on CPU 1997 /// resources and computed by checkHazard(). A fully in-order model 1998 /// (MicroOpBufferSize==0) will not make use of this since instructions are not 1999 /// available for scheduling until they are ready. However, a weaker in-order 2000 /// model may use this for heuristics. For example, if a processor has in-order 2001 /// behavior when reading certain resources, this may come into play. 2002 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) { 2003 if (!SU->isUnbuffered) 2004 return 0; 2005 2006 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle); 2007 if (ReadyCycle > CurrCycle) 2008 return ReadyCycle - CurrCycle; 2009 return 0; 2010 } 2011 2012 /// Compute the next cycle at which the given processor resource unit 2013 /// can be scheduled. 2014 unsigned SchedBoundary::getNextResourceCycleByInstance(unsigned InstanceIdx, 2015 unsigned Cycles) { 2016 unsigned NextUnreserved = ReservedCycles[InstanceIdx]; 2017 // If this resource has never been used, always return cycle zero. 2018 if (NextUnreserved == InvalidCycle) 2019 return 0; 2020 // For bottom-up scheduling add the cycles needed for the current operation. 2021 if (!isTop()) 2022 NextUnreserved += Cycles; 2023 return NextUnreserved; 2024 } 2025 2026 /// Compute the next cycle at which the given processor resource can be 2027 /// scheduled. Returns the next cycle and the index of the processor resource 2028 /// instance in the reserved cycles vector. 2029 std::pair<unsigned, unsigned> 2030 SchedBoundary::getNextResourceCycle(unsigned PIdx, unsigned Cycles) { 2031 unsigned MinNextUnreserved = InvalidCycle; 2032 unsigned InstanceIdx = 0; 2033 unsigned StartIndex = ReservedCyclesIndex[PIdx]; 2034 unsigned NumberOfInstances = SchedModel->getProcResource(PIdx)->NumUnits; 2035 assert(NumberOfInstances > 0 && 2036 "Cannot have zero instances of a ProcResource"); 2037 2038 for (unsigned I = StartIndex, End = StartIndex + NumberOfInstances; I < End; 2039 ++I) { 2040 unsigned NextUnreserved = getNextResourceCycleByInstance(I, Cycles); 2041 if (MinNextUnreserved > NextUnreserved) { 2042 InstanceIdx = I; 2043 MinNextUnreserved = NextUnreserved; 2044 } 2045 } 2046 return std::make_pair(MinNextUnreserved, InstanceIdx); 2047 } 2048 2049 /// Does this SU have a hazard within the current instruction group. 2050 /// 2051 /// The scheduler supports two modes of hazard recognition. The first is the 2052 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that 2053 /// supports highly complicated in-order reservation tables 2054 /// (ScoreboardHazardRecognizer) and arbitrary target-specific logic. 2055 /// 2056 /// The second is a streamlined mechanism that checks for hazards based on 2057 /// simple counters that the scheduler itself maintains. It explicitly checks 2058 /// for instruction dispatch limitations, including the number of micro-ops that 2059 /// can dispatch per cycle. 2060 /// 2061 /// TODO: Also check whether the SU must start a new group. 2062 bool SchedBoundary::checkHazard(SUnit *SU) { 2063 if (HazardRec->isEnabled() 2064 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) { 2065 return true; 2066 } 2067 2068 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr()); 2069 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) { 2070 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops=" 2071 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n'); 2072 return true; 2073 } 2074 2075 if (CurrMOps > 0 && 2076 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) || 2077 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) { 2078 LLVM_DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must " 2079 << (isTop() ? "begin" : "end") << " group\n"); 2080 return true; 2081 } 2082 2083 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) { 2084 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 2085 for (const MCWriteProcResEntry &PE : 2086 make_range(SchedModel->getWriteProcResBegin(SC), 2087 SchedModel->getWriteProcResEnd(SC))) { 2088 unsigned ResIdx = PE.ProcResourceIdx; 2089 unsigned Cycles = PE.Cycles; 2090 unsigned NRCycle, InstanceIdx; 2091 std::tie(NRCycle, InstanceIdx) = getNextResourceCycle(ResIdx, Cycles); 2092 if (NRCycle > CurrCycle) { 2093 #ifndef NDEBUG 2094 MaxObservedStall = std::max(Cycles, MaxObservedStall); 2095 #endif 2096 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") " 2097 << SchedModel->getResourceName(ResIdx) 2098 << '[' << InstanceIdx - ReservedCyclesIndex[ResIdx] << ']' 2099 << "=" << NRCycle << "c\n"); 2100 return true; 2101 } 2102 } 2103 } 2104 return false; 2105 } 2106 2107 // Find the unscheduled node in ReadySUs with the highest latency. 2108 unsigned SchedBoundary:: 2109 findMaxLatency(ArrayRef<SUnit*> ReadySUs) { 2110 SUnit *LateSU = nullptr; 2111 unsigned RemLatency = 0; 2112 for (SUnit *SU : ReadySUs) { 2113 unsigned L = getUnscheduledLatency(SU); 2114 if (L > RemLatency) { 2115 RemLatency = L; 2116 LateSU = SU; 2117 } 2118 } 2119 if (LateSU) { 2120 LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU(" 2121 << LateSU->NodeNum << ") " << RemLatency << "c\n"); 2122 } 2123 return RemLatency; 2124 } 2125 2126 // Count resources in this zone and the remaining unscheduled 2127 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical 2128 // resource index, or zero if the zone is issue limited. 2129 unsigned SchedBoundary:: 2130 getOtherResourceCount(unsigned &OtherCritIdx) { 2131 OtherCritIdx = 0; 2132 if (!SchedModel->hasInstrSchedModel()) 2133 return 0; 2134 2135 unsigned OtherCritCount = Rem->RemIssueCount 2136 + (RetiredMOps * SchedModel->getMicroOpFactor()); 2137 LLVM_DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: " 2138 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n'); 2139 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds(); 2140 PIdx != PEnd; ++PIdx) { 2141 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx]; 2142 if (OtherCount > OtherCritCount) { 2143 OtherCritCount = OtherCount; 2144 OtherCritIdx = PIdx; 2145 } 2146 } 2147 if (OtherCritIdx) { 2148 LLVM_DEBUG( 2149 dbgs() << " " << Available.getName() << " + Remain CritRes: " 2150 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx) 2151 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n"); 2152 } 2153 return OtherCritCount; 2154 } 2155 2156 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle, bool InPQueue, 2157 unsigned Idx) { 2158 assert(SU->getInstr() && "Scheduled SUnit must have instr"); 2159 2160 #ifndef NDEBUG 2161 // ReadyCycle was been bumped up to the CurrCycle when this node was 2162 // scheduled, but CurrCycle may have been eagerly advanced immediately after 2163 // scheduling, so may now be greater than ReadyCycle. 2164 if (ReadyCycle > CurrCycle) 2165 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall); 2166 #endif 2167 2168 if (ReadyCycle < MinReadyCycle) 2169 MinReadyCycle = ReadyCycle; 2170 2171 // Check for interlocks first. For the purpose of other heuristics, an 2172 // instruction that cannot issue appears as if it's not in the ReadyQueue. 2173 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0; 2174 bool HazardDetected = (!IsBuffered && ReadyCycle > CurrCycle) || 2175 checkHazard(SU) || (Available.size() >= ReadyListLimit); 2176 2177 if (!HazardDetected) { 2178 Available.push(SU); 2179 2180 if (InPQueue) 2181 Pending.remove(Pending.begin() + Idx); 2182 return; 2183 } 2184 2185 if (!InPQueue) 2186 Pending.push(SU); 2187 } 2188 2189 /// Move the boundary of scheduled code by one cycle. 2190 void SchedBoundary::bumpCycle(unsigned NextCycle) { 2191 if (SchedModel->getMicroOpBufferSize() == 0) { 2192 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() && 2193 "MinReadyCycle uninitialized"); 2194 if (MinReadyCycle > NextCycle) 2195 NextCycle = MinReadyCycle; 2196 } 2197 // Update the current micro-ops, which will issue in the next cycle. 2198 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle); 2199 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps; 2200 2201 // Decrement DependentLatency based on the next cycle. 2202 if ((NextCycle - CurrCycle) > DependentLatency) 2203 DependentLatency = 0; 2204 else 2205 DependentLatency -= (NextCycle - CurrCycle); 2206 2207 if (!HazardRec->isEnabled()) { 2208 // Bypass HazardRec virtual calls. 2209 CurrCycle = NextCycle; 2210 } else { 2211 // Bypass getHazardType calls in case of long latency. 2212 for (; CurrCycle != NextCycle; ++CurrCycle) { 2213 if (isTop()) 2214 HazardRec->AdvanceCycle(); 2215 else 2216 HazardRec->RecedeCycle(); 2217 } 2218 } 2219 CheckPending = true; 2220 IsResourceLimited = 2221 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(), 2222 getScheduledLatency(), true); 2223 2224 LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() 2225 << '\n'); 2226 } 2227 2228 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) { 2229 ExecutedResCounts[PIdx] += Count; 2230 if (ExecutedResCounts[PIdx] > MaxExecutedResCount) 2231 MaxExecutedResCount = ExecutedResCounts[PIdx]; 2232 } 2233 2234 /// Add the given processor resource to this scheduled zone. 2235 /// 2236 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles 2237 /// during which this resource is consumed. 2238 /// 2239 /// \return the next cycle at which the instruction may execute without 2240 /// oversubscribing resources. 2241 unsigned SchedBoundary:: 2242 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) { 2243 unsigned Factor = SchedModel->getResourceFactor(PIdx); 2244 unsigned Count = Factor * Cycles; 2245 LLVM_DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx) << " +" 2246 << Cycles << "x" << Factor << "u\n"); 2247 2248 // Update Executed resources counts. 2249 incExecutedResources(PIdx, Count); 2250 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted"); 2251 Rem->RemainingCounts[PIdx] -= Count; 2252 2253 // Check if this resource exceeds the current critical resource. If so, it 2254 // becomes the critical resource. 2255 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) { 2256 ZoneCritResIdx = PIdx; 2257 LLVM_DEBUG(dbgs() << " *** Critical resource " 2258 << SchedModel->getResourceName(PIdx) << ": " 2259 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() 2260 << "c\n"); 2261 } 2262 // For reserved resources, record the highest cycle using the resource. 2263 unsigned NextAvailable, InstanceIdx; 2264 std::tie(NextAvailable, InstanceIdx) = getNextResourceCycle(PIdx, Cycles); 2265 if (NextAvailable > CurrCycle) { 2266 LLVM_DEBUG(dbgs() << " Resource conflict: " 2267 << SchedModel->getResourceName(PIdx) 2268 << '[' << InstanceIdx - ReservedCyclesIndex[PIdx] << ']' 2269 << " reserved until @" << NextAvailable << "\n"); 2270 } 2271 return NextAvailable; 2272 } 2273 2274 /// Move the boundary of scheduled code by one SUnit. 2275 void SchedBoundary::bumpNode(SUnit *SU) { 2276 // Update the reservation table. 2277 if (HazardRec->isEnabled()) { 2278 if (!isTop() && SU->isCall) { 2279 // Calls are scheduled with their preceding instructions. For bottom-up 2280 // scheduling, clear the pipeline state before emitting. 2281 HazardRec->Reset(); 2282 } 2283 HazardRec->EmitInstruction(SU); 2284 // Scheduling an instruction may have made pending instructions available. 2285 CheckPending = true; 2286 } 2287 // checkHazard should prevent scheduling multiple instructions per cycle that 2288 // exceed the issue width. 2289 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 2290 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr()); 2291 assert( 2292 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) && 2293 "Cannot schedule this instruction's MicroOps in the current cycle."); 2294 2295 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle); 2296 LLVM_DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n"); 2297 2298 unsigned NextCycle = CurrCycle; 2299 switch (SchedModel->getMicroOpBufferSize()) { 2300 case 0: 2301 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue"); 2302 break; 2303 case 1: 2304 if (ReadyCycle > NextCycle) { 2305 NextCycle = ReadyCycle; 2306 LLVM_DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n"); 2307 } 2308 break; 2309 default: 2310 // We don't currently model the OOO reorder buffer, so consider all 2311 // scheduled MOps to be "retired". We do loosely model in-order resource 2312 // latency. If this instruction uses an in-order resource, account for any 2313 // likely stall cycles. 2314 if (SU->isUnbuffered && ReadyCycle > NextCycle) 2315 NextCycle = ReadyCycle; 2316 break; 2317 } 2318 RetiredMOps += IncMOps; 2319 2320 // Update resource counts and critical resource. 2321 if (SchedModel->hasInstrSchedModel()) { 2322 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor(); 2323 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted"); 2324 Rem->RemIssueCount -= DecRemIssue; 2325 if (ZoneCritResIdx) { 2326 // Scale scheduled micro-ops for comparing with the critical resource. 2327 unsigned ScaledMOps = 2328 RetiredMOps * SchedModel->getMicroOpFactor(); 2329 2330 // If scaled micro-ops are now more than the previous critical resource by 2331 // a full cycle, then micro-ops issue becomes critical. 2332 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx)) 2333 >= (int)SchedModel->getLatencyFactor()) { 2334 ZoneCritResIdx = 0; 2335 LLVM_DEBUG(dbgs() << " *** Critical resource NumMicroOps: " 2336 << ScaledMOps / SchedModel->getLatencyFactor() 2337 << "c\n"); 2338 } 2339 } 2340 for (TargetSchedModel::ProcResIter 2341 PI = SchedModel->getWriteProcResBegin(SC), 2342 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 2343 unsigned RCycle = 2344 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle); 2345 if (RCycle > NextCycle) 2346 NextCycle = RCycle; 2347 } 2348 if (SU->hasReservedResource) { 2349 // For reserved resources, record the highest cycle using the resource. 2350 // For top-down scheduling, this is the cycle in which we schedule this 2351 // instruction plus the number of cycles the operations reserves the 2352 // resource. For bottom-up is it simply the instruction's cycle. 2353 for (TargetSchedModel::ProcResIter 2354 PI = SchedModel->getWriteProcResBegin(SC), 2355 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 2356 unsigned PIdx = PI->ProcResourceIdx; 2357 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) { 2358 unsigned ReservedUntil, InstanceIdx; 2359 std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(PIdx, 0); 2360 if (isTop()) { 2361 ReservedCycles[InstanceIdx] = 2362 std::max(ReservedUntil, NextCycle + PI->Cycles); 2363 } else 2364 ReservedCycles[InstanceIdx] = NextCycle; 2365 } 2366 } 2367 } 2368 } 2369 // Update ExpectedLatency and DependentLatency. 2370 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency; 2371 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency; 2372 if (SU->getDepth() > TopLatency) { 2373 TopLatency = SU->getDepth(); 2374 LLVM_DEBUG(dbgs() << " " << Available.getName() << " TopLatency SU(" 2375 << SU->NodeNum << ") " << TopLatency << "c\n"); 2376 } 2377 if (SU->getHeight() > BotLatency) { 2378 BotLatency = SU->getHeight(); 2379 LLVM_DEBUG(dbgs() << " " << Available.getName() << " BotLatency SU(" 2380 << SU->NodeNum << ") " << BotLatency << "c\n"); 2381 } 2382 // If we stall for any reason, bump the cycle. 2383 if (NextCycle > CurrCycle) 2384 bumpCycle(NextCycle); 2385 else 2386 // After updating ZoneCritResIdx and ExpectedLatency, check if we're 2387 // resource limited. If a stall occurred, bumpCycle does this. 2388 IsResourceLimited = 2389 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(), 2390 getScheduledLatency(), true); 2391 2392 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle 2393 // resets CurrMOps. Loop to handle instructions with more MOps than issue in 2394 // one cycle. Since we commonly reach the max MOps here, opportunistically 2395 // bump the cycle to avoid uselessly checking everything in the readyQ. 2396 CurrMOps += IncMOps; 2397 2398 // Bump the cycle count for issue group constraints. 2399 // This must be done after NextCycle has been adjust for all other stalls. 2400 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set 2401 // currCycle to X. 2402 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) || 2403 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) { 2404 LLVM_DEBUG(dbgs() << " Bump cycle to " << (isTop() ? "end" : "begin") 2405 << " group\n"); 2406 bumpCycle(++NextCycle); 2407 } 2408 2409 while (CurrMOps >= SchedModel->getIssueWidth()) { 2410 LLVM_DEBUG(dbgs() << " *** Max MOps " << CurrMOps << " at cycle " 2411 << CurrCycle << '\n'); 2412 bumpCycle(++NextCycle); 2413 } 2414 LLVM_DEBUG(dumpScheduledState()); 2415 } 2416 2417 /// Release pending ready nodes in to the available queue. This makes them 2418 /// visible to heuristics. 2419 void SchedBoundary::releasePending() { 2420 // If the available queue is empty, it is safe to reset MinReadyCycle. 2421 if (Available.empty()) 2422 MinReadyCycle = std::numeric_limits<unsigned>::max(); 2423 2424 // Check to see if any of the pending instructions are ready to issue. If 2425 // so, add them to the available queue. 2426 for (unsigned I = 0, E = Pending.size(); I < E; ++I) { 2427 SUnit *SU = *(Pending.begin() + I); 2428 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle; 2429 2430 if (ReadyCycle < MinReadyCycle) 2431 MinReadyCycle = ReadyCycle; 2432 2433 if (Available.size() >= ReadyListLimit) 2434 break; 2435 2436 releaseNode(SU, ReadyCycle, true, I); 2437 if (E != Pending.size()) { 2438 --I; 2439 --E; 2440 } 2441 } 2442 CheckPending = false; 2443 } 2444 2445 /// Remove SU from the ready set for this boundary. 2446 void SchedBoundary::removeReady(SUnit *SU) { 2447 if (Available.isInQueue(SU)) 2448 Available.remove(Available.find(SU)); 2449 else { 2450 assert(Pending.isInQueue(SU) && "bad ready count"); 2451 Pending.remove(Pending.find(SU)); 2452 } 2453 } 2454 2455 /// If this queue only has one ready candidate, return it. As a side effect, 2456 /// defer any nodes that now hit a hazard, and advance the cycle until at least 2457 /// one node is ready. If multiple instructions are ready, return NULL. 2458 SUnit *SchedBoundary::pickOnlyChoice() { 2459 if (CheckPending) 2460 releasePending(); 2461 2462 // Defer any ready instrs that now have a hazard. 2463 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) { 2464 if (checkHazard(*I)) { 2465 Pending.push(*I); 2466 I = Available.remove(I); 2467 continue; 2468 } 2469 ++I; 2470 } 2471 for (unsigned i = 0; Available.empty(); ++i) { 2472 // FIXME: Re-enable assert once PR20057 is resolved. 2473 // assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) && 2474 // "permanent hazard"); 2475 (void)i; 2476 bumpCycle(CurrCycle + 1); 2477 releasePending(); 2478 } 2479 2480 LLVM_DEBUG(Pending.dump()); 2481 LLVM_DEBUG(Available.dump()); 2482 2483 if (Available.size() == 1) 2484 return *Available.begin(); 2485 return nullptr; 2486 } 2487 2488 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2489 // This is useful information to dump after bumpNode. 2490 // Note that the Queue contents are more useful before pickNodeFromQueue. 2491 LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const { 2492 unsigned ResFactor; 2493 unsigned ResCount; 2494 if (ZoneCritResIdx) { 2495 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx); 2496 ResCount = getResourceCount(ZoneCritResIdx); 2497 } else { 2498 ResFactor = SchedModel->getMicroOpFactor(); 2499 ResCount = RetiredMOps * ResFactor; 2500 } 2501 unsigned LFactor = SchedModel->getLatencyFactor(); 2502 dbgs() << Available.getName() << " @" << CurrCycle << "c\n" 2503 << " Retired: " << RetiredMOps; 2504 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c"; 2505 dbgs() << "\n Critical: " << ResCount / LFactor << "c, " 2506 << ResCount / ResFactor << " " 2507 << SchedModel->getResourceName(ZoneCritResIdx) 2508 << "\n ExpectedLatency: " << ExpectedLatency << "c\n" 2509 << (IsResourceLimited ? " - Resource" : " - Latency") 2510 << " limited.\n"; 2511 } 2512 #endif 2513 2514 //===----------------------------------------------------------------------===// 2515 // GenericScheduler - Generic implementation of MachineSchedStrategy. 2516 //===----------------------------------------------------------------------===// 2517 2518 void GenericSchedulerBase::SchedCandidate:: 2519 initResourceDelta(const ScheduleDAGMI *DAG, 2520 const TargetSchedModel *SchedModel) { 2521 if (!Policy.ReduceResIdx && !Policy.DemandResIdx) 2522 return; 2523 2524 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 2525 for (TargetSchedModel::ProcResIter 2526 PI = SchedModel->getWriteProcResBegin(SC), 2527 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 2528 if (PI->ProcResourceIdx == Policy.ReduceResIdx) 2529 ResDelta.CritResources += PI->Cycles; 2530 if (PI->ProcResourceIdx == Policy.DemandResIdx) 2531 ResDelta.DemandedResources += PI->Cycles; 2532 } 2533 } 2534 2535 /// Compute remaining latency. We need this both to determine whether the 2536 /// overall schedule has become latency-limited and whether the instructions 2537 /// outside this zone are resource or latency limited. 2538 /// 2539 /// The "dependent" latency is updated incrementally during scheduling as the 2540 /// max height/depth of scheduled nodes minus the cycles since it was 2541 /// scheduled: 2542 /// DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone 2543 /// 2544 /// The "independent" latency is the max ready queue depth: 2545 /// ILat = max N.depth for N in Available|Pending 2546 /// 2547 /// RemainingLatency is the greater of independent and dependent latency. 2548 /// 2549 /// These computations are expensive, especially in DAGs with many edges, so 2550 /// only do them if necessary. 2551 static unsigned computeRemLatency(SchedBoundary &CurrZone) { 2552 unsigned RemLatency = CurrZone.getDependentLatency(); 2553 RemLatency = std::max(RemLatency, 2554 CurrZone.findMaxLatency(CurrZone.Available.elements())); 2555 RemLatency = std::max(RemLatency, 2556 CurrZone.findMaxLatency(CurrZone.Pending.elements())); 2557 return RemLatency; 2558 } 2559 2560 /// Returns true if the current cycle plus remaning latency is greater than 2561 /// the critical path in the scheduling region. 2562 bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy, 2563 SchedBoundary &CurrZone, 2564 bool ComputeRemLatency, 2565 unsigned &RemLatency) const { 2566 // The current cycle is already greater than the critical path, so we are 2567 // already latency limited and don't need to compute the remaining latency. 2568 if (CurrZone.getCurrCycle() > Rem.CriticalPath) 2569 return true; 2570 2571 // If we haven't scheduled anything yet, then we aren't latency limited. 2572 if (CurrZone.getCurrCycle() == 0) 2573 return false; 2574 2575 if (ComputeRemLatency) 2576 RemLatency = computeRemLatency(CurrZone); 2577 2578 return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath; 2579 } 2580 2581 /// Set the CandPolicy given a scheduling zone given the current resources and 2582 /// latencies inside and outside the zone. 2583 void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA, 2584 SchedBoundary &CurrZone, 2585 SchedBoundary *OtherZone) { 2586 // Apply preemptive heuristics based on the total latency and resources 2587 // inside and outside this zone. Potential stalls should be considered before 2588 // following this policy. 2589 2590 // Compute the critical resource outside the zone. 2591 unsigned OtherCritIdx = 0; 2592 unsigned OtherCount = 2593 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0; 2594 2595 bool OtherResLimited = false; 2596 unsigned RemLatency = 0; 2597 bool RemLatencyComputed = false; 2598 if (SchedModel->hasInstrSchedModel() && OtherCount != 0) { 2599 RemLatency = computeRemLatency(CurrZone); 2600 RemLatencyComputed = true; 2601 OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(), 2602 OtherCount, RemLatency, false); 2603 } 2604 2605 // Schedule aggressively for latency in PostRA mode. We don't check for 2606 // acyclic latency during PostRA, and highly out-of-order processors will 2607 // skip PostRA scheduling. 2608 if (!OtherResLimited && 2609 (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed, 2610 RemLatency))) { 2611 Policy.ReduceLatency |= true; 2612 LLVM_DEBUG(dbgs() << " " << CurrZone.Available.getName() 2613 << " RemainingLatency " << RemLatency << " + " 2614 << CurrZone.getCurrCycle() << "c > CritPath " 2615 << Rem.CriticalPath << "\n"); 2616 } 2617 // If the same resource is limiting inside and outside the zone, do nothing. 2618 if (CurrZone.getZoneCritResIdx() == OtherCritIdx) 2619 return; 2620 2621 LLVM_DEBUG(if (CurrZone.isResourceLimited()) { 2622 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: " 2623 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n"; 2624 } if (OtherResLimited) dbgs() 2625 << " RemainingLimit: " 2626 << SchedModel->getResourceName(OtherCritIdx) << "\n"; 2627 if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs() 2628 << " Latency limited both directions.\n"); 2629 2630 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx) 2631 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx(); 2632 2633 if (OtherResLimited) 2634 Policy.DemandResIdx = OtherCritIdx; 2635 } 2636 2637 #ifndef NDEBUG 2638 const char *GenericSchedulerBase::getReasonStr( 2639 GenericSchedulerBase::CandReason Reason) { 2640 switch (Reason) { 2641 case NoCand: return "NOCAND "; 2642 case Only1: return "ONLY1 "; 2643 case PhysReg: return "PHYS-REG "; 2644 case RegExcess: return "REG-EXCESS"; 2645 case RegCritical: return "REG-CRIT "; 2646 case Stall: return "STALL "; 2647 case Cluster: return "CLUSTER "; 2648 case Weak: return "WEAK "; 2649 case RegMax: return "REG-MAX "; 2650 case ResourceReduce: return "RES-REDUCE"; 2651 case ResourceDemand: return "RES-DEMAND"; 2652 case TopDepthReduce: return "TOP-DEPTH "; 2653 case TopPathReduce: return "TOP-PATH "; 2654 case BotHeightReduce:return "BOT-HEIGHT"; 2655 case BotPathReduce: return "BOT-PATH "; 2656 case NextDefUse: return "DEF-USE "; 2657 case NodeOrder: return "ORDER "; 2658 }; 2659 llvm_unreachable("Unknown reason!"); 2660 } 2661 2662 void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) { 2663 PressureChange P; 2664 unsigned ResIdx = 0; 2665 unsigned Latency = 0; 2666 switch (Cand.Reason) { 2667 default: 2668 break; 2669 case RegExcess: 2670 P = Cand.RPDelta.Excess; 2671 break; 2672 case RegCritical: 2673 P = Cand.RPDelta.CriticalMax; 2674 break; 2675 case RegMax: 2676 P = Cand.RPDelta.CurrentMax; 2677 break; 2678 case ResourceReduce: 2679 ResIdx = Cand.Policy.ReduceResIdx; 2680 break; 2681 case ResourceDemand: 2682 ResIdx = Cand.Policy.DemandResIdx; 2683 break; 2684 case TopDepthReduce: 2685 Latency = Cand.SU->getDepth(); 2686 break; 2687 case TopPathReduce: 2688 Latency = Cand.SU->getHeight(); 2689 break; 2690 case BotHeightReduce: 2691 Latency = Cand.SU->getHeight(); 2692 break; 2693 case BotPathReduce: 2694 Latency = Cand.SU->getDepth(); 2695 break; 2696 } 2697 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason); 2698 if (P.isValid()) 2699 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet()) 2700 << ":" << P.getUnitInc() << " "; 2701 else 2702 dbgs() << " "; 2703 if (ResIdx) 2704 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " "; 2705 else 2706 dbgs() << " "; 2707 if (Latency) 2708 dbgs() << " " << Latency << " cycles "; 2709 else 2710 dbgs() << " "; 2711 dbgs() << '\n'; 2712 } 2713 #endif 2714 2715 namespace llvm { 2716 /// Return true if this heuristic determines order. 2717 bool tryLess(int TryVal, int CandVal, 2718 GenericSchedulerBase::SchedCandidate &TryCand, 2719 GenericSchedulerBase::SchedCandidate &Cand, 2720 GenericSchedulerBase::CandReason Reason) { 2721 if (TryVal < CandVal) { 2722 TryCand.Reason = Reason; 2723 return true; 2724 } 2725 if (TryVal > CandVal) { 2726 if (Cand.Reason > Reason) 2727 Cand.Reason = Reason; 2728 return true; 2729 } 2730 return false; 2731 } 2732 2733 bool tryGreater(int TryVal, int CandVal, 2734 GenericSchedulerBase::SchedCandidate &TryCand, 2735 GenericSchedulerBase::SchedCandidate &Cand, 2736 GenericSchedulerBase::CandReason Reason) { 2737 if (TryVal > CandVal) { 2738 TryCand.Reason = Reason; 2739 return true; 2740 } 2741 if (TryVal < CandVal) { 2742 if (Cand.Reason > Reason) 2743 Cand.Reason = Reason; 2744 return true; 2745 } 2746 return false; 2747 } 2748 2749 bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, 2750 GenericSchedulerBase::SchedCandidate &Cand, 2751 SchedBoundary &Zone) { 2752 if (Zone.isTop()) { 2753 // Prefer the candidate with the lesser depth, but only if one of them has 2754 // depth greater than the total latency scheduled so far, otherwise either 2755 // of them could be scheduled now with no stall. 2756 if (std::max(TryCand.SU->getDepth(), Cand.SU->getDepth()) > 2757 Zone.getScheduledLatency()) { 2758 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(), 2759 TryCand, Cand, GenericSchedulerBase::TopDepthReduce)) 2760 return true; 2761 } 2762 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(), 2763 TryCand, Cand, GenericSchedulerBase::TopPathReduce)) 2764 return true; 2765 } else { 2766 // Prefer the candidate with the lesser height, but only if one of them has 2767 // height greater than the total latency scheduled so far, otherwise either 2768 // of them could be scheduled now with no stall. 2769 if (std::max(TryCand.SU->getHeight(), Cand.SU->getHeight()) > 2770 Zone.getScheduledLatency()) { 2771 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(), 2772 TryCand, Cand, GenericSchedulerBase::BotHeightReduce)) 2773 return true; 2774 } 2775 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(), 2776 TryCand, Cand, GenericSchedulerBase::BotPathReduce)) 2777 return true; 2778 } 2779 return false; 2780 } 2781 } // end namespace llvm 2782 2783 static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) { 2784 LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ") 2785 << GenericSchedulerBase::getReasonStr(Reason) << '\n'); 2786 } 2787 2788 static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) { 2789 tracePick(Cand.Reason, Cand.AtTop); 2790 } 2791 2792 void GenericScheduler::initialize(ScheduleDAGMI *dag) { 2793 assert(dag->hasVRegLiveness() && 2794 "(PreRA)GenericScheduler needs vreg liveness"); 2795 DAG = static_cast<ScheduleDAGMILive*>(dag); 2796 SchedModel = DAG->getSchedModel(); 2797 TRI = DAG->TRI; 2798 2799 if (RegionPolicy.ComputeDFSResult) 2800 DAG->computeDFSResult(); 2801 2802 Rem.init(DAG, SchedModel); 2803 Top.init(DAG, SchedModel, &Rem); 2804 Bot.init(DAG, SchedModel, &Rem); 2805 2806 // Initialize resource counts. 2807 2808 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or 2809 // are disabled, then these HazardRecs will be disabled. 2810 const InstrItineraryData *Itin = SchedModel->getInstrItineraries(); 2811 if (!Top.HazardRec) { 2812 Top.HazardRec = 2813 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer( 2814 Itin, DAG); 2815 } 2816 if (!Bot.HazardRec) { 2817 Bot.HazardRec = 2818 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer( 2819 Itin, DAG); 2820 } 2821 TopCand.SU = nullptr; 2822 BotCand.SU = nullptr; 2823 } 2824 2825 /// Initialize the per-region scheduling policy. 2826 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin, 2827 MachineBasicBlock::iterator End, 2828 unsigned NumRegionInstrs) { 2829 const MachineFunction &MF = *Begin->getMF(); 2830 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering(); 2831 2832 // Avoid setting up the register pressure tracker for small regions to save 2833 // compile time. As a rough heuristic, only track pressure when the number of 2834 // schedulable instructions exceeds half the integer register file. 2835 RegionPolicy.ShouldTrackPressure = true; 2836 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) { 2837 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT; 2838 if (TLI->isTypeLegal(LegalIntVT)) { 2839 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs( 2840 TLI->getRegClassFor(LegalIntVT)); 2841 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2); 2842 } 2843 } 2844 2845 // For generic targets, we default to bottom-up, because it's simpler and more 2846 // compile-time optimizations have been implemented in that direction. 2847 RegionPolicy.OnlyBottomUp = true; 2848 2849 // Allow the subtarget to override default policy. 2850 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs); 2851 2852 // After subtarget overrides, apply command line options. 2853 if (!EnableRegPressure) { 2854 RegionPolicy.ShouldTrackPressure = false; 2855 RegionPolicy.ShouldTrackLaneMasks = false; 2856 } 2857 2858 // Check -misched-topdown/bottomup can force or unforce scheduling direction. 2859 // e.g. -misched-bottomup=false allows scheduling in both directions. 2860 assert((!ForceTopDown || !ForceBottomUp) && 2861 "-misched-topdown incompatible with -misched-bottomup"); 2862 if (ForceBottomUp.getNumOccurrences() > 0) { 2863 RegionPolicy.OnlyBottomUp = ForceBottomUp; 2864 if (RegionPolicy.OnlyBottomUp) 2865 RegionPolicy.OnlyTopDown = false; 2866 } 2867 if (ForceTopDown.getNumOccurrences() > 0) { 2868 RegionPolicy.OnlyTopDown = ForceTopDown; 2869 if (RegionPolicy.OnlyTopDown) 2870 RegionPolicy.OnlyBottomUp = false; 2871 } 2872 } 2873 2874 void GenericScheduler::dumpPolicy() const { 2875 // Cannot completely remove virtual function even in release mode. 2876 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2877 dbgs() << "GenericScheduler RegionPolicy: " 2878 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure 2879 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown 2880 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp 2881 << "\n"; 2882 #endif 2883 } 2884 2885 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic 2886 /// critical path by more cycles than it takes to drain the instruction buffer. 2887 /// We estimate an upper bounds on in-flight instructions as: 2888 /// 2889 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height ) 2890 /// InFlightIterations = AcyclicPath / CyclesPerIteration 2891 /// InFlightResources = InFlightIterations * LoopResources 2892 /// 2893 /// TODO: Check execution resources in addition to IssueCount. 2894 void GenericScheduler::checkAcyclicLatency() { 2895 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath) 2896 return; 2897 2898 // Scaled number of cycles per loop iteration. 2899 unsigned IterCount = 2900 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(), 2901 Rem.RemIssueCount); 2902 // Scaled acyclic critical path. 2903 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor(); 2904 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop 2905 unsigned InFlightCount = 2906 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount; 2907 unsigned BufferLimit = 2908 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor(); 2909 2910 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit; 2911 2912 LLVM_DEBUG( 2913 dbgs() << "IssueCycles=" 2914 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c " 2915 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor() 2916 << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount 2917 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor() 2918 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n"; 2919 if (Rem.IsAcyclicLatencyLimited) dbgs() << " ACYCLIC LATENCY LIMIT\n"); 2920 } 2921 2922 void GenericScheduler::registerRoots() { 2923 Rem.CriticalPath = DAG->ExitSU.getDepth(); 2924 2925 // Some roots may not feed into ExitSU. Check all of them in case. 2926 for (const SUnit *SU : Bot.Available) { 2927 if (SU->getDepth() > Rem.CriticalPath) 2928 Rem.CriticalPath = SU->getDepth(); 2929 } 2930 LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n'); 2931 if (DumpCriticalPathLength) { 2932 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n"; 2933 } 2934 2935 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) { 2936 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath(); 2937 checkAcyclicLatency(); 2938 } 2939 } 2940 2941 namespace llvm { 2942 bool tryPressure(const PressureChange &TryP, 2943 const PressureChange &CandP, 2944 GenericSchedulerBase::SchedCandidate &TryCand, 2945 GenericSchedulerBase::SchedCandidate &Cand, 2946 GenericSchedulerBase::CandReason Reason, 2947 const TargetRegisterInfo *TRI, 2948 const MachineFunction &MF) { 2949 // If one candidate decreases and the other increases, go with it. 2950 // Invalid candidates have UnitInc==0. 2951 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand, 2952 Reason)) { 2953 return true; 2954 } 2955 // Do not compare the magnitude of pressure changes between top and bottom 2956 // boundary. 2957 if (Cand.AtTop != TryCand.AtTop) 2958 return false; 2959 2960 // If both candidates affect the same set in the same boundary, go with the 2961 // smallest increase. 2962 unsigned TryPSet = TryP.getPSetOrMax(); 2963 unsigned CandPSet = CandP.getPSetOrMax(); 2964 if (TryPSet == CandPSet) { 2965 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand, 2966 Reason); 2967 } 2968 2969 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) : 2970 std::numeric_limits<int>::max(); 2971 2972 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) : 2973 std::numeric_limits<int>::max(); 2974 2975 // If the candidates are decreasing pressure, reverse priority. 2976 if (TryP.getUnitInc() < 0) 2977 std::swap(TryRank, CandRank); 2978 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason); 2979 } 2980 2981 unsigned getWeakLeft(const SUnit *SU, bool isTop) { 2982 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft; 2983 } 2984 2985 /// Minimize physical register live ranges. Regalloc wants them adjacent to 2986 /// their physreg def/use. 2987 /// 2988 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf 2989 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled 2990 /// with the operation that produces or consumes the physreg. We'll do this when 2991 /// regalloc has support for parallel copies. 2992 int biasPhysReg(const SUnit *SU, bool isTop) { 2993 const MachineInstr *MI = SU->getInstr(); 2994 2995 if (MI->isCopy()) { 2996 unsigned ScheduledOper = isTop ? 1 : 0; 2997 unsigned UnscheduledOper = isTop ? 0 : 1; 2998 // If we have already scheduled the physreg produce/consumer, immediately 2999 // schedule the copy. 3000 if (Register::isPhysicalRegister(MI->getOperand(ScheduledOper).getReg())) 3001 return 1; 3002 // If the physreg is at the boundary, defer it. Otherwise schedule it 3003 // immediately to free the dependent. We can hoist the copy later. 3004 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft; 3005 if (Register::isPhysicalRegister(MI->getOperand(UnscheduledOper).getReg())) 3006 return AtBoundary ? -1 : 1; 3007 } 3008 3009 if (MI->isMoveImmediate()) { 3010 // If we have a move immediate and all successors have been assigned, bias 3011 // towards scheduling this later. Make sure all register defs are to 3012 // physical registers. 3013 bool DoBias = true; 3014 for (const MachineOperand &Op : MI->defs()) { 3015 if (Op.isReg() && !Register::isPhysicalRegister(Op.getReg())) { 3016 DoBias = false; 3017 break; 3018 } 3019 } 3020 3021 if (DoBias) 3022 return isTop ? -1 : 1; 3023 } 3024 3025 return 0; 3026 } 3027 } // end namespace llvm 3028 3029 void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU, 3030 bool AtTop, 3031 const RegPressureTracker &RPTracker, 3032 RegPressureTracker &TempTracker) { 3033 Cand.SU = SU; 3034 Cand.AtTop = AtTop; 3035 if (DAG->isTrackingPressure()) { 3036 if (AtTop) { 3037 TempTracker.getMaxDownwardPressureDelta( 3038 Cand.SU->getInstr(), 3039 Cand.RPDelta, 3040 DAG->getRegionCriticalPSets(), 3041 DAG->getRegPressure().MaxSetPressure); 3042 } else { 3043 if (VerifyScheduling) { 3044 TempTracker.getMaxUpwardPressureDelta( 3045 Cand.SU->getInstr(), 3046 &DAG->getPressureDiff(Cand.SU), 3047 Cand.RPDelta, 3048 DAG->getRegionCriticalPSets(), 3049 DAG->getRegPressure().MaxSetPressure); 3050 } else { 3051 RPTracker.getUpwardPressureDelta( 3052 Cand.SU->getInstr(), 3053 DAG->getPressureDiff(Cand.SU), 3054 Cand.RPDelta, 3055 DAG->getRegionCriticalPSets(), 3056 DAG->getRegPressure().MaxSetPressure); 3057 } 3058 } 3059 } 3060 LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs() 3061 << " Try SU(" << Cand.SU->NodeNum << ") " 3062 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":" 3063 << Cand.RPDelta.Excess.getUnitInc() << "\n"); 3064 } 3065 3066 /// Apply a set of heuristics to a new candidate. Heuristics are currently 3067 /// hierarchical. This may be more efficient than a graduated cost model because 3068 /// we don't need to evaluate all aspects of the model for each node in the 3069 /// queue. But it's really done to make the heuristics easier to debug and 3070 /// statistically analyze. 3071 /// 3072 /// \param Cand provides the policy and current best candidate. 3073 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized. 3074 /// \param Zone describes the scheduled zone that we are extending, or nullptr 3075 // if Cand is from a different zone than TryCand. 3076 void GenericScheduler::tryCandidate(SchedCandidate &Cand, 3077 SchedCandidate &TryCand, 3078 SchedBoundary *Zone) const { 3079 // Initialize the candidate if needed. 3080 if (!Cand.isValid()) { 3081 TryCand.Reason = NodeOrder; 3082 return; 3083 } 3084 3085 // Bias PhysReg Defs and copies to their uses and defined respectively. 3086 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop), 3087 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg)) 3088 return; 3089 3090 // Avoid exceeding the target's limit. 3091 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess, 3092 Cand.RPDelta.Excess, 3093 TryCand, Cand, RegExcess, TRI, 3094 DAG->MF)) 3095 return; 3096 3097 // Avoid increasing the max critical pressure in the scheduled region. 3098 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax, 3099 Cand.RPDelta.CriticalMax, 3100 TryCand, Cand, RegCritical, TRI, 3101 DAG->MF)) 3102 return; 3103 3104 // We only compare a subset of features when comparing nodes between 3105 // Top and Bottom boundary. Some properties are simply incomparable, in many 3106 // other instances we should only override the other boundary if something 3107 // is a clear good pick on one boundary. Skip heuristics that are more 3108 // "tie-breaking" in nature. 3109 bool SameBoundary = Zone != nullptr; 3110 if (SameBoundary) { 3111 // For loops that are acyclic path limited, aggressively schedule for 3112 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal 3113 // heuristics to take precedence. 3114 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() && 3115 tryLatency(TryCand, Cand, *Zone)) 3116 return; 3117 3118 // Prioritize instructions that read unbuffered resources by stall cycles. 3119 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU), 3120 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall)) 3121 return; 3122 } 3123 3124 // Keep clustered nodes together to encourage downstream peephole 3125 // optimizations which may reduce resource requirements. 3126 // 3127 // This is a best effort to set things up for a post-RA pass. Optimizations 3128 // like generating loads of multiple registers should ideally be done within 3129 // the scheduler pass by combining the loads during DAG postprocessing. 3130 const SUnit *CandNextClusterSU = 3131 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred(); 3132 const SUnit *TryCandNextClusterSU = 3133 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred(); 3134 if (tryGreater(TryCand.SU == TryCandNextClusterSU, 3135 Cand.SU == CandNextClusterSU, 3136 TryCand, Cand, Cluster)) 3137 return; 3138 3139 if (SameBoundary) { 3140 // Weak edges are for clustering and other constraints. 3141 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop), 3142 getWeakLeft(Cand.SU, Cand.AtTop), 3143 TryCand, Cand, Weak)) 3144 return; 3145 } 3146 3147 // Avoid increasing the max pressure of the entire region. 3148 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax, 3149 Cand.RPDelta.CurrentMax, 3150 TryCand, Cand, RegMax, TRI, 3151 DAG->MF)) 3152 return; 3153 3154 if (SameBoundary) { 3155 // Avoid critical resource consumption and balance the schedule. 3156 TryCand.initResourceDelta(DAG, SchedModel); 3157 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources, 3158 TryCand, Cand, ResourceReduce)) 3159 return; 3160 if (tryGreater(TryCand.ResDelta.DemandedResources, 3161 Cand.ResDelta.DemandedResources, 3162 TryCand, Cand, ResourceDemand)) 3163 return; 3164 3165 // Avoid serializing long latency dependence chains. 3166 // For acyclic path limited loops, latency was already checked above. 3167 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency && 3168 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone)) 3169 return; 3170 3171 // Fall through to original instruction order. 3172 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum) 3173 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) { 3174 TryCand.Reason = NodeOrder; 3175 } 3176 } 3177 } 3178 3179 /// Pick the best candidate from the queue. 3180 /// 3181 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during 3182 /// DAG building. To adjust for the current scheduling location we need to 3183 /// maintain the number of vreg uses remaining to be top-scheduled. 3184 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone, 3185 const CandPolicy &ZonePolicy, 3186 const RegPressureTracker &RPTracker, 3187 SchedCandidate &Cand) { 3188 // getMaxPressureDelta temporarily modifies the tracker. 3189 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker); 3190 3191 ReadyQueue &Q = Zone.Available; 3192 for (SUnit *SU : Q) { 3193 3194 SchedCandidate TryCand(ZonePolicy); 3195 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker); 3196 // Pass SchedBoundary only when comparing nodes from the same boundary. 3197 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr; 3198 tryCandidate(Cand, TryCand, ZoneArg); 3199 if (TryCand.Reason != NoCand) { 3200 // Initialize resource delta if needed in case future heuristics query it. 3201 if (TryCand.ResDelta == SchedResourceDelta()) 3202 TryCand.initResourceDelta(DAG, SchedModel); 3203 Cand.setBest(TryCand); 3204 LLVM_DEBUG(traceCandidate(Cand)); 3205 } 3206 } 3207 } 3208 3209 /// Pick the best candidate node from either the top or bottom queue. 3210 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) { 3211 // Schedule as far as possible in the direction of no choice. This is most 3212 // efficient, but also provides the best heuristics for CriticalPSets. 3213 if (SUnit *SU = Bot.pickOnlyChoice()) { 3214 IsTopNode = false; 3215 tracePick(Only1, false); 3216 return SU; 3217 } 3218 if (SUnit *SU = Top.pickOnlyChoice()) { 3219 IsTopNode = true; 3220 tracePick(Only1, true); 3221 return SU; 3222 } 3223 // Set the bottom-up policy based on the state of the current bottom zone and 3224 // the instructions outside the zone, including the top zone. 3225 CandPolicy BotPolicy; 3226 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top); 3227 // Set the top-down policy based on the state of the current top zone and 3228 // the instructions outside the zone, including the bottom zone. 3229 CandPolicy TopPolicy; 3230 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot); 3231 3232 // See if BotCand is still valid (because we previously scheduled from Top). 3233 LLVM_DEBUG(dbgs() << "Picking from Bot:\n"); 3234 if (!BotCand.isValid() || BotCand.SU->isScheduled || 3235 BotCand.Policy != BotPolicy) { 3236 BotCand.reset(CandPolicy()); 3237 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand); 3238 assert(BotCand.Reason != NoCand && "failed to find the first candidate"); 3239 } else { 3240 LLVM_DEBUG(traceCandidate(BotCand)); 3241 #ifndef NDEBUG 3242 if (VerifyScheduling) { 3243 SchedCandidate TCand; 3244 TCand.reset(CandPolicy()); 3245 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand); 3246 assert(TCand.SU == BotCand.SU && 3247 "Last pick result should correspond to re-picking right now"); 3248 } 3249 #endif 3250 } 3251 3252 // Check if the top Q has a better candidate. 3253 LLVM_DEBUG(dbgs() << "Picking from Top:\n"); 3254 if (!TopCand.isValid() || TopCand.SU->isScheduled || 3255 TopCand.Policy != TopPolicy) { 3256 TopCand.reset(CandPolicy()); 3257 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand); 3258 assert(TopCand.Reason != NoCand && "failed to find the first candidate"); 3259 } else { 3260 LLVM_DEBUG(traceCandidate(TopCand)); 3261 #ifndef NDEBUG 3262 if (VerifyScheduling) { 3263 SchedCandidate TCand; 3264 TCand.reset(CandPolicy()); 3265 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand); 3266 assert(TCand.SU == TopCand.SU && 3267 "Last pick result should correspond to re-picking right now"); 3268 } 3269 #endif 3270 } 3271 3272 // Pick best from BotCand and TopCand. 3273 assert(BotCand.isValid()); 3274 assert(TopCand.isValid()); 3275 SchedCandidate Cand = BotCand; 3276 TopCand.Reason = NoCand; 3277 tryCandidate(Cand, TopCand, nullptr); 3278 if (TopCand.Reason != NoCand) { 3279 Cand.setBest(TopCand); 3280 LLVM_DEBUG(traceCandidate(Cand)); 3281 } 3282 3283 IsTopNode = Cand.AtTop; 3284 tracePick(Cand); 3285 return Cand.SU; 3286 } 3287 3288 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy. 3289 SUnit *GenericScheduler::pickNode(bool &IsTopNode) { 3290 if (DAG->top() == DAG->bottom()) { 3291 assert(Top.Available.empty() && Top.Pending.empty() && 3292 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage"); 3293 return nullptr; 3294 } 3295 SUnit *SU; 3296 do { 3297 if (RegionPolicy.OnlyTopDown) { 3298 SU = Top.pickOnlyChoice(); 3299 if (!SU) { 3300 CandPolicy NoPolicy; 3301 TopCand.reset(NoPolicy); 3302 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand); 3303 assert(TopCand.Reason != NoCand && "failed to find a candidate"); 3304 tracePick(TopCand); 3305 SU = TopCand.SU; 3306 } 3307 IsTopNode = true; 3308 } else if (RegionPolicy.OnlyBottomUp) { 3309 SU = Bot.pickOnlyChoice(); 3310 if (!SU) { 3311 CandPolicy NoPolicy; 3312 BotCand.reset(NoPolicy); 3313 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand); 3314 assert(BotCand.Reason != NoCand && "failed to find a candidate"); 3315 tracePick(BotCand); 3316 SU = BotCand.SU; 3317 } 3318 IsTopNode = false; 3319 } else { 3320 SU = pickNodeBidirectional(IsTopNode); 3321 } 3322 } while (SU->isScheduled); 3323 3324 if (SU->isTopReady()) 3325 Top.removeReady(SU); 3326 if (SU->isBottomReady()) 3327 Bot.removeReady(SU); 3328 3329 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " 3330 << *SU->getInstr()); 3331 return SU; 3332 } 3333 3334 void GenericScheduler::reschedulePhysReg(SUnit *SU, bool isTop) { 3335 MachineBasicBlock::iterator InsertPos = SU->getInstr(); 3336 if (!isTop) 3337 ++InsertPos; 3338 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs; 3339 3340 // Find already scheduled copies with a single physreg dependence and move 3341 // them just above the scheduled instruction. 3342 for (SDep &Dep : Deps) { 3343 if (Dep.getKind() != SDep::Data || 3344 !Register::isPhysicalRegister(Dep.getReg())) 3345 continue; 3346 SUnit *DepSU = Dep.getSUnit(); 3347 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1) 3348 continue; 3349 MachineInstr *Copy = DepSU->getInstr(); 3350 if (!Copy->isCopy() && !Copy->isMoveImmediate()) 3351 continue; 3352 LLVM_DEBUG(dbgs() << " Rescheduling physreg copy "; 3353 DAG->dumpNode(*Dep.getSUnit())); 3354 DAG->moveInstruction(Copy, InsertPos); 3355 } 3356 } 3357 3358 /// Update the scheduler's state after scheduling a node. This is the same node 3359 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to 3360 /// update it's state based on the current cycle before MachineSchedStrategy 3361 /// does. 3362 /// 3363 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling 3364 /// them here. See comments in biasPhysReg. 3365 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) { 3366 if (IsTopNode) { 3367 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle()); 3368 Top.bumpNode(SU); 3369 if (SU->hasPhysRegUses) 3370 reschedulePhysReg(SU, true); 3371 } else { 3372 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle()); 3373 Bot.bumpNode(SU); 3374 if (SU->hasPhysRegDefs) 3375 reschedulePhysReg(SU, false); 3376 } 3377 } 3378 3379 /// Create the standard converging machine scheduler. This will be used as the 3380 /// default scheduler if the target does not set a default. 3381 ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) { 3382 ScheduleDAGMILive *DAG = 3383 new ScheduleDAGMILive(C, std::make_unique<GenericScheduler>(C)); 3384 // Register DAG post-processors. 3385 // 3386 // FIXME: extend the mutation API to allow earlier mutations to instantiate 3387 // data and pass it to later mutations. Have a single mutation that gathers 3388 // the interesting nodes in one pass. 3389 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI)); 3390 return DAG; 3391 } 3392 3393 static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) { 3394 return createGenericSchedLive(C); 3395 } 3396 3397 static MachineSchedRegistry 3398 GenericSchedRegistry("converge", "Standard converging scheduler.", 3399 createConveringSched); 3400 3401 //===----------------------------------------------------------------------===// 3402 // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy. 3403 //===----------------------------------------------------------------------===// 3404 3405 void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) { 3406 DAG = Dag; 3407 SchedModel = DAG->getSchedModel(); 3408 TRI = DAG->TRI; 3409 3410 Rem.init(DAG, SchedModel); 3411 Top.init(DAG, SchedModel, &Rem); 3412 BotRoots.clear(); 3413 3414 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, 3415 // or are disabled, then these HazardRecs will be disabled. 3416 const InstrItineraryData *Itin = SchedModel->getInstrItineraries(); 3417 if (!Top.HazardRec) { 3418 Top.HazardRec = 3419 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer( 3420 Itin, DAG); 3421 } 3422 } 3423 3424 void PostGenericScheduler::registerRoots() { 3425 Rem.CriticalPath = DAG->ExitSU.getDepth(); 3426 3427 // Some roots may not feed into ExitSU. Check all of them in case. 3428 for (const SUnit *SU : BotRoots) { 3429 if (SU->getDepth() > Rem.CriticalPath) 3430 Rem.CriticalPath = SU->getDepth(); 3431 } 3432 LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n'); 3433 if (DumpCriticalPathLength) { 3434 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n"; 3435 } 3436 } 3437 3438 /// Apply a set of heuristics to a new candidate for PostRA scheduling. 3439 /// 3440 /// \param Cand provides the policy and current best candidate. 3441 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized. 3442 void PostGenericScheduler::tryCandidate(SchedCandidate &Cand, 3443 SchedCandidate &TryCand) { 3444 // Initialize the candidate if needed. 3445 if (!Cand.isValid()) { 3446 TryCand.Reason = NodeOrder; 3447 return; 3448 } 3449 3450 // Prioritize instructions that read unbuffered resources by stall cycles. 3451 if (tryLess(Top.getLatencyStallCycles(TryCand.SU), 3452 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall)) 3453 return; 3454 3455 // Keep clustered nodes together. 3456 if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(), 3457 Cand.SU == DAG->getNextClusterSucc(), 3458 TryCand, Cand, Cluster)) 3459 return; 3460 3461 // Avoid critical resource consumption and balance the schedule. 3462 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources, 3463 TryCand, Cand, ResourceReduce)) 3464 return; 3465 if (tryGreater(TryCand.ResDelta.DemandedResources, 3466 Cand.ResDelta.DemandedResources, 3467 TryCand, Cand, ResourceDemand)) 3468 return; 3469 3470 // Avoid serializing long latency dependence chains. 3471 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) { 3472 return; 3473 } 3474 3475 // Fall through to original instruction order. 3476 if (TryCand.SU->NodeNum < Cand.SU->NodeNum) 3477 TryCand.Reason = NodeOrder; 3478 } 3479 3480 void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) { 3481 ReadyQueue &Q = Top.Available; 3482 for (SUnit *SU : Q) { 3483 SchedCandidate TryCand(Cand.Policy); 3484 TryCand.SU = SU; 3485 TryCand.AtTop = true; 3486 TryCand.initResourceDelta(DAG, SchedModel); 3487 tryCandidate(Cand, TryCand); 3488 if (TryCand.Reason != NoCand) { 3489 Cand.setBest(TryCand); 3490 LLVM_DEBUG(traceCandidate(Cand)); 3491 } 3492 } 3493 } 3494 3495 /// Pick the next node to schedule. 3496 SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) { 3497 if (DAG->top() == DAG->bottom()) { 3498 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage"); 3499 return nullptr; 3500 } 3501 SUnit *SU; 3502 do { 3503 SU = Top.pickOnlyChoice(); 3504 if (SU) { 3505 tracePick(Only1, true); 3506 } else { 3507 CandPolicy NoPolicy; 3508 SchedCandidate TopCand(NoPolicy); 3509 // Set the top-down policy based on the state of the current top zone and 3510 // the instructions outside the zone, including the bottom zone. 3511 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr); 3512 pickNodeFromQueue(TopCand); 3513 assert(TopCand.Reason != NoCand && "failed to find a candidate"); 3514 tracePick(TopCand); 3515 SU = TopCand.SU; 3516 } 3517 } while (SU->isScheduled); 3518 3519 IsTopNode = true; 3520 Top.removeReady(SU); 3521 3522 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " 3523 << *SU->getInstr()); 3524 return SU; 3525 } 3526 3527 /// Called after ScheduleDAGMI has scheduled an instruction and updated 3528 /// scheduled/remaining flags in the DAG nodes. 3529 void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) { 3530 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle()); 3531 Top.bumpNode(SU); 3532 } 3533 3534 ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) { 3535 return new ScheduleDAGMI(C, std::make_unique<PostGenericScheduler>(C), 3536 /*RemoveKillFlags=*/true); 3537 } 3538 3539 //===----------------------------------------------------------------------===// 3540 // ILP Scheduler. Currently for experimental analysis of heuristics. 3541 //===----------------------------------------------------------------------===// 3542 3543 namespace { 3544 3545 /// Order nodes by the ILP metric. 3546 struct ILPOrder { 3547 const SchedDFSResult *DFSResult = nullptr; 3548 const BitVector *ScheduledTrees = nullptr; 3549 bool MaximizeILP; 3550 3551 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {} 3552 3553 /// Apply a less-than relation on node priority. 3554 /// 3555 /// (Return true if A comes after B in the Q.) 3556 bool operator()(const SUnit *A, const SUnit *B) const { 3557 unsigned SchedTreeA = DFSResult->getSubtreeID(A); 3558 unsigned SchedTreeB = DFSResult->getSubtreeID(B); 3559 if (SchedTreeA != SchedTreeB) { 3560 // Unscheduled trees have lower priority. 3561 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB)) 3562 return ScheduledTrees->test(SchedTreeB); 3563 3564 // Trees with shallower connections have have lower priority. 3565 if (DFSResult->getSubtreeLevel(SchedTreeA) 3566 != DFSResult->getSubtreeLevel(SchedTreeB)) { 3567 return DFSResult->getSubtreeLevel(SchedTreeA) 3568 < DFSResult->getSubtreeLevel(SchedTreeB); 3569 } 3570 } 3571 if (MaximizeILP) 3572 return DFSResult->getILP(A) < DFSResult->getILP(B); 3573 else 3574 return DFSResult->getILP(A) > DFSResult->getILP(B); 3575 } 3576 }; 3577 3578 /// Schedule based on the ILP metric. 3579 class ILPScheduler : public MachineSchedStrategy { 3580 ScheduleDAGMILive *DAG = nullptr; 3581 ILPOrder Cmp; 3582 3583 std::vector<SUnit*> ReadyQ; 3584 3585 public: 3586 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {} 3587 3588 void initialize(ScheduleDAGMI *dag) override { 3589 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness"); 3590 DAG = static_cast<ScheduleDAGMILive*>(dag); 3591 DAG->computeDFSResult(); 3592 Cmp.DFSResult = DAG->getDFSResult(); 3593 Cmp.ScheduledTrees = &DAG->getScheduledTrees(); 3594 ReadyQ.clear(); 3595 } 3596 3597 void registerRoots() override { 3598 // Restore the heap in ReadyQ with the updated DFS results. 3599 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3600 } 3601 3602 /// Implement MachineSchedStrategy interface. 3603 /// ----------------------------------------- 3604 3605 /// Callback to select the highest priority node from the ready Q. 3606 SUnit *pickNode(bool &IsTopNode) override { 3607 if (ReadyQ.empty()) return nullptr; 3608 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3609 SUnit *SU = ReadyQ.back(); 3610 ReadyQ.pop_back(); 3611 IsTopNode = false; 3612 LLVM_DEBUG(dbgs() << "Pick node " 3613 << "SU(" << SU->NodeNum << ") " 3614 << " ILP: " << DAG->getDFSResult()->getILP(SU) 3615 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) 3616 << " @" 3617 << DAG->getDFSResult()->getSubtreeLevel( 3618 DAG->getDFSResult()->getSubtreeID(SU)) 3619 << '\n' 3620 << "Scheduling " << *SU->getInstr()); 3621 return SU; 3622 } 3623 3624 /// Scheduler callback to notify that a new subtree is scheduled. 3625 void scheduleTree(unsigned SubtreeID) override { 3626 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3627 } 3628 3629 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify 3630 /// DFSResults, and resort the priority Q. 3631 void schedNode(SUnit *SU, bool IsTopNode) override { 3632 assert(!IsTopNode && "SchedDFSResult needs bottom-up"); 3633 } 3634 3635 void releaseTopNode(SUnit *) override { /*only called for top roots*/ } 3636 3637 void releaseBottomNode(SUnit *SU) override { 3638 ReadyQ.push_back(SU); 3639 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3640 } 3641 }; 3642 3643 } // end anonymous namespace 3644 3645 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) { 3646 return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(true)); 3647 } 3648 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) { 3649 return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(false)); 3650 } 3651 3652 static MachineSchedRegistry ILPMaxRegistry( 3653 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler); 3654 static MachineSchedRegistry ILPMinRegistry( 3655 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler); 3656 3657 //===----------------------------------------------------------------------===// 3658 // Machine Instruction Shuffler for Correctness Testing 3659 //===----------------------------------------------------------------------===// 3660 3661 #ifndef NDEBUG 3662 namespace { 3663 3664 /// Apply a less-than relation on the node order, which corresponds to the 3665 /// instruction order prior to scheduling. IsReverse implements greater-than. 3666 template<bool IsReverse> 3667 struct SUnitOrder { 3668 bool operator()(SUnit *A, SUnit *B) const { 3669 if (IsReverse) 3670 return A->NodeNum > B->NodeNum; 3671 else 3672 return A->NodeNum < B->NodeNum; 3673 } 3674 }; 3675 3676 /// Reorder instructions as much as possible. 3677 class InstructionShuffler : public MachineSchedStrategy { 3678 bool IsAlternating; 3679 bool IsTopDown; 3680 3681 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority 3682 // gives nodes with a higher number higher priority causing the latest 3683 // instructions to be scheduled first. 3684 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>> 3685 TopQ; 3686 3687 // When scheduling bottom-up, use greater-than as the queue priority. 3688 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>> 3689 BottomQ; 3690 3691 public: 3692 InstructionShuffler(bool alternate, bool topdown) 3693 : IsAlternating(alternate), IsTopDown(topdown) {} 3694 3695 void initialize(ScheduleDAGMI*) override { 3696 TopQ.clear(); 3697 BottomQ.clear(); 3698 } 3699 3700 /// Implement MachineSchedStrategy interface. 3701 /// ----------------------------------------- 3702 3703 SUnit *pickNode(bool &IsTopNode) override { 3704 SUnit *SU; 3705 if (IsTopDown) { 3706 do { 3707 if (TopQ.empty()) return nullptr; 3708 SU = TopQ.top(); 3709 TopQ.pop(); 3710 } while (SU->isScheduled); 3711 IsTopNode = true; 3712 } else { 3713 do { 3714 if (BottomQ.empty()) return nullptr; 3715 SU = BottomQ.top(); 3716 BottomQ.pop(); 3717 } while (SU->isScheduled); 3718 IsTopNode = false; 3719 } 3720 if (IsAlternating) 3721 IsTopDown = !IsTopDown; 3722 return SU; 3723 } 3724 3725 void schedNode(SUnit *SU, bool IsTopNode) override {} 3726 3727 void releaseTopNode(SUnit *SU) override { 3728 TopQ.push(SU); 3729 } 3730 void releaseBottomNode(SUnit *SU) override { 3731 BottomQ.push(SU); 3732 } 3733 }; 3734 3735 } // end anonymous namespace 3736 3737 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) { 3738 bool Alternate = !ForceTopDown && !ForceBottomUp; 3739 bool TopDown = !ForceBottomUp; 3740 assert((TopDown || !ForceTopDown) && 3741 "-misched-topdown incompatible with -misched-bottomup"); 3742 return new ScheduleDAGMILive( 3743 C, std::make_unique<InstructionShuffler>(Alternate, TopDown)); 3744 } 3745 3746 static MachineSchedRegistry ShufflerRegistry( 3747 "shuffle", "Shuffle machine instructions alternating directions", 3748 createInstructionShuffler); 3749 #endif // !NDEBUG 3750 3751 //===----------------------------------------------------------------------===// 3752 // GraphWriter support for ScheduleDAGMILive. 3753 //===----------------------------------------------------------------------===// 3754 3755 #ifndef NDEBUG 3756 namespace llvm { 3757 3758 template<> struct GraphTraits< 3759 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {}; 3760 3761 template<> 3762 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits { 3763 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3764 3765 static std::string getGraphName(const ScheduleDAG *G) { 3766 return std::string(G->MF.getName()); 3767 } 3768 3769 static bool renderGraphFromBottomUp() { 3770 return true; 3771 } 3772 3773 static bool isNodeHidden(const SUnit *Node) { 3774 if (ViewMISchedCutoff == 0) 3775 return false; 3776 return (Node->Preds.size() > ViewMISchedCutoff 3777 || Node->Succs.size() > ViewMISchedCutoff); 3778 } 3779 3780 /// If you want to override the dot attributes printed for a particular 3781 /// edge, override this method. 3782 static std::string getEdgeAttributes(const SUnit *Node, 3783 SUnitIterator EI, 3784 const ScheduleDAG *Graph) { 3785 if (EI.isArtificialDep()) 3786 return "color=cyan,style=dashed"; 3787 if (EI.isCtrlDep()) 3788 return "color=blue,style=dashed"; 3789 return ""; 3790 } 3791 3792 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) { 3793 std::string Str; 3794 raw_string_ostream SS(Str); 3795 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G); 3796 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ? 3797 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr; 3798 SS << "SU:" << SU->NodeNum; 3799 if (DFS) 3800 SS << " I:" << DFS->getNumInstrs(SU); 3801 return SS.str(); 3802 } 3803 3804 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) { 3805 return G->getGraphNodeLabel(SU); 3806 } 3807 3808 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) { 3809 std::string Str("shape=Mrecord"); 3810 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G); 3811 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ? 3812 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr; 3813 if (DFS) { 3814 Str += ",style=filled,fillcolor=\"#"; 3815 Str += DOT::getColorString(DFS->getSubtreeID(N)); 3816 Str += '"'; 3817 } 3818 return Str; 3819 } 3820 }; 3821 3822 } // end namespace llvm 3823 #endif // NDEBUG 3824 3825 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG 3826 /// rendered using 'dot'. 3827 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) { 3828 #ifndef NDEBUG 3829 ViewGraph(this, Name, false, Title); 3830 #else 3831 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on " 3832 << "systems with Graphviz or gv!\n"; 3833 #endif // NDEBUG 3834 } 3835 3836 /// Out-of-line implementation with no arguments is handy for gdb. 3837 void ScheduleDAGMI::viewGraph() { 3838 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName()); 3839 } 3840