PostRASchedulerList.cpp 24 KB

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