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