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