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<MemOpInfo> MemOps, 1534 ScheduleDAGInstrs *DAG); 1535 void collectMemOpRecords(std::vector<SUnit> &SUnits, 1536 SmallVectorImpl<MemOpInfo> &MemOpRecords); 1537 }; 1538 1539 class StoreClusterMutation : public BaseMemOpClusterMutation { 1540 public: 1541 StoreClusterMutation(const TargetInstrInfo *tii, 1542 const TargetRegisterInfo *tri) 1543 : BaseMemOpClusterMutation(tii, tri, false) {} 1544 }; 1545 1546 class LoadClusterMutation : public BaseMemOpClusterMutation { 1547 public: 1548 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri) 1549 : BaseMemOpClusterMutation(tii, tri, true) {} 1550 }; 1551 1552 } // end anonymous namespace 1553 1554 namespace llvm { 1555 1556 std::unique_ptr<ScheduleDAGMutation> 1557 createLoadClusterDAGMutation(const TargetInstrInfo *TII, 1558 const TargetRegisterInfo *TRI) { 1559 return EnableMemOpCluster ? std::make_unique<LoadClusterMutation>(TII, TRI) 1560 : nullptr; 1561 } 1562 1563 std::unique_ptr<ScheduleDAGMutation> 1564 createStoreClusterDAGMutation(const TargetInstrInfo *TII, 1565 const TargetRegisterInfo *TRI) { 1566 return EnableMemOpCluster ? std::make_unique<StoreClusterMutation>(TII, TRI) 1567 : nullptr; 1568 } 1569 1570 } // end namespace llvm 1571 1572 // Sorting all the loads/stores first, then for each load/store, checking the 1573 // following load/store one by one, until reach the first non-dependent one and 1574 // call target hook to see if they can cluster. 1575 void BaseMemOpClusterMutation::clusterNeighboringMemOps( 1576 ArrayRef<MemOpInfo> MemOpRecords, ScheduleDAGInstrs *DAG) { 1577 // Keep track of the current cluster length and bytes for each SUnit. 1578 DenseMap<unsigned, std::pair<unsigned, unsigned>> SUnit2ClusterInfo; 1579 1580 // At this point, `MemOpRecords` array must hold atleast two mem ops. Try to 1581 // cluster mem ops collected within `MemOpRecords` array. 1582 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) { 1583 // Decision to cluster mem ops is taken based on target dependent logic 1584 auto MemOpa = MemOpRecords[Idx]; 1585 1586 // Seek for the next load/store to do the cluster. 1587 unsigned NextIdx = Idx + 1; 1588 for (; NextIdx < End; ++NextIdx) 1589 // Skip if MemOpb has been clustered already or has dependency with 1590 // MemOpa. 1591 if (!SUnit2ClusterInfo.count(MemOpRecords[NextIdx].SU->NodeNum) && 1592 !DAG->IsReachable(MemOpRecords[NextIdx].SU, MemOpa.SU) && 1593 !DAG->IsReachable(MemOpa.SU, MemOpRecords[NextIdx].SU)) 1594 break; 1595 if (NextIdx == End) 1596 continue; 1597 1598 auto MemOpb = MemOpRecords[NextIdx]; 1599 unsigned ClusterLength = 2; 1600 unsigned CurrentClusterBytes = MemOpa.Width + MemOpb.Width; 1601 if (SUnit2ClusterInfo.count(MemOpa.SU->NodeNum)) { 1602 ClusterLength = SUnit2ClusterInfo[MemOpa.SU->NodeNum].first + 1; 1603 CurrentClusterBytes = 1604 SUnit2ClusterInfo[MemOpa.SU->NodeNum].second + MemOpb.Width; 1605 } 1606 1607 if (!TII->shouldClusterMemOps(MemOpa.BaseOps, MemOpb.BaseOps, ClusterLength, 1608 CurrentClusterBytes)) 1609 continue; 1610 1611 SUnit *SUa = MemOpa.SU; 1612 SUnit *SUb = MemOpb.SU; 1613 if (SUa->NodeNum > SUb->NodeNum) 1614 std::swap(SUa, SUb); 1615 1616 // FIXME: Is this check really required? 1617 if (!DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) 1618 continue; 1619 1620 LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU(" 1621 << SUb->NodeNum << ")\n"); 1622 ++NumClustered; 1623 1624 if (IsLoad) { 1625 // Copy successor edges from SUa to SUb. Interleaving computation 1626 // dependent on SUa can prevent load combining due to register reuse. 1627 // Predecessor edges do not need to be copied from SUb to SUa since 1628 // nearby loads should have effectively the same inputs. 1629 for (const SDep &Succ : SUa->Succs) { 1630 if (Succ.getSUnit() == SUb) 1631 continue; 1632 LLVM_DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum 1633 << ")\n"); 1634 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial)); 1635 } 1636 } else { 1637 // Copy predecessor edges from SUb to SUa to avoid the SUnits that 1638 // SUb dependent on scheduled in-between SUb and SUa. Successor edges 1639 // do not need to be copied from SUa to SUb since no one will depend 1640 // on stores. 1641 // Notice that, we don't need to care about the memory dependency as 1642 // we won't try to cluster them if they have any memory dependency. 1643 for (const SDep &Pred : SUb->Preds) { 1644 if (Pred.getSUnit() == SUa) 1645 continue; 1646 LLVM_DEBUG(dbgs() << " Copy Pred SU(" << Pred.getSUnit()->NodeNum 1647 << ")\n"); 1648 DAG->addEdge(SUa, SDep(Pred.getSUnit(), SDep::Artificial)); 1649 } 1650 } 1651 1652 SUnit2ClusterInfo[MemOpb.SU->NodeNum] = {ClusterLength, 1653 CurrentClusterBytes}; 1654 1655 LLVM_DEBUG(dbgs() << " Curr cluster length: " << ClusterLength 1656 << ", Curr cluster bytes: " << CurrentClusterBytes 1657 << "\n"); 1658 } 1659 } 1660 1661 void BaseMemOpClusterMutation::collectMemOpRecords( 1662 std::vector<SUnit> &SUnits, SmallVectorImpl<MemOpInfo> &MemOpRecords) { 1663 for (auto &SU : SUnits) { 1664 if ((IsLoad && !SU.getInstr()->mayLoad()) || 1665 (!IsLoad && !SU.getInstr()->mayStore())) 1666 continue; 1667 1668 const MachineInstr &MI = *SU.getInstr(); 1669 SmallVector<const MachineOperand *, 4> BaseOps; 1670 int64_t Offset; 1671 bool OffsetIsScalable; 1672 unsigned Width; 1673 if (TII->getMemOperandsWithOffsetWidth(MI, BaseOps, Offset, 1674 OffsetIsScalable, Width, TRI)) { 1675 MemOpRecords.push_back(MemOpInfo(&SU, BaseOps, Offset, Width)); 1676 1677 LLVM_DEBUG(dbgs() << "Num BaseOps: " << BaseOps.size() << ", Offset: " 1678 << Offset << ", OffsetIsScalable: " << OffsetIsScalable 1679 << ", Width: " << Width << "\n"); 1680 } 1681 #ifndef NDEBUG 1682 for (auto *Op : BaseOps) 1683 assert(Op); 1684 #endif 1685 } 1686 } 1687 1688 /// Callback from DAG postProcessing to create cluster edges for loads/stores. 1689 void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAG) { 1690 // Collect all the clusterable loads/stores 1691 SmallVector<MemOpInfo, 32> MemOpRecords; 1692 collectMemOpRecords(DAG->SUnits, MemOpRecords); 1693 1694 if (MemOpRecords.size() < 2) 1695 return; 1696 1697 // Sorting the loads/stores, so that, we can stop the cluster as early as 1698 // possible. 1699 llvm::sort(MemOpRecords); 1700 1701 // Trying to cluster all the neighboring loads/stores. 1702 clusterNeighboringMemOps(MemOpRecords, DAG); 1703 } 1704 1705 //===----------------------------------------------------------------------===// 1706 // CopyConstrain - DAG post-processing to encourage copy elimination. 1707 //===----------------------------------------------------------------------===// 1708 1709 namespace { 1710 1711 /// Post-process the DAG to create weak edges from all uses of a copy to 1712 /// the one use that defines the copy's source vreg, most likely an induction 1713 /// variable increment. 1714 class CopyConstrain : public ScheduleDAGMutation { 1715 // Transient state. 1716 SlotIndex RegionBeginIdx; 1717 1718 // RegionEndIdx is the slot index of the last non-debug instruction in the 1719 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx. 1720 SlotIndex RegionEndIdx; 1721 1722 public: 1723 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {} 1724 1725 void apply(ScheduleDAGInstrs *DAGInstrs) override; 1726 1727 protected: 1728 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG); 1729 }; 1730 1731 } // end anonymous namespace 1732 1733 namespace llvm { 1734 1735 std::unique_ptr<ScheduleDAGMutation> 1736 createCopyConstrainDAGMutation(const TargetInstrInfo *TII, 1737 const TargetRegisterInfo *TRI) { 1738 return std::make_unique<CopyConstrain>(TII, TRI); 1739 } 1740 1741 } // end namespace llvm 1742 1743 /// constrainLocalCopy handles two possibilities: 1744 /// 1) Local src: 1745 /// I0: = dst 1746 /// I1: src = ... 1747 /// I2: = dst 1748 /// I3: dst = src (copy) 1749 /// (create pred->succ edges I0->I1, I2->I1) 1750 /// 1751 /// 2) Local copy: 1752 /// I0: dst = src (copy) 1753 /// I1: = dst 1754 /// I2: src = ... 1755 /// I3: = dst 1756 /// (create pred->succ edges I1->I2, I3->I2) 1757 /// 1758 /// Although the MachineScheduler is currently constrained to single blocks, 1759 /// this algorithm should handle extended blocks. An EBB is a set of 1760 /// contiguously numbered blocks such that the previous block in the EBB is 1761 /// always the single predecessor. 1762 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) { 1763 LiveIntervals *LIS = DAG->getLIS(); 1764 MachineInstr *Copy = CopySU->getInstr(); 1765 1766 // Check for pure vreg copies. 1767 const MachineOperand &SrcOp = Copy->getOperand(1); 1768 Register SrcReg = SrcOp.getReg(); 1769 if (!Register::isVirtualRegister(SrcReg) || !SrcOp.readsReg()) 1770 return; 1771 1772 const MachineOperand &DstOp = Copy->getOperand(0); 1773 Register DstReg = DstOp.getReg(); 1774 if (!Register::isVirtualRegister(DstReg) || DstOp.isDead()) 1775 return; 1776 1777 // Check if either the dest or source is local. If it's live across a back 1778 // edge, it's not local. Note that if both vregs are live across the back 1779 // edge, we cannot successfully contrain the copy without cyclic scheduling. 1780 // If both the copy's source and dest are local live intervals, then we 1781 // should treat the dest as the global for the purpose of adding 1782 // constraints. This adds edges from source's other uses to the copy. 1783 unsigned LocalReg = SrcReg; 1784 unsigned GlobalReg = DstReg; 1785 LiveInterval *LocalLI = &LIS->getInterval(LocalReg); 1786 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) { 1787 LocalReg = DstReg; 1788 GlobalReg = SrcReg; 1789 LocalLI = &LIS->getInterval(LocalReg); 1790 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) 1791 return; 1792 } 1793 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg); 1794 1795 // Find the global segment after the start of the local LI. 1796 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex()); 1797 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a 1798 // local live range. We could create edges from other global uses to the local 1799 // start, but the coalescer should have already eliminated these cases, so 1800 // don't bother dealing with it. 1801 if (GlobalSegment == GlobalLI->end()) 1802 return; 1803 1804 // If GlobalSegment is killed at the LocalLI->start, the call to find() 1805 // returned the next global segment. But if GlobalSegment overlaps with 1806 // LocalLI->start, then advance to the next segment. If a hole in GlobalLI 1807 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole. 1808 if (GlobalSegment->contains(LocalLI->beginIndex())) 1809 ++GlobalSegment; 1810 1811 if (GlobalSegment == GlobalLI->end()) 1812 return; 1813 1814 // Check if GlobalLI contains a hole in the vicinity of LocalLI. 1815 if (GlobalSegment != GlobalLI->begin()) { 1816 // Two address defs have no hole. 1817 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end, 1818 GlobalSegment->start)) { 1819 return; 1820 } 1821 // If the prior global segment may be defined by the same two-address 1822 // instruction that also defines LocalLI, then can't make a hole here. 1823 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start, 1824 LocalLI->beginIndex())) { 1825 return; 1826 } 1827 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise 1828 // it would be a disconnected component in the live range. 1829 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() && 1830 "Disconnected LRG within the scheduling region."); 1831 } 1832 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start); 1833 if (!GlobalDef) 1834 return; 1835 1836 SUnit *GlobalSU = DAG->getSUnit(GlobalDef); 1837 if (!GlobalSU) 1838 return; 1839 1840 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by 1841 // constraining the uses of the last local def to precede GlobalDef. 1842 SmallVector<SUnit*,8> LocalUses; 1843 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex()); 1844 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def); 1845 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef); 1846 for (const SDep &Succ : LastLocalSU->Succs) { 1847 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg) 1848 continue; 1849 if (Succ.getSUnit() == GlobalSU) 1850 continue; 1851 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit())) 1852 return; 1853 LocalUses.push_back(Succ.getSUnit()); 1854 } 1855 // Open the top of the GlobalLI hole by constraining any earlier global uses 1856 // to precede the start of LocalLI. 1857 SmallVector<SUnit*,8> GlobalUses; 1858 MachineInstr *FirstLocalDef = 1859 LIS->getInstructionFromIndex(LocalLI->beginIndex()); 1860 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef); 1861 for (const SDep &Pred : GlobalSU->Preds) { 1862 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg) 1863 continue; 1864 if (Pred.getSUnit() == FirstLocalSU) 1865 continue; 1866 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit())) 1867 return; 1868 GlobalUses.push_back(Pred.getSUnit()); 1869 } 1870 LLVM_DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n"); 1871 // Add the weak edges. 1872 for (SmallVectorImpl<SUnit*>::const_iterator 1873 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) { 1874 LLVM_DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU(" 1875 << GlobalSU->NodeNum << ")\n"); 1876 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak)); 1877 } 1878 for (SmallVectorImpl<SUnit*>::const_iterator 1879 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) { 1880 LLVM_DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU(" 1881 << FirstLocalSU->NodeNum << ")\n"); 1882 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak)); 1883 } 1884 } 1885 1886 /// Callback from DAG postProcessing to create weak edges to encourage 1887 /// copy elimination. 1888 void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) { 1889 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs); 1890 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals"); 1891 1892 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end()); 1893 if (FirstPos == DAG->end()) 1894 return; 1895 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos); 1896 RegionEndIdx = DAG->getLIS()->getInstructionIndex( 1897 *priorNonDebug(DAG->end(), DAG->begin())); 1898 1899 for (SUnit &SU : DAG->SUnits) { 1900 if (!SU.getInstr()->isCopy()) 1901 continue; 1902 1903 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG)); 1904 } 1905 } 1906 1907 //===----------------------------------------------------------------------===// 1908 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler 1909 // and possibly other custom schedulers. 1910 //===----------------------------------------------------------------------===// 1911 1912 static const unsigned InvalidCycle = ~0U; 1913 1914 SchedBoundary::~SchedBoundary() { delete HazardRec; } 1915 1916 /// Given a Count of resource usage and a Latency value, return true if a 1917 /// SchedBoundary becomes resource limited. 1918 /// If we are checking after scheduling a node, we should return true when 1919 /// we just reach the resource limit. 1920 static bool checkResourceLimit(unsigned LFactor, unsigned Count, 1921 unsigned Latency, bool AfterSchedNode) { 1922 int ResCntFactor = (int)(Count - (Latency * LFactor)); 1923 if (AfterSchedNode) 1924 return ResCntFactor >= (int)LFactor; 1925 else 1926 return ResCntFactor > (int)LFactor; 1927 } 1928 1929 void SchedBoundary::reset() { 1930 // A new HazardRec is created for each DAG and owned by SchedBoundary. 1931 // Destroying and reconstructing it is very expensive though. So keep 1932 // invalid, placeholder HazardRecs. 1933 if (HazardRec && HazardRec->isEnabled()) { 1934 delete HazardRec; 1935 HazardRec = nullptr; 1936 } 1937 Available.clear(); 1938 Pending.clear(); 1939 CheckPending = false; 1940 CurrCycle = 0; 1941 CurrMOps = 0; 1942 MinReadyCycle = std::numeric_limits<unsigned>::max(); 1943 ExpectedLatency = 0; 1944 DependentLatency = 0; 1945 RetiredMOps = 0; 1946 MaxExecutedResCount = 0; 1947 ZoneCritResIdx = 0; 1948 IsResourceLimited = false; 1949 ReservedCycles.clear(); 1950 ReservedCyclesIndex.clear(); 1951 #ifndef NDEBUG 1952 // Track the maximum number of stall cycles that could arise either from the 1953 // latency of a DAG edge or the number of cycles that a processor resource is 1954 // reserved (SchedBoundary::ReservedCycles). 1955 MaxObservedStall = 0; 1956 #endif 1957 // Reserve a zero-count for invalid CritResIdx. 1958 ExecutedResCounts.resize(1); 1959 assert(!ExecutedResCounts[0] && "nonzero count for bad resource"); 1960 } 1961 1962 void SchedRemainder:: 1963 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) { 1964 reset(); 1965 if (!SchedModel->hasInstrSchedModel()) 1966 return; 1967 RemainingCounts.resize(SchedModel->getNumProcResourceKinds()); 1968 for (SUnit &SU : DAG->SUnits) { 1969 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU); 1970 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC) 1971 * SchedModel->getMicroOpFactor(); 1972 for (TargetSchedModel::ProcResIter 1973 PI = SchedModel->getWriteProcResBegin(SC), 1974 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 1975 unsigned PIdx = PI->ProcResourceIdx; 1976 unsigned Factor = SchedModel->getResourceFactor(PIdx); 1977 RemainingCounts[PIdx] += (Factor * PI->Cycles); 1978 } 1979 } 1980 } 1981 1982 void SchedBoundary:: 1983 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) { 1984 reset(); 1985 DAG = dag; 1986 SchedModel = smodel; 1987 Rem = rem; 1988 if (SchedModel->hasInstrSchedModel()) { 1989 unsigned ResourceCount = SchedModel->getNumProcResourceKinds(); 1990 ReservedCyclesIndex.resize(ResourceCount); 1991 ExecutedResCounts.resize(ResourceCount); 1992 unsigned NumUnits = 0; 1993 1994 for (unsigned i = 0; i < ResourceCount; ++i) { 1995 ReservedCyclesIndex[i] = NumUnits; 1996 NumUnits += SchedModel->getProcResource(i)->NumUnits; 1997 } 1998 1999 ReservedCycles.resize(NumUnits, InvalidCycle); 2000 } 2001 } 2002 2003 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat 2004 /// these "soft stalls" differently than the hard stall cycles based on CPU 2005 /// resources and computed by checkHazard(). A fully in-order model 2006 /// (MicroOpBufferSize==0) will not make use of this since instructions are not 2007 /// available for scheduling until they are ready. However, a weaker in-order 2008 /// model may use this for heuristics. For example, if a processor has in-order 2009 /// behavior when reading certain resources, this may come into play. 2010 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) { 2011 if (!SU->isUnbuffered) 2012 return 0; 2013 2014 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle); 2015 if (ReadyCycle > CurrCycle) 2016 return ReadyCycle - CurrCycle; 2017 return 0; 2018 } 2019 2020 /// Compute the next cycle at which the given processor resource unit 2021 /// can be scheduled. 2022 unsigned SchedBoundary::getNextResourceCycleByInstance(unsigned InstanceIdx, 2023 unsigned Cycles) { 2024 unsigned NextUnreserved = ReservedCycles[InstanceIdx]; 2025 // If this resource has never been used, always return cycle zero. 2026 if (NextUnreserved == InvalidCycle) 2027 return 0; 2028 // For bottom-up scheduling add the cycles needed for the current operation. 2029 if (!isTop()) 2030 NextUnreserved += Cycles; 2031 return NextUnreserved; 2032 } 2033 2034 /// Compute the next cycle at which the given processor resource can be 2035 /// scheduled. Returns the next cycle and the index of the processor resource 2036 /// instance in the reserved cycles vector. 2037 std::pair<unsigned, unsigned> 2038 SchedBoundary::getNextResourceCycle(unsigned PIdx, unsigned Cycles) { 2039 unsigned MinNextUnreserved = InvalidCycle; 2040 unsigned InstanceIdx = 0; 2041 unsigned StartIndex = ReservedCyclesIndex[PIdx]; 2042 unsigned NumberOfInstances = SchedModel->getProcResource(PIdx)->NumUnits; 2043 assert(NumberOfInstances > 0 && 2044 "Cannot have zero instances of a ProcResource"); 2045 2046 for (unsigned I = StartIndex, End = StartIndex + NumberOfInstances; I < End; 2047 ++I) { 2048 unsigned NextUnreserved = getNextResourceCycleByInstance(I, Cycles); 2049 if (MinNextUnreserved > NextUnreserved) { 2050 InstanceIdx = I; 2051 MinNextUnreserved = NextUnreserved; 2052 } 2053 } 2054 return std::make_pair(MinNextUnreserved, InstanceIdx); 2055 } 2056 2057 /// Does this SU have a hazard within the current instruction group. 2058 /// 2059 /// The scheduler supports two modes of hazard recognition. The first is the 2060 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that 2061 /// supports highly complicated in-order reservation tables 2062 /// (ScoreboardHazardRecognizer) and arbitrary target-specific logic. 2063 /// 2064 /// The second is a streamlined mechanism that checks for hazards based on 2065 /// simple counters that the scheduler itself maintains. It explicitly checks 2066 /// for instruction dispatch limitations, including the number of micro-ops that 2067 /// can dispatch per cycle. 2068 /// 2069 /// TODO: Also check whether the SU must start a new group. 2070 bool SchedBoundary::checkHazard(SUnit *SU) { 2071 if (HazardRec->isEnabled() 2072 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) { 2073 return true; 2074 } 2075 2076 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr()); 2077 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) { 2078 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops=" 2079 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n'); 2080 return true; 2081 } 2082 2083 if (CurrMOps > 0 && 2084 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) || 2085 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) { 2086 LLVM_DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must " 2087 << (isTop() ? "begin" : "end") << " group\n"); 2088 return true; 2089 } 2090 2091 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) { 2092 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 2093 for (const MCWriteProcResEntry &PE : 2094 make_range(SchedModel->getWriteProcResBegin(SC), 2095 SchedModel->getWriteProcResEnd(SC))) { 2096 unsigned ResIdx = PE.ProcResourceIdx; 2097 unsigned Cycles = PE.Cycles; 2098 unsigned NRCycle, InstanceIdx; 2099 std::tie(NRCycle, InstanceIdx) = getNextResourceCycle(ResIdx, Cycles); 2100 if (NRCycle > CurrCycle) { 2101 #ifndef NDEBUG 2102 MaxObservedStall = std::max(Cycles, MaxObservedStall); 2103 #endif 2104 LLVM_DEBUG(dbgs() << " SU(" << SU->NodeNum << ") " 2105 << SchedModel->getResourceName(ResIdx) 2106 << '[' << InstanceIdx - ReservedCyclesIndex[ResIdx] << ']' 2107 << "=" << NRCycle << "c\n"); 2108 return true; 2109 } 2110 } 2111 } 2112 return false; 2113 } 2114 2115 // Find the unscheduled node in ReadySUs with the highest latency. 2116 unsigned SchedBoundary:: 2117 findMaxLatency(ArrayRef<SUnit*> ReadySUs) { 2118 SUnit *LateSU = nullptr; 2119 unsigned RemLatency = 0; 2120 for (SUnit *SU : ReadySUs) { 2121 unsigned L = getUnscheduledLatency(SU); 2122 if (L > RemLatency) { 2123 RemLatency = L; 2124 LateSU = SU; 2125 } 2126 } 2127 if (LateSU) { 2128 LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency SU(" 2129 << LateSU->NodeNum << ") " << RemLatency << "c\n"); 2130 } 2131 return RemLatency; 2132 } 2133 2134 // Count resources in this zone and the remaining unscheduled 2135 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical 2136 // resource index, or zero if the zone is issue limited. 2137 unsigned SchedBoundary:: 2138 getOtherResourceCount(unsigned &OtherCritIdx) { 2139 OtherCritIdx = 0; 2140 if (!SchedModel->hasInstrSchedModel()) 2141 return 0; 2142 2143 unsigned OtherCritCount = Rem->RemIssueCount 2144 + (RetiredMOps * SchedModel->getMicroOpFactor()); 2145 LLVM_DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: " 2146 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n'); 2147 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds(); 2148 PIdx != PEnd; ++PIdx) { 2149 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx]; 2150 if (OtherCount > OtherCritCount) { 2151 OtherCritCount = OtherCount; 2152 OtherCritIdx = PIdx; 2153 } 2154 } 2155 if (OtherCritIdx) { 2156 LLVM_DEBUG( 2157 dbgs() << " " << Available.getName() << " + Remain CritRes: " 2158 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx) 2159 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n"); 2160 } 2161 return OtherCritCount; 2162 } 2163 2164 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle, bool InPQueue, 2165 unsigned Idx) { 2166 assert(SU->getInstr() && "Scheduled SUnit must have instr"); 2167 2168 #ifndef NDEBUG 2169 // ReadyCycle was been bumped up to the CurrCycle when this node was 2170 // scheduled, but CurrCycle may have been eagerly advanced immediately after 2171 // scheduling, so may now be greater than ReadyCycle. 2172 if (ReadyCycle > CurrCycle) 2173 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall); 2174 #endif 2175 2176 if (ReadyCycle < MinReadyCycle) 2177 MinReadyCycle = ReadyCycle; 2178 2179 // Check for interlocks first. For the purpose of other heuristics, an 2180 // instruction that cannot issue appears as if it's not in the ReadyQueue. 2181 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0; 2182 bool HazardDetected = (!IsBuffered && ReadyCycle > CurrCycle) || 2183 checkHazard(SU) || (Available.size() >= ReadyListLimit); 2184 2185 if (!HazardDetected) { 2186 Available.push(SU); 2187 2188 if (InPQueue) 2189 Pending.remove(Pending.begin() + Idx); 2190 return; 2191 } 2192 2193 if (!InPQueue) 2194 Pending.push(SU); 2195 } 2196 2197 /// Move the boundary of scheduled code by one cycle. 2198 void SchedBoundary::bumpCycle(unsigned NextCycle) { 2199 if (SchedModel->getMicroOpBufferSize() == 0) { 2200 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() && 2201 "MinReadyCycle uninitialized"); 2202 if (MinReadyCycle > NextCycle) 2203 NextCycle = MinReadyCycle; 2204 } 2205 // Update the current micro-ops, which will issue in the next cycle. 2206 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle); 2207 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps; 2208 2209 // Decrement DependentLatency based on the next cycle. 2210 if ((NextCycle - CurrCycle) > DependentLatency) 2211 DependentLatency = 0; 2212 else 2213 DependentLatency -= (NextCycle - CurrCycle); 2214 2215 if (!HazardRec->isEnabled()) { 2216 // Bypass HazardRec virtual calls. 2217 CurrCycle = NextCycle; 2218 } else { 2219 // Bypass getHazardType calls in case of long latency. 2220 for (; CurrCycle != NextCycle; ++CurrCycle) { 2221 if (isTop()) 2222 HazardRec->AdvanceCycle(); 2223 else 2224 HazardRec->RecedeCycle(); 2225 } 2226 } 2227 CheckPending = true; 2228 IsResourceLimited = 2229 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(), 2230 getScheduledLatency(), true); 2231 2232 LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() 2233 << '\n'); 2234 } 2235 2236 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) { 2237 ExecutedResCounts[PIdx] += Count; 2238 if (ExecutedResCounts[PIdx] > MaxExecutedResCount) 2239 MaxExecutedResCount = ExecutedResCounts[PIdx]; 2240 } 2241 2242 /// Add the given processor resource to this scheduled zone. 2243 /// 2244 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles 2245 /// during which this resource is consumed. 2246 /// 2247 /// \return the next cycle at which the instruction may execute without 2248 /// oversubscribing resources. 2249 unsigned SchedBoundary:: 2250 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) { 2251 unsigned Factor = SchedModel->getResourceFactor(PIdx); 2252 unsigned Count = Factor * Cycles; 2253 LLVM_DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx) << " +" 2254 << Cycles << "x" << Factor << "u\n"); 2255 2256 // Update Executed resources counts. 2257 incExecutedResources(PIdx, Count); 2258 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted"); 2259 Rem->RemainingCounts[PIdx] -= Count; 2260 2261 // Check if this resource exceeds the current critical resource. If so, it 2262 // becomes the critical resource. 2263 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) { 2264 ZoneCritResIdx = PIdx; 2265 LLVM_DEBUG(dbgs() << " *** Critical resource " 2266 << SchedModel->getResourceName(PIdx) << ": " 2267 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() 2268 << "c\n"); 2269 } 2270 // For reserved resources, record the highest cycle using the resource. 2271 unsigned NextAvailable, InstanceIdx; 2272 std::tie(NextAvailable, InstanceIdx) = getNextResourceCycle(PIdx, Cycles); 2273 if (NextAvailable > CurrCycle) { 2274 LLVM_DEBUG(dbgs() << " Resource conflict: " 2275 << SchedModel->getResourceName(PIdx) 2276 << '[' << InstanceIdx - ReservedCyclesIndex[PIdx] << ']' 2277 << " reserved until @" << NextAvailable << "\n"); 2278 } 2279 return NextAvailable; 2280 } 2281 2282 /// Move the boundary of scheduled code by one SUnit. 2283 void SchedBoundary::bumpNode(SUnit *SU) { 2284 // Update the reservation table. 2285 if (HazardRec->isEnabled()) { 2286 if (!isTop() && SU->isCall) { 2287 // Calls are scheduled with their preceding instructions. For bottom-up 2288 // scheduling, clear the pipeline state before emitting. 2289 HazardRec->Reset(); 2290 } 2291 HazardRec->EmitInstruction(SU); 2292 // Scheduling an instruction may have made pending instructions available. 2293 CheckPending = true; 2294 } 2295 // checkHazard should prevent scheduling multiple instructions per cycle that 2296 // exceed the issue width. 2297 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 2298 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr()); 2299 assert( 2300 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) && 2301 "Cannot schedule this instruction's MicroOps in the current cycle."); 2302 2303 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle); 2304 LLVM_DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n"); 2305 2306 unsigned NextCycle = CurrCycle; 2307 switch (SchedModel->getMicroOpBufferSize()) { 2308 case 0: 2309 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue"); 2310 break; 2311 case 1: 2312 if (ReadyCycle > NextCycle) { 2313 NextCycle = ReadyCycle; 2314 LLVM_DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n"); 2315 } 2316 break; 2317 default: 2318 // We don't currently model the OOO reorder buffer, so consider all 2319 // scheduled MOps to be "retired". We do loosely model in-order resource 2320 // latency. If this instruction uses an in-order resource, account for any 2321 // likely stall cycles. 2322 if (SU->isUnbuffered && ReadyCycle > NextCycle) 2323 NextCycle = ReadyCycle; 2324 break; 2325 } 2326 RetiredMOps += IncMOps; 2327 2328 // Update resource counts and critical resource. 2329 if (SchedModel->hasInstrSchedModel()) { 2330 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor(); 2331 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted"); 2332 Rem->RemIssueCount -= DecRemIssue; 2333 if (ZoneCritResIdx) { 2334 // Scale scheduled micro-ops for comparing with the critical resource. 2335 unsigned ScaledMOps = 2336 RetiredMOps * SchedModel->getMicroOpFactor(); 2337 2338 // If scaled micro-ops are now more than the previous critical resource by 2339 // a full cycle, then micro-ops issue becomes critical. 2340 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx)) 2341 >= (int)SchedModel->getLatencyFactor()) { 2342 ZoneCritResIdx = 0; 2343 LLVM_DEBUG(dbgs() << " *** Critical resource NumMicroOps: " 2344 << ScaledMOps / SchedModel->getLatencyFactor() 2345 << "c\n"); 2346 } 2347 } 2348 for (TargetSchedModel::ProcResIter 2349 PI = SchedModel->getWriteProcResBegin(SC), 2350 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 2351 unsigned RCycle = 2352 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle); 2353 if (RCycle > NextCycle) 2354 NextCycle = RCycle; 2355 } 2356 if (SU->hasReservedResource) { 2357 // For reserved resources, record the highest cycle using the resource. 2358 // For top-down scheduling, this is the cycle in which we schedule this 2359 // instruction plus the number of cycles the operations reserves the 2360 // resource. For bottom-up is it simply the instruction's cycle. 2361 for (TargetSchedModel::ProcResIter 2362 PI = SchedModel->getWriteProcResBegin(SC), 2363 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 2364 unsigned PIdx = PI->ProcResourceIdx; 2365 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) { 2366 unsigned ReservedUntil, InstanceIdx; 2367 std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(PIdx, 0); 2368 if (isTop()) { 2369 ReservedCycles[InstanceIdx] = 2370 std::max(ReservedUntil, NextCycle + PI->Cycles); 2371 } else 2372 ReservedCycles[InstanceIdx] = NextCycle; 2373 } 2374 } 2375 } 2376 } 2377 // Update ExpectedLatency and DependentLatency. 2378 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency; 2379 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency; 2380 if (SU->getDepth() > TopLatency) { 2381 TopLatency = SU->getDepth(); 2382 LLVM_DEBUG(dbgs() << " " << Available.getName() << " TopLatency SU(" 2383 << SU->NodeNum << ") " << TopLatency << "c\n"); 2384 } 2385 if (SU->getHeight() > BotLatency) { 2386 BotLatency = SU->getHeight(); 2387 LLVM_DEBUG(dbgs() << " " << Available.getName() << " BotLatency SU(" 2388 << SU->NodeNum << ") " << BotLatency << "c\n"); 2389 } 2390 // If we stall for any reason, bump the cycle. 2391 if (NextCycle > CurrCycle) 2392 bumpCycle(NextCycle); 2393 else 2394 // After updating ZoneCritResIdx and ExpectedLatency, check if we're 2395 // resource limited. If a stall occurred, bumpCycle does this. 2396 IsResourceLimited = 2397 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(), 2398 getScheduledLatency(), true); 2399 2400 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle 2401 // resets CurrMOps. Loop to handle instructions with more MOps than issue in 2402 // one cycle. Since we commonly reach the max MOps here, opportunistically 2403 // bump the cycle to avoid uselessly checking everything in the readyQ. 2404 CurrMOps += IncMOps; 2405 2406 // Bump the cycle count for issue group constraints. 2407 // This must be done after NextCycle has been adjust for all other stalls. 2408 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set 2409 // currCycle to X. 2410 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) || 2411 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) { 2412 LLVM_DEBUG(dbgs() << " Bump cycle to " << (isTop() ? "end" : "begin") 2413 << " group\n"); 2414 bumpCycle(++NextCycle); 2415 } 2416 2417 while (CurrMOps >= SchedModel->getIssueWidth()) { 2418 LLVM_DEBUG(dbgs() << " *** Max MOps " << CurrMOps << " at cycle " 2419 << CurrCycle << '\n'); 2420 bumpCycle(++NextCycle); 2421 } 2422 LLVM_DEBUG(dumpScheduledState()); 2423 } 2424 2425 /// Release pending ready nodes in to the available queue. This makes them 2426 /// visible to heuristics. 2427 void SchedBoundary::releasePending() { 2428 // If the available queue is empty, it is safe to reset MinReadyCycle. 2429 if (Available.empty()) 2430 MinReadyCycle = std::numeric_limits<unsigned>::max(); 2431 2432 // Check to see if any of the pending instructions are ready to issue. If 2433 // so, add them to the available queue. 2434 for (unsigned I = 0, E = Pending.size(); I < E; ++I) { 2435 SUnit *SU = *(Pending.begin() + I); 2436 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle; 2437 2438 if (ReadyCycle < MinReadyCycle) 2439 MinReadyCycle = ReadyCycle; 2440 2441 if (Available.size() >= ReadyListLimit) 2442 break; 2443 2444 releaseNode(SU, ReadyCycle, true, I); 2445 if (E != Pending.size()) { 2446 --I; 2447 --E; 2448 } 2449 } 2450 CheckPending = false; 2451 } 2452 2453 /// Remove SU from the ready set for this boundary. 2454 void SchedBoundary::removeReady(SUnit *SU) { 2455 if (Available.isInQueue(SU)) 2456 Available.remove(Available.find(SU)); 2457 else { 2458 assert(Pending.isInQueue(SU) && "bad ready count"); 2459 Pending.remove(Pending.find(SU)); 2460 } 2461 } 2462 2463 /// If this queue only has one ready candidate, return it. As a side effect, 2464 /// defer any nodes that now hit a hazard, and advance the cycle until at least 2465 /// one node is ready. If multiple instructions are ready, return NULL. 2466 SUnit *SchedBoundary::pickOnlyChoice() { 2467 if (CheckPending) 2468 releasePending(); 2469 2470 // Defer any ready instrs that now have a hazard. 2471 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) { 2472 if (checkHazard(*I)) { 2473 Pending.push(*I); 2474 I = Available.remove(I); 2475 continue; 2476 } 2477 ++I; 2478 } 2479 for (unsigned i = 0; Available.empty(); ++i) { 2480 // FIXME: Re-enable assert once PR20057 is resolved. 2481 // assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) && 2482 // "permanent hazard"); 2483 (void)i; 2484 bumpCycle(CurrCycle + 1); 2485 releasePending(); 2486 } 2487 2488 LLVM_DEBUG(Pending.dump()); 2489 LLVM_DEBUG(Available.dump()); 2490 2491 if (Available.size() == 1) 2492 return *Available.begin(); 2493 return nullptr; 2494 } 2495 2496 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2497 // This is useful information to dump after bumpNode. 2498 // Note that the Queue contents are more useful before pickNodeFromQueue. 2499 LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const { 2500 unsigned ResFactor; 2501 unsigned ResCount; 2502 if (ZoneCritResIdx) { 2503 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx); 2504 ResCount = getResourceCount(ZoneCritResIdx); 2505 } else { 2506 ResFactor = SchedModel->getMicroOpFactor(); 2507 ResCount = RetiredMOps * ResFactor; 2508 } 2509 unsigned LFactor = SchedModel->getLatencyFactor(); 2510 dbgs() << Available.getName() << " @" << CurrCycle << "c\n" 2511 << " Retired: " << RetiredMOps; 2512 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c"; 2513 dbgs() << "\n Critical: " << ResCount / LFactor << "c, " 2514 << ResCount / ResFactor << " " 2515 << SchedModel->getResourceName(ZoneCritResIdx) 2516 << "\n ExpectedLatency: " << ExpectedLatency << "c\n" 2517 << (IsResourceLimited ? " - Resource" : " - Latency") 2518 << " limited.\n"; 2519 } 2520 #endif 2521 2522 //===----------------------------------------------------------------------===// 2523 // GenericScheduler - Generic implementation of MachineSchedStrategy. 2524 //===----------------------------------------------------------------------===// 2525 2526 void GenericSchedulerBase::SchedCandidate:: 2527 initResourceDelta(const ScheduleDAGMI *DAG, 2528 const TargetSchedModel *SchedModel) { 2529 if (!Policy.ReduceResIdx && !Policy.DemandResIdx) 2530 return; 2531 2532 const MCSchedClassDesc *SC = DAG->getSchedClass(SU); 2533 for (TargetSchedModel::ProcResIter 2534 PI = SchedModel->getWriteProcResBegin(SC), 2535 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { 2536 if (PI->ProcResourceIdx == Policy.ReduceResIdx) 2537 ResDelta.CritResources += PI->Cycles; 2538 if (PI->ProcResourceIdx == Policy.DemandResIdx) 2539 ResDelta.DemandedResources += PI->Cycles; 2540 } 2541 } 2542 2543 /// Compute remaining latency. We need this both to determine whether the 2544 /// overall schedule has become latency-limited and whether the instructions 2545 /// outside this zone are resource or latency limited. 2546 /// 2547 /// The "dependent" latency is updated incrementally during scheduling as the 2548 /// max height/depth of scheduled nodes minus the cycles since it was 2549 /// scheduled: 2550 /// DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone 2551 /// 2552 /// The "independent" latency is the max ready queue depth: 2553 /// ILat = max N.depth for N in Available|Pending 2554 /// 2555 /// RemainingLatency is the greater of independent and dependent latency. 2556 /// 2557 /// These computations are expensive, especially in DAGs with many edges, so 2558 /// only do them if necessary. 2559 static unsigned computeRemLatency(SchedBoundary &CurrZone) { 2560 unsigned RemLatency = CurrZone.getDependentLatency(); 2561 RemLatency = std::max(RemLatency, 2562 CurrZone.findMaxLatency(CurrZone.Available.elements())); 2563 RemLatency = std::max(RemLatency, 2564 CurrZone.findMaxLatency(CurrZone.Pending.elements())); 2565 return RemLatency; 2566 } 2567 2568 /// Returns true if the current cycle plus remaning latency is greater than 2569 /// the critical path in the scheduling region. 2570 bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy, 2571 SchedBoundary &CurrZone, 2572 bool ComputeRemLatency, 2573 unsigned &RemLatency) const { 2574 // The current cycle is already greater than the critical path, so we are 2575 // already latency limited and don't need to compute the remaining latency. 2576 if (CurrZone.getCurrCycle() > Rem.CriticalPath) 2577 return true; 2578 2579 // If we haven't scheduled anything yet, then we aren't latency limited. 2580 if (CurrZone.getCurrCycle() == 0) 2581 return false; 2582 2583 if (ComputeRemLatency) 2584 RemLatency = computeRemLatency(CurrZone); 2585 2586 return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath; 2587 } 2588 2589 /// Set the CandPolicy given a scheduling zone given the current resources and 2590 /// latencies inside and outside the zone. 2591 void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA, 2592 SchedBoundary &CurrZone, 2593 SchedBoundary *OtherZone) { 2594 // Apply preemptive heuristics based on the total latency and resources 2595 // inside and outside this zone. Potential stalls should be considered before 2596 // following this policy. 2597 2598 // Compute the critical resource outside the zone. 2599 unsigned OtherCritIdx = 0; 2600 unsigned OtherCount = 2601 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0; 2602 2603 bool OtherResLimited = false; 2604 unsigned RemLatency = 0; 2605 bool RemLatencyComputed = false; 2606 if (SchedModel->hasInstrSchedModel() && OtherCount != 0) { 2607 RemLatency = computeRemLatency(CurrZone); 2608 RemLatencyComputed = true; 2609 OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(), 2610 OtherCount, RemLatency, false); 2611 } 2612 2613 // Schedule aggressively for latency in PostRA mode. We don't check for 2614 // acyclic latency during PostRA, and highly out-of-order processors will 2615 // skip PostRA scheduling. 2616 if (!OtherResLimited && 2617 (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed, 2618 RemLatency))) { 2619 Policy.ReduceLatency |= true; 2620 LLVM_DEBUG(dbgs() << " " << CurrZone.Available.getName() 2621 << " RemainingLatency " << RemLatency << " + " 2622 << CurrZone.getCurrCycle() << "c > CritPath " 2623 << Rem.CriticalPath << "\n"); 2624 } 2625 // If the same resource is limiting inside and outside the zone, do nothing. 2626 if (CurrZone.getZoneCritResIdx() == OtherCritIdx) 2627 return; 2628 2629 LLVM_DEBUG(if (CurrZone.isResourceLimited()) { 2630 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: " 2631 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n"; 2632 } if (OtherResLimited) dbgs() 2633 << " RemainingLimit: " 2634 << SchedModel->getResourceName(OtherCritIdx) << "\n"; 2635 if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs() 2636 << " Latency limited both directions.\n"); 2637 2638 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx) 2639 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx(); 2640 2641 if (OtherResLimited) 2642 Policy.DemandResIdx = OtherCritIdx; 2643 } 2644 2645 #ifndef NDEBUG 2646 const char *GenericSchedulerBase::getReasonStr( 2647 GenericSchedulerBase::CandReason Reason) { 2648 switch (Reason) { 2649 case NoCand: return "NOCAND "; 2650 case Only1: return "ONLY1 "; 2651 case PhysReg: return "PHYS-REG "; 2652 case RegExcess: return "REG-EXCESS"; 2653 case RegCritical: return "REG-CRIT "; 2654 case Stall: return "STALL "; 2655 case Cluster: return "CLUSTER "; 2656 case Weak: return "WEAK "; 2657 case RegMax: return "REG-MAX "; 2658 case ResourceReduce: return "RES-REDUCE"; 2659 case ResourceDemand: return "RES-DEMAND"; 2660 case TopDepthReduce: return "TOP-DEPTH "; 2661 case TopPathReduce: return "TOP-PATH "; 2662 case BotHeightReduce:return "BOT-HEIGHT"; 2663 case BotPathReduce: return "BOT-PATH "; 2664 case NextDefUse: return "DEF-USE "; 2665 case NodeOrder: return "ORDER "; 2666 }; 2667 llvm_unreachable("Unknown reason!"); 2668 } 2669 2670 void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) { 2671 PressureChange P; 2672 unsigned ResIdx = 0; 2673 unsigned Latency = 0; 2674 switch (Cand.Reason) { 2675 default: 2676 break; 2677 case RegExcess: 2678 P = Cand.RPDelta.Excess; 2679 break; 2680 case RegCritical: 2681 P = Cand.RPDelta.CriticalMax; 2682 break; 2683 case RegMax: 2684 P = Cand.RPDelta.CurrentMax; 2685 break; 2686 case ResourceReduce: 2687 ResIdx = Cand.Policy.ReduceResIdx; 2688 break; 2689 case ResourceDemand: 2690 ResIdx = Cand.Policy.DemandResIdx; 2691 break; 2692 case TopDepthReduce: 2693 Latency = Cand.SU->getDepth(); 2694 break; 2695 case TopPathReduce: 2696 Latency = Cand.SU->getHeight(); 2697 break; 2698 case BotHeightReduce: 2699 Latency = Cand.SU->getHeight(); 2700 break; 2701 case BotPathReduce: 2702 Latency = Cand.SU->getDepth(); 2703 break; 2704 } 2705 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason); 2706 if (P.isValid()) 2707 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet()) 2708 << ":" << P.getUnitInc() << " "; 2709 else 2710 dbgs() << " "; 2711 if (ResIdx) 2712 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " "; 2713 else 2714 dbgs() << " "; 2715 if (Latency) 2716 dbgs() << " " << Latency << " cycles "; 2717 else 2718 dbgs() << " "; 2719 dbgs() << '\n'; 2720 } 2721 #endif 2722 2723 namespace llvm { 2724 /// Return true if this heuristic determines order. 2725 bool tryLess(int TryVal, int CandVal, 2726 GenericSchedulerBase::SchedCandidate &TryCand, 2727 GenericSchedulerBase::SchedCandidate &Cand, 2728 GenericSchedulerBase::CandReason Reason) { 2729 if (TryVal < CandVal) { 2730 TryCand.Reason = Reason; 2731 return true; 2732 } 2733 if (TryVal > CandVal) { 2734 if (Cand.Reason > Reason) 2735 Cand.Reason = Reason; 2736 return true; 2737 } 2738 return false; 2739 } 2740 2741 bool tryGreater(int TryVal, int CandVal, 2742 GenericSchedulerBase::SchedCandidate &TryCand, 2743 GenericSchedulerBase::SchedCandidate &Cand, 2744 GenericSchedulerBase::CandReason Reason) { 2745 if (TryVal > CandVal) { 2746 TryCand.Reason = Reason; 2747 return true; 2748 } 2749 if (TryVal < CandVal) { 2750 if (Cand.Reason > Reason) 2751 Cand.Reason = Reason; 2752 return true; 2753 } 2754 return false; 2755 } 2756 2757 bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, 2758 GenericSchedulerBase::SchedCandidate &Cand, 2759 SchedBoundary &Zone) { 2760 if (Zone.isTop()) { 2761 // Prefer the candidate with the lesser depth, but only if one of them has 2762 // depth greater than the total latency scheduled so far, otherwise either 2763 // of them could be scheduled now with no stall. 2764 if (std::max(TryCand.SU->getDepth(), Cand.SU->getDepth()) > 2765 Zone.getScheduledLatency()) { 2766 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(), 2767 TryCand, Cand, GenericSchedulerBase::TopDepthReduce)) 2768 return true; 2769 } 2770 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(), 2771 TryCand, Cand, GenericSchedulerBase::TopPathReduce)) 2772 return true; 2773 } else { 2774 // Prefer the candidate with the lesser height, but only if one of them has 2775 // height greater than the total latency scheduled so far, otherwise either 2776 // of them could be scheduled now with no stall. 2777 if (std::max(TryCand.SU->getHeight(), Cand.SU->getHeight()) > 2778 Zone.getScheduledLatency()) { 2779 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(), 2780 TryCand, Cand, GenericSchedulerBase::BotHeightReduce)) 2781 return true; 2782 } 2783 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(), 2784 TryCand, Cand, GenericSchedulerBase::BotPathReduce)) 2785 return true; 2786 } 2787 return false; 2788 } 2789 } // end namespace llvm 2790 2791 static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) { 2792 LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ") 2793 << GenericSchedulerBase::getReasonStr(Reason) << '\n'); 2794 } 2795 2796 static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) { 2797 tracePick(Cand.Reason, Cand.AtTop); 2798 } 2799 2800 void GenericScheduler::initialize(ScheduleDAGMI *dag) { 2801 assert(dag->hasVRegLiveness() && 2802 "(PreRA)GenericScheduler needs vreg liveness"); 2803 DAG = static_cast<ScheduleDAGMILive*>(dag); 2804 SchedModel = DAG->getSchedModel(); 2805 TRI = DAG->TRI; 2806 2807 if (RegionPolicy.ComputeDFSResult) 2808 DAG->computeDFSResult(); 2809 2810 Rem.init(DAG, SchedModel); 2811 Top.init(DAG, SchedModel, &Rem); 2812 Bot.init(DAG, SchedModel, &Rem); 2813 2814 // Initialize resource counts. 2815 2816 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or 2817 // are disabled, then these HazardRecs will be disabled. 2818 const InstrItineraryData *Itin = SchedModel->getInstrItineraries(); 2819 if (!Top.HazardRec) { 2820 Top.HazardRec = 2821 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer( 2822 Itin, DAG); 2823 } 2824 if (!Bot.HazardRec) { 2825 Bot.HazardRec = 2826 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer( 2827 Itin, DAG); 2828 } 2829 TopCand.SU = nullptr; 2830 BotCand.SU = nullptr; 2831 } 2832 2833 /// Initialize the per-region scheduling policy. 2834 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin, 2835 MachineBasicBlock::iterator End, 2836 unsigned NumRegionInstrs) { 2837 const MachineFunction &MF = *Begin->getMF(); 2838 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering(); 2839 2840 // Avoid setting up the register pressure tracker for small regions to save 2841 // compile time. As a rough heuristic, only track pressure when the number of 2842 // schedulable instructions exceeds half the integer register file. 2843 RegionPolicy.ShouldTrackPressure = true; 2844 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) { 2845 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT; 2846 if (TLI->isTypeLegal(LegalIntVT)) { 2847 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs( 2848 TLI->getRegClassFor(LegalIntVT)); 2849 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2); 2850 } 2851 } 2852 2853 // For generic targets, we default to bottom-up, because it's simpler and more 2854 // compile-time optimizations have been implemented in that direction. 2855 RegionPolicy.OnlyBottomUp = true; 2856 2857 // Allow the subtarget to override default policy. 2858 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs); 2859 2860 // After subtarget overrides, apply command line options. 2861 if (!EnableRegPressure) { 2862 RegionPolicy.ShouldTrackPressure = false; 2863 RegionPolicy.ShouldTrackLaneMasks = false; 2864 } 2865 2866 // Check -misched-topdown/bottomup can force or unforce scheduling direction. 2867 // e.g. -misched-bottomup=false allows scheduling in both directions. 2868 assert((!ForceTopDown || !ForceBottomUp) && 2869 "-misched-topdown incompatible with -misched-bottomup"); 2870 if (ForceBottomUp.getNumOccurrences() > 0) { 2871 RegionPolicy.OnlyBottomUp = ForceBottomUp; 2872 if (RegionPolicy.OnlyBottomUp) 2873 RegionPolicy.OnlyTopDown = false; 2874 } 2875 if (ForceTopDown.getNumOccurrences() > 0) { 2876 RegionPolicy.OnlyTopDown = ForceTopDown; 2877 if (RegionPolicy.OnlyTopDown) 2878 RegionPolicy.OnlyBottomUp = false; 2879 } 2880 } 2881 2882 void GenericScheduler::dumpPolicy() const { 2883 // Cannot completely remove virtual function even in release mode. 2884 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2885 dbgs() << "GenericScheduler RegionPolicy: " 2886 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure 2887 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown 2888 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp 2889 << "\n"; 2890 #endif 2891 } 2892 2893 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic 2894 /// critical path by more cycles than it takes to drain the instruction buffer. 2895 /// We estimate an upper bounds on in-flight instructions as: 2896 /// 2897 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height ) 2898 /// InFlightIterations = AcyclicPath / CyclesPerIteration 2899 /// InFlightResources = InFlightIterations * LoopResources 2900 /// 2901 /// TODO: Check execution resources in addition to IssueCount. 2902 void GenericScheduler::checkAcyclicLatency() { 2903 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath) 2904 return; 2905 2906 // Scaled number of cycles per loop iteration. 2907 unsigned IterCount = 2908 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(), 2909 Rem.RemIssueCount); 2910 // Scaled acyclic critical path. 2911 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor(); 2912 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop 2913 unsigned InFlightCount = 2914 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount; 2915 unsigned BufferLimit = 2916 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor(); 2917 2918 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit; 2919 2920 LLVM_DEBUG( 2921 dbgs() << "IssueCycles=" 2922 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c " 2923 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor() 2924 << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount 2925 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor() 2926 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n"; 2927 if (Rem.IsAcyclicLatencyLimited) dbgs() << " ACYCLIC LATENCY LIMIT\n"); 2928 } 2929 2930 void GenericScheduler::registerRoots() { 2931 Rem.CriticalPath = DAG->ExitSU.getDepth(); 2932 2933 // Some roots may not feed into ExitSU. Check all of them in case. 2934 for (const SUnit *SU : Bot.Available) { 2935 if (SU->getDepth() > Rem.CriticalPath) 2936 Rem.CriticalPath = SU->getDepth(); 2937 } 2938 LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n'); 2939 if (DumpCriticalPathLength) { 2940 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n"; 2941 } 2942 2943 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) { 2944 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath(); 2945 checkAcyclicLatency(); 2946 } 2947 } 2948 2949 namespace llvm { 2950 bool tryPressure(const PressureChange &TryP, 2951 const PressureChange &CandP, 2952 GenericSchedulerBase::SchedCandidate &TryCand, 2953 GenericSchedulerBase::SchedCandidate &Cand, 2954 GenericSchedulerBase::CandReason Reason, 2955 const TargetRegisterInfo *TRI, 2956 const MachineFunction &MF) { 2957 // If one candidate decreases and the other increases, go with it. 2958 // Invalid candidates have UnitInc==0. 2959 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand, 2960 Reason)) { 2961 return true; 2962 } 2963 // Do not compare the magnitude of pressure changes between top and bottom 2964 // boundary. 2965 if (Cand.AtTop != TryCand.AtTop) 2966 return false; 2967 2968 // If both candidates affect the same set in the same boundary, go with the 2969 // smallest increase. 2970 unsigned TryPSet = TryP.getPSetOrMax(); 2971 unsigned CandPSet = CandP.getPSetOrMax(); 2972 if (TryPSet == CandPSet) { 2973 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand, 2974 Reason); 2975 } 2976 2977 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) : 2978 std::numeric_limits<int>::max(); 2979 2980 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) : 2981 std::numeric_limits<int>::max(); 2982 2983 // If the candidates are decreasing pressure, reverse priority. 2984 if (TryP.getUnitInc() < 0) 2985 std::swap(TryRank, CandRank); 2986 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason); 2987 } 2988 2989 unsigned getWeakLeft(const SUnit *SU, bool isTop) { 2990 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft; 2991 } 2992 2993 /// Minimize physical register live ranges. Regalloc wants them adjacent to 2994 /// their physreg def/use. 2995 /// 2996 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf 2997 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled 2998 /// with the operation that produces or consumes the physreg. We'll do this when 2999 /// regalloc has support for parallel copies. 3000 int biasPhysReg(const SUnit *SU, bool isTop) { 3001 const MachineInstr *MI = SU->getInstr(); 3002 3003 if (MI->isCopy()) { 3004 unsigned ScheduledOper = isTop ? 1 : 0; 3005 unsigned UnscheduledOper = isTop ? 0 : 1; 3006 // If we have already scheduled the physreg produce/consumer, immediately 3007 // schedule the copy. 3008 if (Register::isPhysicalRegister(MI->getOperand(ScheduledOper).getReg())) 3009 return 1; 3010 // If the physreg is at the boundary, defer it. Otherwise schedule it 3011 // immediately to free the dependent. We can hoist the copy later. 3012 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft; 3013 if (Register::isPhysicalRegister(MI->getOperand(UnscheduledOper).getReg())) 3014 return AtBoundary ? -1 : 1; 3015 } 3016 3017 if (MI->isMoveImmediate()) { 3018 // If we have a move immediate and all successors have been assigned, bias 3019 // towards scheduling this later. Make sure all register defs are to 3020 // physical registers. 3021 bool DoBias = true; 3022 for (const MachineOperand &Op : MI->defs()) { 3023 if (Op.isReg() && !Register::isPhysicalRegister(Op.getReg())) { 3024 DoBias = false; 3025 break; 3026 } 3027 } 3028 3029 if (DoBias) 3030 return isTop ? -1 : 1; 3031 } 3032 3033 return 0; 3034 } 3035 } // end namespace llvm 3036 3037 void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU, 3038 bool AtTop, 3039 const RegPressureTracker &RPTracker, 3040 RegPressureTracker &TempTracker) { 3041 Cand.SU = SU; 3042 Cand.AtTop = AtTop; 3043 if (DAG->isTrackingPressure()) { 3044 if (AtTop) { 3045 TempTracker.getMaxDownwardPressureDelta( 3046 Cand.SU->getInstr(), 3047 Cand.RPDelta, 3048 DAG->getRegionCriticalPSets(), 3049 DAG->getRegPressure().MaxSetPressure); 3050 } else { 3051 if (VerifyScheduling) { 3052 TempTracker.getMaxUpwardPressureDelta( 3053 Cand.SU->getInstr(), 3054 &DAG->getPressureDiff(Cand.SU), 3055 Cand.RPDelta, 3056 DAG->getRegionCriticalPSets(), 3057 DAG->getRegPressure().MaxSetPressure); 3058 } else { 3059 RPTracker.getUpwardPressureDelta( 3060 Cand.SU->getInstr(), 3061 DAG->getPressureDiff(Cand.SU), 3062 Cand.RPDelta, 3063 DAG->getRegionCriticalPSets(), 3064 DAG->getRegPressure().MaxSetPressure); 3065 } 3066 } 3067 } 3068 LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs() 3069 << " Try SU(" << Cand.SU->NodeNum << ") " 3070 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":" 3071 << Cand.RPDelta.Excess.getUnitInc() << "\n"); 3072 } 3073 3074 /// Apply a set of heuristics to a new candidate. Heuristics are currently 3075 /// hierarchical. This may be more efficient than a graduated cost model because 3076 /// we don't need to evaluate all aspects of the model for each node in the 3077 /// queue. But it's really done to make the heuristics easier to debug and 3078 /// statistically analyze. 3079 /// 3080 /// \param Cand provides the policy and current best candidate. 3081 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized. 3082 /// \param Zone describes the scheduled zone that we are extending, or nullptr 3083 // if Cand is from a different zone than TryCand. 3084 void GenericScheduler::tryCandidate(SchedCandidate &Cand, 3085 SchedCandidate &TryCand, 3086 SchedBoundary *Zone) const { 3087 // Initialize the candidate if needed. 3088 if (!Cand.isValid()) { 3089 TryCand.Reason = NodeOrder; 3090 return; 3091 } 3092 3093 // Bias PhysReg Defs and copies to their uses and defined respectively. 3094 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop), 3095 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg)) 3096 return; 3097 3098 // Avoid exceeding the target's limit. 3099 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess, 3100 Cand.RPDelta.Excess, 3101 TryCand, Cand, RegExcess, TRI, 3102 DAG->MF)) 3103 return; 3104 3105 // Avoid increasing the max critical pressure in the scheduled region. 3106 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax, 3107 Cand.RPDelta.CriticalMax, 3108 TryCand, Cand, RegCritical, TRI, 3109 DAG->MF)) 3110 return; 3111 3112 // We only compare a subset of features when comparing nodes between 3113 // Top and Bottom boundary. Some properties are simply incomparable, in many 3114 // other instances we should only override the other boundary if something 3115 // is a clear good pick on one boundary. Skip heuristics that are more 3116 // "tie-breaking" in nature. 3117 bool SameBoundary = Zone != nullptr; 3118 if (SameBoundary) { 3119 // For loops that are acyclic path limited, aggressively schedule for 3120 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal 3121 // heuristics to take precedence. 3122 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() && 3123 tryLatency(TryCand, Cand, *Zone)) 3124 return; 3125 3126 // Prioritize instructions that read unbuffered resources by stall cycles. 3127 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU), 3128 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall)) 3129 return; 3130 } 3131 3132 // Keep clustered nodes together to encourage downstream peephole 3133 // optimizations which may reduce resource requirements. 3134 // 3135 // This is a best effort to set things up for a post-RA pass. Optimizations 3136 // like generating loads of multiple registers should ideally be done within 3137 // the scheduler pass by combining the loads during DAG postprocessing. 3138 const SUnit *CandNextClusterSU = 3139 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred(); 3140 const SUnit *TryCandNextClusterSU = 3141 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred(); 3142 if (tryGreater(TryCand.SU == TryCandNextClusterSU, 3143 Cand.SU == CandNextClusterSU, 3144 TryCand, Cand, Cluster)) 3145 return; 3146 3147 if (SameBoundary) { 3148 // Weak edges are for clustering and other constraints. 3149 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop), 3150 getWeakLeft(Cand.SU, Cand.AtTop), 3151 TryCand, Cand, Weak)) 3152 return; 3153 } 3154 3155 // Avoid increasing the max pressure of the entire region. 3156 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax, 3157 Cand.RPDelta.CurrentMax, 3158 TryCand, Cand, RegMax, TRI, 3159 DAG->MF)) 3160 return; 3161 3162 if (SameBoundary) { 3163 // Avoid critical resource consumption and balance the schedule. 3164 TryCand.initResourceDelta(DAG, SchedModel); 3165 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources, 3166 TryCand, Cand, ResourceReduce)) 3167 return; 3168 if (tryGreater(TryCand.ResDelta.DemandedResources, 3169 Cand.ResDelta.DemandedResources, 3170 TryCand, Cand, ResourceDemand)) 3171 return; 3172 3173 // Avoid serializing long latency dependence chains. 3174 // For acyclic path limited loops, latency was already checked above. 3175 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency && 3176 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone)) 3177 return; 3178 3179 // Fall through to original instruction order. 3180 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum) 3181 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) { 3182 TryCand.Reason = NodeOrder; 3183 } 3184 } 3185 } 3186 3187 /// Pick the best candidate from the queue. 3188 /// 3189 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during 3190 /// DAG building. To adjust for the current scheduling location we need to 3191 /// maintain the number of vreg uses remaining to be top-scheduled. 3192 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone, 3193 const CandPolicy &ZonePolicy, 3194 const RegPressureTracker &RPTracker, 3195 SchedCandidate &Cand) { 3196 // getMaxPressureDelta temporarily modifies the tracker. 3197 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker); 3198 3199 ReadyQueue &Q = Zone.Available; 3200 for (SUnit *SU : Q) { 3201 3202 SchedCandidate TryCand(ZonePolicy); 3203 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker); 3204 // Pass SchedBoundary only when comparing nodes from the same boundary. 3205 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr; 3206 tryCandidate(Cand, TryCand, ZoneArg); 3207 if (TryCand.Reason != NoCand) { 3208 // Initialize resource delta if needed in case future heuristics query it. 3209 if (TryCand.ResDelta == SchedResourceDelta()) 3210 TryCand.initResourceDelta(DAG, SchedModel); 3211 Cand.setBest(TryCand); 3212 LLVM_DEBUG(traceCandidate(Cand)); 3213 } 3214 } 3215 } 3216 3217 /// Pick the best candidate node from either the top or bottom queue. 3218 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) { 3219 // Schedule as far as possible in the direction of no choice. This is most 3220 // efficient, but also provides the best heuristics for CriticalPSets. 3221 if (SUnit *SU = Bot.pickOnlyChoice()) { 3222 IsTopNode = false; 3223 tracePick(Only1, false); 3224 return SU; 3225 } 3226 if (SUnit *SU = Top.pickOnlyChoice()) { 3227 IsTopNode = true; 3228 tracePick(Only1, true); 3229 return SU; 3230 } 3231 // Set the bottom-up policy based on the state of the current bottom zone and 3232 // the instructions outside the zone, including the top zone. 3233 CandPolicy BotPolicy; 3234 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top); 3235 // Set the top-down policy based on the state of the current top zone and 3236 // the instructions outside the zone, including the bottom zone. 3237 CandPolicy TopPolicy; 3238 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot); 3239 3240 // See if BotCand is still valid (because we previously scheduled from Top). 3241 LLVM_DEBUG(dbgs() << "Picking from Bot:\n"); 3242 if (!BotCand.isValid() || BotCand.SU->isScheduled || 3243 BotCand.Policy != BotPolicy) { 3244 BotCand.reset(CandPolicy()); 3245 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand); 3246 assert(BotCand.Reason != NoCand && "failed to find the first candidate"); 3247 } else { 3248 LLVM_DEBUG(traceCandidate(BotCand)); 3249 #ifndef NDEBUG 3250 if (VerifyScheduling) { 3251 SchedCandidate TCand; 3252 TCand.reset(CandPolicy()); 3253 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand); 3254 assert(TCand.SU == BotCand.SU && 3255 "Last pick result should correspond to re-picking right now"); 3256 } 3257 #endif 3258 } 3259 3260 // Check if the top Q has a better candidate. 3261 LLVM_DEBUG(dbgs() << "Picking from Top:\n"); 3262 if (!TopCand.isValid() || TopCand.SU->isScheduled || 3263 TopCand.Policy != TopPolicy) { 3264 TopCand.reset(CandPolicy()); 3265 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand); 3266 assert(TopCand.Reason != NoCand && "failed to find the first candidate"); 3267 } else { 3268 LLVM_DEBUG(traceCandidate(TopCand)); 3269 #ifndef NDEBUG 3270 if (VerifyScheduling) { 3271 SchedCandidate TCand; 3272 TCand.reset(CandPolicy()); 3273 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand); 3274 assert(TCand.SU == TopCand.SU && 3275 "Last pick result should correspond to re-picking right now"); 3276 } 3277 #endif 3278 } 3279 3280 // Pick best from BotCand and TopCand. 3281 assert(BotCand.isValid()); 3282 assert(TopCand.isValid()); 3283 SchedCandidate Cand = BotCand; 3284 TopCand.Reason = NoCand; 3285 tryCandidate(Cand, TopCand, nullptr); 3286 if (TopCand.Reason != NoCand) { 3287 Cand.setBest(TopCand); 3288 LLVM_DEBUG(traceCandidate(Cand)); 3289 } 3290 3291 IsTopNode = Cand.AtTop; 3292 tracePick(Cand); 3293 return Cand.SU; 3294 } 3295 3296 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy. 3297 SUnit *GenericScheduler::pickNode(bool &IsTopNode) { 3298 if (DAG->top() == DAG->bottom()) { 3299 assert(Top.Available.empty() && Top.Pending.empty() && 3300 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage"); 3301 return nullptr; 3302 } 3303 SUnit *SU; 3304 do { 3305 if (RegionPolicy.OnlyTopDown) { 3306 SU = Top.pickOnlyChoice(); 3307 if (!SU) { 3308 CandPolicy NoPolicy; 3309 TopCand.reset(NoPolicy); 3310 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand); 3311 assert(TopCand.Reason != NoCand && "failed to find a candidate"); 3312 tracePick(TopCand); 3313 SU = TopCand.SU; 3314 } 3315 IsTopNode = true; 3316 } else if (RegionPolicy.OnlyBottomUp) { 3317 SU = Bot.pickOnlyChoice(); 3318 if (!SU) { 3319 CandPolicy NoPolicy; 3320 BotCand.reset(NoPolicy); 3321 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand); 3322 assert(BotCand.Reason != NoCand && "failed to find a candidate"); 3323 tracePick(BotCand); 3324 SU = BotCand.SU; 3325 } 3326 IsTopNode = false; 3327 } else { 3328 SU = pickNodeBidirectional(IsTopNode); 3329 } 3330 } while (SU->isScheduled); 3331 3332 if (SU->isTopReady()) 3333 Top.removeReady(SU); 3334 if (SU->isBottomReady()) 3335 Bot.removeReady(SU); 3336 3337 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " 3338 << *SU->getInstr()); 3339 return SU; 3340 } 3341 3342 void GenericScheduler::reschedulePhysReg(SUnit *SU, bool isTop) { 3343 MachineBasicBlock::iterator InsertPos = SU->getInstr(); 3344 if (!isTop) 3345 ++InsertPos; 3346 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs; 3347 3348 // Find already scheduled copies with a single physreg dependence and move 3349 // them just above the scheduled instruction. 3350 for (SDep &Dep : Deps) { 3351 if (Dep.getKind() != SDep::Data || 3352 !Register::isPhysicalRegister(Dep.getReg())) 3353 continue; 3354 SUnit *DepSU = Dep.getSUnit(); 3355 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1) 3356 continue; 3357 MachineInstr *Copy = DepSU->getInstr(); 3358 if (!Copy->isCopy() && !Copy->isMoveImmediate()) 3359 continue; 3360 LLVM_DEBUG(dbgs() << " Rescheduling physreg copy "; 3361 DAG->dumpNode(*Dep.getSUnit())); 3362 DAG->moveInstruction(Copy, InsertPos); 3363 } 3364 } 3365 3366 /// Update the scheduler's state after scheduling a node. This is the same node 3367 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to 3368 /// update it's state based on the current cycle before MachineSchedStrategy 3369 /// does. 3370 /// 3371 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling 3372 /// them here. See comments in biasPhysReg. 3373 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) { 3374 if (IsTopNode) { 3375 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle()); 3376 Top.bumpNode(SU); 3377 if (SU->hasPhysRegUses) 3378 reschedulePhysReg(SU, true); 3379 } else { 3380 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle()); 3381 Bot.bumpNode(SU); 3382 if (SU->hasPhysRegDefs) 3383 reschedulePhysReg(SU, false); 3384 } 3385 } 3386 3387 /// Create the standard converging machine scheduler. This will be used as the 3388 /// default scheduler if the target does not set a default. 3389 ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) { 3390 ScheduleDAGMILive *DAG = 3391 new ScheduleDAGMILive(C, std::make_unique<GenericScheduler>(C)); 3392 // Register DAG post-processors. 3393 // 3394 // FIXME: extend the mutation API to allow earlier mutations to instantiate 3395 // data and pass it to later mutations. Have a single mutation that gathers 3396 // the interesting nodes in one pass. 3397 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI)); 3398 return DAG; 3399 } 3400 3401 static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) { 3402 return createGenericSchedLive(C); 3403 } 3404 3405 static MachineSchedRegistry 3406 GenericSchedRegistry("converge", "Standard converging scheduler.", 3407 createConveringSched); 3408 3409 //===----------------------------------------------------------------------===// 3410 // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy. 3411 //===----------------------------------------------------------------------===// 3412 3413 void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) { 3414 DAG = Dag; 3415 SchedModel = DAG->getSchedModel(); 3416 TRI = DAG->TRI; 3417 3418 Rem.init(DAG, SchedModel); 3419 Top.init(DAG, SchedModel, &Rem); 3420 BotRoots.clear(); 3421 3422 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, 3423 // or are disabled, then these HazardRecs will be disabled. 3424 const InstrItineraryData *Itin = SchedModel->getInstrItineraries(); 3425 if (!Top.HazardRec) { 3426 Top.HazardRec = 3427 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer( 3428 Itin, DAG); 3429 } 3430 } 3431 3432 void PostGenericScheduler::registerRoots() { 3433 Rem.CriticalPath = DAG->ExitSU.getDepth(); 3434 3435 // Some roots may not feed into ExitSU. Check all of them in case. 3436 for (const SUnit *SU : BotRoots) { 3437 if (SU->getDepth() > Rem.CriticalPath) 3438 Rem.CriticalPath = SU->getDepth(); 3439 } 3440 LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n'); 3441 if (DumpCriticalPathLength) { 3442 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n"; 3443 } 3444 } 3445 3446 /// Apply a set of heuristics to a new candidate for PostRA scheduling. 3447 /// 3448 /// \param Cand provides the policy and current best candidate. 3449 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized. 3450 void PostGenericScheduler::tryCandidate(SchedCandidate &Cand, 3451 SchedCandidate &TryCand) { 3452 // Initialize the candidate if needed. 3453 if (!Cand.isValid()) { 3454 TryCand.Reason = NodeOrder; 3455 return; 3456 } 3457 3458 // Prioritize instructions that read unbuffered resources by stall cycles. 3459 if (tryLess(Top.getLatencyStallCycles(TryCand.SU), 3460 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall)) 3461 return; 3462 3463 // Keep clustered nodes together. 3464 if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(), 3465 Cand.SU == DAG->getNextClusterSucc(), 3466 TryCand, Cand, Cluster)) 3467 return; 3468 3469 // Avoid critical resource consumption and balance the schedule. 3470 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources, 3471 TryCand, Cand, ResourceReduce)) 3472 return; 3473 if (tryGreater(TryCand.ResDelta.DemandedResources, 3474 Cand.ResDelta.DemandedResources, 3475 TryCand, Cand, ResourceDemand)) 3476 return; 3477 3478 // Avoid serializing long latency dependence chains. 3479 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) { 3480 return; 3481 } 3482 3483 // Fall through to original instruction order. 3484 if (TryCand.SU->NodeNum < Cand.SU->NodeNum) 3485 TryCand.Reason = NodeOrder; 3486 } 3487 3488 void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) { 3489 ReadyQueue &Q = Top.Available; 3490 for (SUnit *SU : Q) { 3491 SchedCandidate TryCand(Cand.Policy); 3492 TryCand.SU = SU; 3493 TryCand.AtTop = true; 3494 TryCand.initResourceDelta(DAG, SchedModel); 3495 tryCandidate(Cand, TryCand); 3496 if (TryCand.Reason != NoCand) { 3497 Cand.setBest(TryCand); 3498 LLVM_DEBUG(traceCandidate(Cand)); 3499 } 3500 } 3501 } 3502 3503 /// Pick the next node to schedule. 3504 SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) { 3505 if (DAG->top() == DAG->bottom()) { 3506 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage"); 3507 return nullptr; 3508 } 3509 SUnit *SU; 3510 do { 3511 SU = Top.pickOnlyChoice(); 3512 if (SU) { 3513 tracePick(Only1, true); 3514 } else { 3515 CandPolicy NoPolicy; 3516 SchedCandidate TopCand(NoPolicy); 3517 // Set the top-down policy based on the state of the current top zone and 3518 // the instructions outside the zone, including the bottom zone. 3519 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr); 3520 pickNodeFromQueue(TopCand); 3521 assert(TopCand.Reason != NoCand && "failed to find a candidate"); 3522 tracePick(TopCand); 3523 SU = TopCand.SU; 3524 } 3525 } while (SU->isScheduled); 3526 3527 IsTopNode = true; 3528 Top.removeReady(SU); 3529 3530 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " 3531 << *SU->getInstr()); 3532 return SU; 3533 } 3534 3535 /// Called after ScheduleDAGMI has scheduled an instruction and updated 3536 /// scheduled/remaining flags in the DAG nodes. 3537 void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) { 3538 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle()); 3539 Top.bumpNode(SU); 3540 } 3541 3542 ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) { 3543 return new ScheduleDAGMI(C, std::make_unique<PostGenericScheduler>(C), 3544 /*RemoveKillFlags=*/true); 3545 } 3546 3547 //===----------------------------------------------------------------------===// 3548 // ILP Scheduler. Currently for experimental analysis of heuristics. 3549 //===----------------------------------------------------------------------===// 3550 3551 namespace { 3552 3553 /// Order nodes by the ILP metric. 3554 struct ILPOrder { 3555 const SchedDFSResult *DFSResult = nullptr; 3556 const BitVector *ScheduledTrees = nullptr; 3557 bool MaximizeILP; 3558 3559 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {} 3560 3561 /// Apply a less-than relation on node priority. 3562 /// 3563 /// (Return true if A comes after B in the Q.) 3564 bool operator()(const SUnit *A, const SUnit *B) const { 3565 unsigned SchedTreeA = DFSResult->getSubtreeID(A); 3566 unsigned SchedTreeB = DFSResult->getSubtreeID(B); 3567 if (SchedTreeA != SchedTreeB) { 3568 // Unscheduled trees have lower priority. 3569 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB)) 3570 return ScheduledTrees->test(SchedTreeB); 3571 3572 // Trees with shallower connections have have lower priority. 3573 if (DFSResult->getSubtreeLevel(SchedTreeA) 3574 != DFSResult->getSubtreeLevel(SchedTreeB)) { 3575 return DFSResult->getSubtreeLevel(SchedTreeA) 3576 < DFSResult->getSubtreeLevel(SchedTreeB); 3577 } 3578 } 3579 if (MaximizeILP) 3580 return DFSResult->getILP(A) < DFSResult->getILP(B); 3581 else 3582 return DFSResult->getILP(A) > DFSResult->getILP(B); 3583 } 3584 }; 3585 3586 /// Schedule based on the ILP metric. 3587 class ILPScheduler : public MachineSchedStrategy { 3588 ScheduleDAGMILive *DAG = nullptr; 3589 ILPOrder Cmp; 3590 3591 std::vector<SUnit*> ReadyQ; 3592 3593 public: 3594 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {} 3595 3596 void initialize(ScheduleDAGMI *dag) override { 3597 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness"); 3598 DAG = static_cast<ScheduleDAGMILive*>(dag); 3599 DAG->computeDFSResult(); 3600 Cmp.DFSResult = DAG->getDFSResult(); 3601 Cmp.ScheduledTrees = &DAG->getScheduledTrees(); 3602 ReadyQ.clear(); 3603 } 3604 3605 void registerRoots() override { 3606 // Restore the heap in ReadyQ with the updated DFS results. 3607 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3608 } 3609 3610 /// Implement MachineSchedStrategy interface. 3611 /// ----------------------------------------- 3612 3613 /// Callback to select the highest priority node from the ready Q. 3614 SUnit *pickNode(bool &IsTopNode) override { 3615 if (ReadyQ.empty()) return nullptr; 3616 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3617 SUnit *SU = ReadyQ.back(); 3618 ReadyQ.pop_back(); 3619 IsTopNode = false; 3620 LLVM_DEBUG(dbgs() << "Pick node " 3621 << "SU(" << SU->NodeNum << ") " 3622 << " ILP: " << DAG->getDFSResult()->getILP(SU) 3623 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) 3624 << " @" 3625 << DAG->getDFSResult()->getSubtreeLevel( 3626 DAG->getDFSResult()->getSubtreeID(SU)) 3627 << '\n' 3628 << "Scheduling " << *SU->getInstr()); 3629 return SU; 3630 } 3631 3632 /// Scheduler callback to notify that a new subtree is scheduled. 3633 void scheduleTree(unsigned SubtreeID) override { 3634 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3635 } 3636 3637 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify 3638 /// DFSResults, and resort the priority Q. 3639 void schedNode(SUnit *SU, bool IsTopNode) override { 3640 assert(!IsTopNode && "SchedDFSResult needs bottom-up"); 3641 } 3642 3643 void releaseTopNode(SUnit *) override { /*only called for top roots*/ } 3644 3645 void releaseBottomNode(SUnit *SU) override { 3646 ReadyQ.push_back(SU); 3647 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp); 3648 } 3649 }; 3650 3651 } // end anonymous namespace 3652 3653 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) { 3654 return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(true)); 3655 } 3656 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) { 3657 return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(false)); 3658 } 3659 3660 static MachineSchedRegistry ILPMaxRegistry( 3661 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler); 3662 static MachineSchedRegistry ILPMinRegistry( 3663 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler); 3664 3665 //===----------------------------------------------------------------------===// 3666 // Machine Instruction Shuffler for Correctness Testing 3667 //===----------------------------------------------------------------------===// 3668 3669 #ifndef NDEBUG 3670 namespace { 3671 3672 /// Apply a less-than relation on the node order, which corresponds to the 3673 /// instruction order prior to scheduling. IsReverse implements greater-than. 3674 template<bool IsReverse> 3675 struct SUnitOrder { 3676 bool operator()(SUnit *A, SUnit *B) const { 3677 if (IsReverse) 3678 return A->NodeNum > B->NodeNum; 3679 else 3680 return A->NodeNum < B->NodeNum; 3681 } 3682 }; 3683 3684 /// Reorder instructions as much as possible. 3685 class InstructionShuffler : public MachineSchedStrategy { 3686 bool IsAlternating; 3687 bool IsTopDown; 3688 3689 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority 3690 // gives nodes with a higher number higher priority causing the latest 3691 // instructions to be scheduled first. 3692 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>> 3693 TopQ; 3694 3695 // When scheduling bottom-up, use greater-than as the queue priority. 3696 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>> 3697 BottomQ; 3698 3699 public: 3700 InstructionShuffler(bool alternate, bool topdown) 3701 : IsAlternating(alternate), IsTopDown(topdown) {} 3702 3703 void initialize(ScheduleDAGMI*) override { 3704 TopQ.clear(); 3705 BottomQ.clear(); 3706 } 3707 3708 /// Implement MachineSchedStrategy interface. 3709 /// ----------------------------------------- 3710 3711 SUnit *pickNode(bool &IsTopNode) override { 3712 SUnit *SU; 3713 if (IsTopDown) { 3714 do { 3715 if (TopQ.empty()) return nullptr; 3716 SU = TopQ.top(); 3717 TopQ.pop(); 3718 } while (SU->isScheduled); 3719 IsTopNode = true; 3720 } else { 3721 do { 3722 if (BottomQ.empty()) return nullptr; 3723 SU = BottomQ.top(); 3724 BottomQ.pop(); 3725 } while (SU->isScheduled); 3726 IsTopNode = false; 3727 } 3728 if (IsAlternating) 3729 IsTopDown = !IsTopDown; 3730 return SU; 3731 } 3732 3733 void schedNode(SUnit *SU, bool IsTopNode) override {} 3734 3735 void releaseTopNode(SUnit *SU) override { 3736 TopQ.push(SU); 3737 } 3738 void releaseBottomNode(SUnit *SU) override { 3739 BottomQ.push(SU); 3740 } 3741 }; 3742 3743 } // end anonymous namespace 3744 3745 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) { 3746 bool Alternate = !ForceTopDown && !ForceBottomUp; 3747 bool TopDown = !ForceBottomUp; 3748 assert((TopDown || !ForceTopDown) && 3749 "-misched-topdown incompatible with -misched-bottomup"); 3750 return new ScheduleDAGMILive( 3751 C, std::make_unique<InstructionShuffler>(Alternate, TopDown)); 3752 } 3753 3754 static MachineSchedRegistry ShufflerRegistry( 3755 "shuffle", "Shuffle machine instructions alternating directions", 3756 createInstructionShuffler); 3757 #endif // !NDEBUG 3758 3759 //===----------------------------------------------------------------------===// 3760 // GraphWriter support for ScheduleDAGMILive. 3761 //===----------------------------------------------------------------------===// 3762 3763 #ifndef NDEBUG 3764 namespace llvm { 3765 3766 template<> struct GraphTraits< 3767 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {}; 3768 3769 template<> 3770 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits { 3771 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3772 3773 static std::string getGraphName(const ScheduleDAG *G) { 3774 return std::string(G->MF.getName()); 3775 } 3776 3777 static bool renderGraphFromBottomUp() { 3778 return true; 3779 } 3780 3781 static bool isNodeHidden(const SUnit *Node) { 3782 if (ViewMISchedCutoff == 0) 3783 return false; 3784 return (Node->Preds.size() > ViewMISchedCutoff 3785 || Node->Succs.size() > ViewMISchedCutoff); 3786 } 3787 3788 /// If you want to override the dot attributes printed for a particular 3789 /// edge, override this method. 3790 static std::string getEdgeAttributes(const SUnit *Node, 3791 SUnitIterator EI, 3792 const ScheduleDAG *Graph) { 3793 if (EI.isArtificialDep()) 3794 return "color=cyan,style=dashed"; 3795 if (EI.isCtrlDep()) 3796 return "color=blue,style=dashed"; 3797 return ""; 3798 } 3799 3800 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) { 3801 std::string Str; 3802 raw_string_ostream SS(Str); 3803 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G); 3804 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ? 3805 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr; 3806 SS << "SU:" << SU->NodeNum; 3807 if (DFS) 3808 SS << " I:" << DFS->getNumInstrs(SU); 3809 return SS.str(); 3810 } 3811 3812 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) { 3813 return G->getGraphNodeLabel(SU); 3814 } 3815 3816 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) { 3817 std::string Str("shape=Mrecord"); 3818 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G); 3819 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ? 3820 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr; 3821 if (DFS) { 3822 Str += ",style=filled,fillcolor=\"#"; 3823 Str += DOT::getColorString(DFS->getSubtreeID(N)); 3824 Str += '"'; 3825 } 3826 return Str; 3827 } 3828 }; 3829 3830 } // end namespace llvm 3831 #endif // NDEBUG 3832 3833 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG 3834 /// rendered using 'dot'. 3835 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) { 3836 #ifndef NDEBUG 3837 ViewGraph(this, Name, false, Title); 3838 #else 3839 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on " 3840 << "systems with Graphviz or gv!\n"; 3841 #endif // NDEBUG 3842 } 3843 3844 /// Out-of-line implementation with no arguments is handy for gdb. 3845 void ScheduleDAGMI::viewGraph() { 3846 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName()); 3847 } 3848