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