PostRASchedulerList.cpp 24 KB

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