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