1 //===----- SchedulePostRAList.cpp - list 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 // This implements a top-down list scheduler, using standard algorithms. 11 // The basic approach uses a priority queue of available nodes to schedule. 12 // One at a time, nodes are taken from the priority queue (thus in priority 13 // order), checked for legality to schedule, and emitted if legal. 14 // 15 // Nodes may not be legal to schedule either due to structural hazards (e.g. 16 // pipeline or resource constraints) or because an input to the instruction has 17 // not completed execution. 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "AggressiveAntiDepBreaker.h" 22 #include "AntiDepBreaker.h" 23 #include "CriticalAntiDepBreaker.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/CodeGen/LatencyPriorityQueue.h" 27 #include "llvm/CodeGen/MachineDominators.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineFunctionPass.h" 30 #include "llvm/CodeGen/MachineLoopInfo.h" 31 #include "llvm/CodeGen/MachineRegisterInfo.h" 32 #include "llvm/CodeGen/Passes.h" 33 #include "llvm/CodeGen/RegisterClassInfo.h" 34 #include "llvm/CodeGen/ScheduleDAGInstrs.h" 35 #include "llvm/CodeGen/ScheduleHazardRecognizer.h" 36 #include "llvm/CodeGen/SchedulerRegistry.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include "llvm/Target/TargetInstrInfo.h" 42 #include "llvm/Target/TargetLowering.h" 43 #include "llvm/Target/TargetRegisterInfo.h" 44 #include "llvm/Target/TargetSubtargetInfo.h" 45 using namespace llvm; 46 47 #define DEBUG_TYPE "post-RA-sched" 48 49 STATISTIC(NumNoops, "Number of noops inserted"); 50 STATISTIC(NumStalls, "Number of pipeline stalls"); 51 STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies"); 52 53 // Post-RA scheduling is enabled with 54 // TargetSubtargetInfo.enablePostRAScheduler(). This flag can be used to 55 // override the target. 56 static cl::opt<bool> 57 EnablePostRAScheduler("post-RA-scheduler", 58 cl::desc("Enable scheduling after register allocation"), 59 cl::init(false), cl::Hidden); 60 static cl::opt<std::string> 61 EnableAntiDepBreaking("break-anti-dependencies", 62 cl::desc("Break post-RA scheduling anti-dependencies: " 63 "\"critical\", \"all\", or \"none\""), 64 cl::init("none"), cl::Hidden); 65 66 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod 67 static cl::opt<int> 68 DebugDiv("postra-sched-debugdiv", 69 cl::desc("Debug control MBBs that are scheduled"), 70 cl::init(0), cl::Hidden); 71 static cl::opt<int> 72 DebugMod("postra-sched-debugmod", 73 cl::desc("Debug control MBBs that are scheduled"), 74 cl::init(0), cl::Hidden); 75 76 AntiDepBreaker::~AntiDepBreaker() { } 77 78 namespace { 79 class PostRAScheduler : public MachineFunctionPass { 80 const TargetInstrInfo *TII; 81 RegisterClassInfo RegClassInfo; 82 83 public: 84 static char ID; 85 PostRAScheduler() : MachineFunctionPass(ID) {} 86 87 void getAnalysisUsage(AnalysisUsage &AU) const override { 88 AU.setPreservesCFG(); 89 AU.addRequired<AAResultsWrapperPass>(); 90 AU.addRequired<TargetPassConfig>(); 91 AU.addRequired<MachineDominatorTree>(); 92 AU.addPreserved<MachineDominatorTree>(); 93 AU.addRequired<MachineLoopInfo>(); 94 AU.addPreserved<MachineLoopInfo>(); 95 MachineFunctionPass::getAnalysisUsage(AU); 96 } 97 98 MachineFunctionProperties getRequiredProperties() const override { 99 return MachineFunctionProperties().set( 100 MachineFunctionProperties::Property::AllVRegsAllocated); 101 } 102 103 bool runOnMachineFunction(MachineFunction &Fn) override; 104 105 bool enablePostRAScheduler( 106 const TargetSubtargetInfo &ST, CodeGenOpt::Level OptLevel, 107 TargetSubtargetInfo::AntiDepBreakMode &Mode, 108 TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const; 109 }; 110 char PostRAScheduler::ID = 0; 111 112 class SchedulePostRATDList : public ScheduleDAGInstrs { 113 /// AvailableQueue - The priority queue to use for the available SUnits. 114 /// 115 LatencyPriorityQueue AvailableQueue; 116 117 /// PendingQueue - This contains all of the instructions whose operands have 118 /// been issued, but their results are not ready yet (due to the latency of 119 /// the operation). Once the operands becomes available, the instruction is 120 /// added to the AvailableQueue. 121 std::vector<SUnit*> PendingQueue; 122 123 /// HazardRec - The hazard recognizer to use. 124 ScheduleHazardRecognizer *HazardRec; 125 126 /// AntiDepBreak - Anti-dependence breaking object, or NULL if none 127 AntiDepBreaker *AntiDepBreak; 128 129 /// AA - AliasAnalysis for making memory reference queries. 130 AliasAnalysis *AA; 131 132 /// The schedule. Null SUnit*'s represent noop instructions. 133 std::vector<SUnit*> Sequence; 134 135 /// Ordered list of DAG postprocessing steps. 136 std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations; 137 138 /// The index in BB of RegionEnd. 139 /// 140 /// This is the instruction number from the top of the current block, not 141 /// the SlotIndex. It is only used by the AntiDepBreaker. 142 unsigned EndIndex; 143 144 public: 145 SchedulePostRATDList( 146 MachineFunction &MF, MachineLoopInfo &MLI, AliasAnalysis *AA, 147 const RegisterClassInfo &, 148 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode, 149 SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs); 150 151 ~SchedulePostRATDList() override; 152 153 /// startBlock - Initialize register live-range state for scheduling in 154 /// this block. 155 /// 156 void startBlock(MachineBasicBlock *BB) override; 157 158 // Set the index of RegionEnd within the current BB. 159 void setEndIndex(unsigned EndIdx) { EndIndex = EndIdx; } 160 161 /// Initialize the scheduler state for the next scheduling region. 162 void enterRegion(MachineBasicBlock *bb, 163 MachineBasicBlock::iterator begin, 164 MachineBasicBlock::iterator end, 165 unsigned regioninstrs) override; 166 167 /// Notify that the scheduler has finished scheduling the current region. 168 void exitRegion() override; 169 170 /// Schedule - Schedule the instruction range using list scheduling. 171 /// 172 void schedule() override; 173 174 void EmitSchedule(); 175 176 /// Observe - Update liveness information to account for the current 177 /// instruction, which will not be scheduled. 178 /// 179 void Observe(MachineInstr &MI, unsigned Count); 180 181 /// finishBlock - Clean up register live-range state. 182 /// 183 void finishBlock() override; 184 185 private: 186 /// Apply each ScheduleDAGMutation step in order. 187 void postprocessDAG(); 188 189 void ReleaseSucc(SUnit *SU, SDep *SuccEdge); 190 void ReleaseSuccessors(SUnit *SU); 191 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle); 192 void ListScheduleTopDown(); 193 194 void dumpSchedule() const; 195 void emitNoop(unsigned CurCycle); 196 }; 197 } 198 199 char &llvm::PostRASchedulerID = PostRAScheduler::ID; 200 201 INITIALIZE_PASS(PostRAScheduler, "post-RA-sched", 202 "Post RA top-down list latency scheduler", false, false) 203 204 SchedulePostRATDList::SchedulePostRATDList( 205 MachineFunction &MF, MachineLoopInfo &MLI, AliasAnalysis *AA, 206 const RegisterClassInfo &RCI, 207 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode, 208 SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs) 209 : ScheduleDAGInstrs(MF, &MLI), AA(AA), EndIndex(0) { 210 211 const InstrItineraryData *InstrItins = 212 MF.getSubtarget().getInstrItineraryData(); 213 HazardRec = 214 MF.getSubtarget().getInstrInfo()->CreateTargetPostRAHazardRecognizer( 215 InstrItins, this); 216 MF.getSubtarget().getPostRAMutations(Mutations); 217 218 assert((AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE || 219 MRI.tracksLiveness()) && 220 "Live-ins must be accurate for anti-dependency breaking"); 221 AntiDepBreak = 222 ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) ? 223 (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs) : 224 ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL) ? 225 (AntiDepBreaker *)new CriticalAntiDepBreaker(MF, RCI) : nullptr)); 226 } 227 228 SchedulePostRATDList::~SchedulePostRATDList() { 229 delete HazardRec; 230 delete AntiDepBreak; 231 } 232 233 /// Initialize state associated with the next scheduling region. 234 void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb, 235 MachineBasicBlock::iterator begin, 236 MachineBasicBlock::iterator end, 237 unsigned regioninstrs) { 238 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs); 239 Sequence.clear(); 240 } 241 242 /// Print the schedule before exiting the region. 243 void SchedulePostRATDList::exitRegion() { 244 DEBUG({ 245 dbgs() << "*** Final schedule ***\n"; 246 dumpSchedule(); 247 dbgs() << '\n'; 248 }); 249 ScheduleDAGInstrs::exitRegion(); 250 } 251 252 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 253 /// dumpSchedule - dump the scheduled Sequence. 254 void SchedulePostRATDList::dumpSchedule() const { 255 for (unsigned i = 0, e = Sequence.size(); i != e; i++) { 256 if (SUnit *SU = Sequence[i]) 257 SU->dump(this); 258 else 259 dbgs() << "**** NOOP ****\n"; 260 } 261 } 262 #endif 263 264 bool PostRAScheduler::enablePostRAScheduler( 265 const TargetSubtargetInfo &ST, 266 CodeGenOpt::Level OptLevel, 267 TargetSubtargetInfo::AntiDepBreakMode &Mode, 268 TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const { 269 Mode = ST.getAntiDepBreakMode(); 270 ST.getCriticalPathRCs(CriticalPathRCs); 271 return ST.enablePostRAScheduler() && 272 OptLevel >= ST.getOptLevelToEnablePostRAScheduler(); 273 } 274 275 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) { 276 if (skipFunction(*Fn.getFunction())) 277 return false; 278 279 TII = Fn.getSubtarget().getInstrInfo(); 280 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>(); 281 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 282 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 283 284 RegClassInfo.runOnMachineFunction(Fn); 285 286 // Check for explicit enable/disable of post-ra scheduling. 287 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode = 288 TargetSubtargetInfo::ANTIDEP_NONE; 289 SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs; 290 if (EnablePostRAScheduler.getPosition() > 0) { 291 if (!EnablePostRAScheduler) 292 return false; 293 } else { 294 // Check that post-RA scheduling is enabled for this target. 295 // This may upgrade the AntiDepMode. 296 if (!enablePostRAScheduler(Fn.getSubtarget(), PassConfig->getOptLevel(), 297 AntiDepMode, CriticalPathRCs)) 298 return false; 299 } 300 301 // Check for antidep breaking override... 302 if (EnableAntiDepBreaking.getPosition() > 0) { 303 AntiDepMode = (EnableAntiDepBreaking == "all") 304 ? TargetSubtargetInfo::ANTIDEP_ALL 305 : ((EnableAntiDepBreaking == "critical") 306 ? TargetSubtargetInfo::ANTIDEP_CRITICAL 307 : TargetSubtargetInfo::ANTIDEP_NONE); 308 } 309 310 DEBUG(dbgs() << "PostRAScheduler\n"); 311 312 SchedulePostRATDList Scheduler(Fn, MLI, AA, RegClassInfo, AntiDepMode, 313 CriticalPathRCs); 314 315 // Loop over all of the basic blocks 316 for (auto &MBB : Fn) { 317 #ifndef NDEBUG 318 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod 319 if (DebugDiv > 0) { 320 static int bbcnt = 0; 321 if (bbcnt++ % DebugDiv != DebugMod) 322 continue; 323 dbgs() << "*** DEBUG scheduling " << Fn.getName() 324 << ":BB#" << MBB.getNumber() << " ***\n"; 325 } 326 #endif 327 328 // Initialize register live-range state for scheduling in this block. 329 Scheduler.startBlock(&MBB); 330 331 // Schedule each sequence of instructions not interrupted by a label 332 // or anything else that effectively needs to shut down scheduling. 333 MachineBasicBlock::iterator Current = MBB.end(); 334 unsigned Count = MBB.size(), CurrentCount = Count; 335 for (MachineBasicBlock::iterator I = Current; I != MBB.begin();) { 336 MachineInstr *MI = std::prev(I); 337 --Count; 338 // Calls are not scheduling boundaries before register allocation, but 339 // post-ra we don't gain anything by scheduling across calls since we 340 // don't need to worry about register pressure. 341 if (MI->isCall() || TII->isSchedulingBoundary(MI, &MBB, Fn)) { 342 Scheduler.enterRegion(&MBB, I, Current, CurrentCount - Count); 343 Scheduler.setEndIndex(CurrentCount); 344 Scheduler.schedule(); 345 Scheduler.exitRegion(); 346 Scheduler.EmitSchedule(); 347 Current = MI; 348 CurrentCount = Count; 349 Scheduler.Observe(*MI, CurrentCount); 350 } 351 I = MI; 352 if (MI->isBundle()) 353 Count -= MI->getBundleSize(); 354 } 355 assert(Count == 0 && "Instruction count mismatch!"); 356 assert((MBB.begin() == Current || CurrentCount != 0) && 357 "Instruction count mismatch!"); 358 Scheduler.enterRegion(&MBB, MBB.begin(), Current, CurrentCount); 359 Scheduler.setEndIndex(CurrentCount); 360 Scheduler.schedule(); 361 Scheduler.exitRegion(); 362 Scheduler.EmitSchedule(); 363 364 // Clean up register live-range state. 365 Scheduler.finishBlock(); 366 367 // Update register kills 368 Scheduler.fixupKills(&MBB); 369 } 370 371 return true; 372 } 373 374 /// StartBlock - Initialize register live-range state for scheduling in 375 /// this block. 376 /// 377 void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) { 378 // Call the superclass. 379 ScheduleDAGInstrs::startBlock(BB); 380 381 // Reset the hazard recognizer and anti-dep breaker. 382 HazardRec->Reset(); 383 if (AntiDepBreak) 384 AntiDepBreak->StartBlock(BB); 385 } 386 387 /// Schedule - Schedule the instruction range using list scheduling. 388 /// 389 void SchedulePostRATDList::schedule() { 390 // Build the scheduling graph. 391 buildSchedGraph(AA); 392 393 if (AntiDepBreak) { 394 unsigned Broken = 395 AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd, 396 EndIndex, DbgValues); 397 398 if (Broken != 0) { 399 // We made changes. Update the dependency graph. 400 // Theoretically we could update the graph in place: 401 // When a live range is changed to use a different register, remove 402 // the def's anti-dependence *and* output-dependence edges due to 403 // that register, and add new anti-dependence and output-dependence 404 // edges based on the next live range of the register. 405 ScheduleDAG::clearDAG(); 406 buildSchedGraph(AA); 407 408 NumFixedAnti += Broken; 409 } 410 } 411 412 postprocessDAG(); 413 414 DEBUG(dbgs() << "********** List Scheduling **********\n"); 415 DEBUG( 416 for (const SUnit &SU : SUnits) { 417 SU.dumpAll(this); 418 dbgs() << '\n'; 419 } 420 ); 421 422 AvailableQueue.initNodes(SUnits); 423 ListScheduleTopDown(); 424 AvailableQueue.releaseState(); 425 } 426 427 /// Observe - Update liveness information to account for the current 428 /// instruction, which will not be scheduled. 429 /// 430 void SchedulePostRATDList::Observe(MachineInstr &MI, unsigned Count) { 431 if (AntiDepBreak) 432 AntiDepBreak->Observe(MI, Count, EndIndex); 433 } 434 435 /// FinishBlock - Clean up register live-range state. 436 /// 437 void SchedulePostRATDList::finishBlock() { 438 if (AntiDepBreak) 439 AntiDepBreak->FinishBlock(); 440 441 // Call the superclass. 442 ScheduleDAGInstrs::finishBlock(); 443 } 444 445 /// Apply each ScheduleDAGMutation step in order. 446 void SchedulePostRATDList::postprocessDAG() { 447 for (auto &M : Mutations) 448 M->apply(this); 449 } 450 451 //===----------------------------------------------------------------------===// 452 // Top-Down Scheduling 453 //===----------------------------------------------------------------------===// 454 455 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to 456 /// the PendingQueue if the count reaches zero. 457 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) { 458 SUnit *SuccSU = SuccEdge->getSUnit(); 459 460 if (SuccEdge->isWeak()) { 461 --SuccSU->WeakPredsLeft; 462 return; 463 } 464 #ifndef NDEBUG 465 if (SuccSU->NumPredsLeft == 0) { 466 dbgs() << "*** Scheduling failed! ***\n"; 467 SuccSU->dump(this); 468 dbgs() << " has been released too many times!\n"; 469 llvm_unreachable(nullptr); 470 } 471 #endif 472 --SuccSU->NumPredsLeft; 473 474 // Standard scheduler algorithms will recompute the depth of the successor 475 // here as such: 476 // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency()); 477 // 478 // However, we lazily compute node depth instead. Note that 479 // ScheduleNodeTopDown has already updated the depth of this node which causes 480 // all descendents to be marked dirty. Setting the successor depth explicitly 481 // here would cause depth to be recomputed for all its ancestors. If the 482 // successor is not yet ready (because of a transitively redundant edge) then 483 // this causes depth computation to be quadratic in the size of the DAG. 484 485 // If all the node's predecessors are scheduled, this node is ready 486 // to be scheduled. Ignore the special ExitSU node. 487 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) 488 PendingQueue.push_back(SuccSU); 489 } 490 491 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors. 492 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) { 493 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end(); 494 I != E; ++I) { 495 ReleaseSucc(SU, &*I); 496 } 497 } 498 499 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending 500 /// count of its successors. If a successor pending count is zero, add it to 501 /// the Available queue. 502 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) { 503 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: "); 504 DEBUG(SU->dump(this)); 505 506 Sequence.push_back(SU); 507 assert(CurCycle >= SU->getDepth() && 508 "Node scheduled above its depth!"); 509 SU->setDepthToAtLeast(CurCycle); 510 511 ReleaseSuccessors(SU); 512 SU->isScheduled = true; 513 AvailableQueue.scheduledNode(SU); 514 } 515 516 /// emitNoop - Add a noop to the current instruction sequence. 517 void SchedulePostRATDList::emitNoop(unsigned CurCycle) { 518 DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n'); 519 HazardRec->EmitNoop(); 520 Sequence.push_back(nullptr); // NULL here means noop 521 ++NumNoops; 522 } 523 524 /// ListScheduleTopDown - The main loop of list scheduling for top-down 525 /// schedulers. 526 void SchedulePostRATDList::ListScheduleTopDown() { 527 unsigned CurCycle = 0; 528 529 // We're scheduling top-down but we're visiting the regions in 530 // bottom-up order, so we don't know the hazards at the start of a 531 // region. So assume no hazards (this should usually be ok as most 532 // blocks are a single region). 533 HazardRec->Reset(); 534 535 // Release any successors of the special Entry node. 536 ReleaseSuccessors(&EntrySU); 537 538 // Add all leaves to Available queue. 539 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { 540 // It is available if it has no predecessors. 541 if (!SUnits[i].NumPredsLeft && !SUnits[i].isAvailable) { 542 AvailableQueue.push(&SUnits[i]); 543 SUnits[i].isAvailable = true; 544 } 545 } 546 547 // In any cycle where we can't schedule any instructions, we must 548 // stall or emit a noop, depending on the target. 549 bool CycleHasInsts = false; 550 551 // While Available queue is not empty, grab the node with the highest 552 // priority. If it is not ready put it back. Schedule the node. 553 std::vector<SUnit*> NotReady; 554 Sequence.reserve(SUnits.size()); 555 while (!AvailableQueue.empty() || !PendingQueue.empty()) { 556 // Check to see if any of the pending instructions are ready to issue. If 557 // so, add them to the available queue. 558 unsigned MinDepth = ~0u; 559 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) { 560 if (PendingQueue[i]->getDepth() <= CurCycle) { 561 AvailableQueue.push(PendingQueue[i]); 562 PendingQueue[i]->isAvailable = true; 563 PendingQueue[i] = PendingQueue.back(); 564 PendingQueue.pop_back(); 565 --i; --e; 566 } else if (PendingQueue[i]->getDepth() < MinDepth) 567 MinDepth = PendingQueue[i]->getDepth(); 568 } 569 570 DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this)); 571 572 SUnit *FoundSUnit = nullptr, *NotPreferredSUnit = nullptr; 573 bool HasNoopHazards = false; 574 while (!AvailableQueue.empty()) { 575 SUnit *CurSUnit = AvailableQueue.pop(); 576 577 ScheduleHazardRecognizer::HazardType HT = 578 HazardRec->getHazardType(CurSUnit, 0/*no stalls*/); 579 if (HT == ScheduleHazardRecognizer::NoHazard) { 580 if (HazardRec->ShouldPreferAnother(CurSUnit)) { 581 if (!NotPreferredSUnit) { 582 // If this is the first non-preferred node for this cycle, then 583 // record it and continue searching for a preferred node. If this 584 // is not the first non-preferred node, then treat it as though 585 // there had been a hazard. 586 NotPreferredSUnit = CurSUnit; 587 continue; 588 } 589 } else { 590 FoundSUnit = CurSUnit; 591 break; 592 } 593 } 594 595 // Remember if this is a noop hazard. 596 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard; 597 598 NotReady.push_back(CurSUnit); 599 } 600 601 // If we have a non-preferred node, push it back onto the available list. 602 // If we did not find a preferred node, then schedule this first 603 // non-preferred node. 604 if (NotPreferredSUnit) { 605 if (!FoundSUnit) { 606 DEBUG(dbgs() << "*** Will schedule a non-preferred instruction...\n"); 607 FoundSUnit = NotPreferredSUnit; 608 } else { 609 AvailableQueue.push(NotPreferredSUnit); 610 } 611 612 NotPreferredSUnit = nullptr; 613 } 614 615 // Add the nodes that aren't ready back onto the available list. 616 if (!NotReady.empty()) { 617 AvailableQueue.push_all(NotReady); 618 NotReady.clear(); 619 } 620 621 // If we found a node to schedule... 622 if (FoundSUnit) { 623 // If we need to emit noops prior to this instruction, then do so. 624 unsigned NumPreNoops = HazardRec->PreEmitNoops(FoundSUnit); 625 for (unsigned i = 0; i != NumPreNoops; ++i) 626 emitNoop(CurCycle); 627 628 // ... schedule the node... 629 ScheduleNodeTopDown(FoundSUnit, CurCycle); 630 HazardRec->EmitInstruction(FoundSUnit); 631 CycleHasInsts = true; 632 if (HazardRec->atIssueLimit()) { 633 DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n'); 634 HazardRec->AdvanceCycle(); 635 ++CurCycle; 636 CycleHasInsts = false; 637 } 638 } else { 639 if (CycleHasInsts) { 640 DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n'); 641 HazardRec->AdvanceCycle(); 642 } else if (!HasNoopHazards) { 643 // Otherwise, we have a pipeline stall, but no other problem, 644 // just advance the current cycle and try again. 645 DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n'); 646 HazardRec->AdvanceCycle(); 647 ++NumStalls; 648 } else { 649 // Otherwise, we have no instructions to issue and we have instructions 650 // that will fault if we don't do this right. This is the case for 651 // processors without pipeline interlocks and other cases. 652 emitNoop(CurCycle); 653 } 654 655 ++CurCycle; 656 CycleHasInsts = false; 657 } 658 } 659 660 #ifndef NDEBUG 661 unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false); 662 unsigned Noops = 0; 663 for (unsigned i = 0, e = Sequence.size(); i != e; ++i) 664 if (!Sequence[i]) 665 ++Noops; 666 assert(Sequence.size() - Noops == ScheduledNodes && 667 "The number of nodes scheduled doesn't match the expected number!"); 668 #endif // NDEBUG 669 } 670 671 // EmitSchedule - Emit the machine code in scheduled order. 672 void SchedulePostRATDList::EmitSchedule() { 673 RegionBegin = RegionEnd; 674 675 // If first instruction was a DBG_VALUE then put it back. 676 if (FirstDbgValue) 677 BB->splice(RegionEnd, BB, FirstDbgValue); 678 679 // Then re-insert them according to the given schedule. 680 for (unsigned i = 0, e = Sequence.size(); i != e; i++) { 681 if (SUnit *SU = Sequence[i]) 682 BB->splice(RegionEnd, BB, SU->getInstr()); 683 else 684 // Null SUnit* is a noop. 685 TII->insertNoop(*BB, RegionEnd); 686 687 // Update the Begin iterator, as the first instruction in the block 688 // may have been scheduled later. 689 if (i == 0) 690 RegionBegin = std::prev(RegionEnd); 691 } 692 693 // Reinsert any remaining debug_values. 694 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator 695 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) { 696 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI); 697 MachineInstr *DbgValue = P.first; 698 MachineBasicBlock::iterator OrigPrivMI = P.second; 699 BB->splice(++OrigPrivMI, BB, DbgValue); 700 } 701 DbgValues.clear(); 702 FirstDbgValue = nullptr; 703 } 704