PostRASchedulerList.cpp 24 KB

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