PostRASchedulerList.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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 "llvm/CodeGen/Passes.h"
  21. #include "AggressiveAntiDepBreaker.h"
  22. #include "AntiDepBreaker.h"
  23. #include "CriticalAntiDepBreaker.h"
  24. #include "llvm/ADT/BitVector.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/Analysis/AliasAnalysis.h"
  27. #include "llvm/CodeGen/LatencyPriorityQueue.h"
  28. #include "llvm/CodeGen/MachineDominators.h"
  29. #include "llvm/CodeGen/MachineFrameInfo.h"
  30. #include "llvm/CodeGen/MachineFunctionPass.h"
  31. #include "llvm/CodeGen/MachineLoopInfo.h"
  32. #include "llvm/CodeGen/MachineRegisterInfo.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/TargetMachine.h"
  44. #include "llvm/Target/TargetRegisterInfo.h"
  45. #include "llvm/Target/TargetSubtargetInfo.h"
  46. using namespace llvm;
  47. #define DEBUG_TYPE "post-RA-sched"
  48. STATISTIC(NumNoops, "Number of noops inserted");
  49. STATISTIC(NumStalls, "Number of pipeline stalls");
  50. STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
  51. // Post-RA scheduling is enabled with
  52. // TargetSubtargetInfo.enablePostRAScheduler(). This flag can be used to
  53. // override the target.
  54. static cl::opt<bool>
  55. EnablePostRAScheduler("post-RA-scheduler",
  56. cl::desc("Enable scheduling after register allocation"),
  57. cl::init(false), cl::Hidden);
  58. static cl::opt<std::string>
  59. EnableAntiDepBreaking("break-anti-dependencies",
  60. cl::desc("Break post-RA scheduling anti-dependencies: "
  61. "\"critical\", \"all\", or \"none\""),
  62. cl::init("none"), cl::Hidden);
  63. // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
  64. static cl::opt<int>
  65. DebugDiv("postra-sched-debugdiv",
  66. cl::desc("Debug control MBBs that are scheduled"),
  67. cl::init(0), cl::Hidden);
  68. static cl::opt<int>
  69. DebugMod("postra-sched-debugmod",
  70. cl::desc("Debug control MBBs that are scheduled"),
  71. cl::init(0), cl::Hidden);
  72. AntiDepBreaker::~AntiDepBreaker() { }
  73. namespace {
  74. class PostRAScheduler : public MachineFunctionPass {
  75. const TargetInstrInfo *TII;
  76. RegisterClassInfo RegClassInfo;
  77. public:
  78. static char ID;
  79. PostRAScheduler() : MachineFunctionPass(ID) {}
  80. void getAnalysisUsage(AnalysisUsage &AU) const override {
  81. AU.setPreservesCFG();
  82. AU.addRequired<AliasAnalysis>();
  83. AU.addRequired<TargetPassConfig>();
  84. AU.addRequired<MachineDominatorTree>();
  85. AU.addPreserved<MachineDominatorTree>();
  86. AU.addRequired<MachineLoopInfo>();
  87. AU.addPreserved<MachineLoopInfo>();
  88. MachineFunctionPass::getAnalysisUsage(AU);
  89. }
  90. bool runOnMachineFunction(MachineFunction &Fn) override;
  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. /// The index in BB of RegionEnd.
  115. ///
  116. /// This is the instruction number from the top of the current block, not
  117. /// the SlotIndex. It is only used by the AntiDepBreaker.
  118. unsigned EndIndex;
  119. public:
  120. SchedulePostRATDList(
  121. MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
  122. AliasAnalysis *AA, const RegisterClassInfo&,
  123. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
  124. SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs);
  125. ~SchedulePostRATDList();
  126. /// startBlock - Initialize register live-range state for scheduling in
  127. /// this block.
  128. ///
  129. void startBlock(MachineBasicBlock *BB) override;
  130. // Set the index of RegionEnd within the current BB.
  131. void setEndIndex(unsigned EndIdx) { EndIndex = EndIdx; }
  132. /// Initialize the scheduler state for the next scheduling region.
  133. void enterRegion(MachineBasicBlock *bb,
  134. MachineBasicBlock::iterator begin,
  135. MachineBasicBlock::iterator end,
  136. unsigned regioninstrs) override;
  137. /// Notify that the scheduler has finished scheduling the current region.
  138. void exitRegion() override;
  139. /// Schedule - Schedule the instruction range using list scheduling.
  140. ///
  141. void schedule() override;
  142. void EmitSchedule();
  143. /// Observe - Update liveness information to account for the current
  144. /// instruction, which will not be scheduled.
  145. ///
  146. void Observe(MachineInstr *MI, unsigned Count);
  147. /// finishBlock - Clean up register live-range state.
  148. ///
  149. void finishBlock() override;
  150. private:
  151. void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
  152. void ReleaseSuccessors(SUnit *SU);
  153. void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
  154. void ListScheduleTopDown();
  155. void dumpSchedule() const;
  156. void emitNoop(unsigned CurCycle);
  157. };
  158. }
  159. char &llvm::PostRASchedulerID = PostRAScheduler::ID;
  160. INITIALIZE_PASS(PostRAScheduler, "post-RA-sched",
  161. "Post RA top-down list latency scheduler", false, false)
  162. SchedulePostRATDList::SchedulePostRATDList(
  163. MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
  164. AliasAnalysis *AA, const RegisterClassInfo &RCI,
  165. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
  166. SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs)
  167. : ScheduleDAGInstrs(MF, MLI, MDT, /*IsPostRA=*/true), AA(AA), EndIndex(0) {
  168. const TargetMachine &TM = MF.getTarget();
  169. const InstrItineraryData *InstrItins =
  170. TM.getSubtargetImpl()->getInstrItineraryData();
  171. HazardRec =
  172. TM.getSubtargetImpl()->getInstrInfo()->CreateTargetPostRAHazardRecognizer(
  173. InstrItins, this);
  174. assert((AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE ||
  175. MRI.tracksLiveness()) &&
  176. "Live-ins must be accurate for anti-dependency breaking");
  177. AntiDepBreak =
  178. ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) ?
  179. (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs) :
  180. ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL) ?
  181. (AntiDepBreaker *)new CriticalAntiDepBreaker(MF, RCI) : nullptr));
  182. }
  183. SchedulePostRATDList::~SchedulePostRATDList() {
  184. delete HazardRec;
  185. delete AntiDepBreak;
  186. }
  187. /// Initialize state associated with the next scheduling region.
  188. void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb,
  189. MachineBasicBlock::iterator begin,
  190. MachineBasicBlock::iterator end,
  191. unsigned regioninstrs) {
  192. ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
  193. Sequence.clear();
  194. }
  195. /// Print the schedule before exiting the region.
  196. void SchedulePostRATDList::exitRegion() {
  197. DEBUG({
  198. dbgs() << "*** Final schedule ***\n";
  199. dumpSchedule();
  200. dbgs() << '\n';
  201. });
  202. ScheduleDAGInstrs::exitRegion();
  203. }
  204. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  205. /// dumpSchedule - dump the scheduled Sequence.
  206. void SchedulePostRATDList::dumpSchedule() const {
  207. for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
  208. if (SUnit *SU = Sequence[i])
  209. SU->dump(this);
  210. else
  211. dbgs() << "**** NOOP ****\n";
  212. }
  213. }
  214. #endif
  215. bool PostRAScheduler::enablePostRAScheduler(
  216. const TargetSubtargetInfo &ST,
  217. CodeGenOpt::Level OptLevel,
  218. TargetSubtargetInfo::AntiDepBreakMode &Mode,
  219. TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const {
  220. Mode = ST.getAntiDepBreakMode();
  221. ST.getCriticalPathRCs(CriticalPathRCs);
  222. return ST.enablePostMachineScheduler() &&
  223. OptLevel >= ST.getOptLevelToEnablePostRAScheduler();
  224. }
  225. bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
  226. if (skipOptnoneFunction(*Fn.getFunction()))
  227. return false;
  228. TII = Fn.getTarget().getSubtargetImpl()->getInstrInfo();
  229. MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
  230. MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
  231. AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
  232. TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
  233. RegClassInfo.runOnMachineFunction(Fn);
  234. // Check for explicit enable/disable of post-ra scheduling.
  235. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
  236. TargetSubtargetInfo::ANTIDEP_NONE;
  237. SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
  238. if (EnablePostRAScheduler.getPosition() > 0) {
  239. if (!EnablePostRAScheduler)
  240. return false;
  241. } else {
  242. // Check that post-RA scheduling is enabled for this target.
  243. // This may upgrade the AntiDepMode.
  244. const TargetSubtargetInfo &ST =
  245. Fn.getTarget().getSubtarget<TargetSubtargetInfo>();
  246. if (!enablePostRAScheduler(ST, PassConfig->getOptLevel(),
  247. AntiDepMode, CriticalPathRCs))
  248. return false;
  249. }
  250. // Check for antidep breaking override...
  251. if (EnableAntiDepBreaking.getPosition() > 0) {
  252. AntiDepMode = (EnableAntiDepBreaking == "all")
  253. ? TargetSubtargetInfo::ANTIDEP_ALL
  254. : ((EnableAntiDepBreaking == "critical")
  255. ? TargetSubtargetInfo::ANTIDEP_CRITICAL
  256. : TargetSubtargetInfo::ANTIDEP_NONE);
  257. }
  258. DEBUG(dbgs() << "PostRAScheduler\n");
  259. SchedulePostRATDList Scheduler(Fn, MLI, MDT, AA, RegClassInfo, AntiDepMode,
  260. CriticalPathRCs);
  261. // Loop over all of the basic blocks
  262. for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
  263. MBB != MBBe; ++MBB) {
  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. << ":BB#" << MBB->getNumber() << " ***\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. DEBUG(dbgs() << "********** List Scheduling **********\n");
  348. DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  349. SUnits[su].dumpAll(this));
  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. //===----------------------------------------------------------------------===//
  370. // Top-Down Scheduling
  371. //===----------------------------------------------------------------------===//
  372. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
  373. /// the PendingQueue if the count reaches zero.
  374. void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
  375. SUnit *SuccSU = SuccEdge->getSUnit();
  376. if (SuccEdge->isWeak()) {
  377. --SuccSU->WeakPredsLeft;
  378. return;
  379. }
  380. #ifndef NDEBUG
  381. if (SuccSU->NumPredsLeft == 0) {
  382. dbgs() << "*** Scheduling failed! ***\n";
  383. SuccSU->dump(this);
  384. dbgs() << " has been released too many times!\n";
  385. llvm_unreachable(nullptr);
  386. }
  387. #endif
  388. --SuccSU->NumPredsLeft;
  389. // Standard scheduler algorithms will recompute the depth of the successor
  390. // here as such:
  391. // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
  392. //
  393. // However, we lazily compute node depth instead. Note that
  394. // ScheduleNodeTopDown has already updated the depth of this node which causes
  395. // all descendents to be marked dirty. Setting the successor depth explicitly
  396. // here would cause depth to be recomputed for all its ancestors. If the
  397. // successor is not yet ready (because of a transitively redundant edge) then
  398. // this causes depth computation to be quadratic in the size of the DAG.
  399. // If all the node's predecessors are scheduled, this node is ready
  400. // to be scheduled. Ignore the special ExitSU node.
  401. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  402. PendingQueue.push_back(SuccSU);
  403. }
  404. /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
  405. void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
  406. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  407. I != E; ++I) {
  408. ReleaseSucc(SU, &*I);
  409. }
  410. }
  411. /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
  412. /// count of its successors. If a successor pending count is zero, add it to
  413. /// the Available queue.
  414. void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
  415. DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
  416. DEBUG(SU->dump(this));
  417. Sequence.push_back(SU);
  418. assert(CurCycle >= SU->getDepth() &&
  419. "Node scheduled above its depth!");
  420. SU->setDepthToAtLeast(CurCycle);
  421. ReleaseSuccessors(SU);
  422. SU->isScheduled = true;
  423. AvailableQueue.scheduledNode(SU);
  424. }
  425. /// emitNoop - Add a noop to the current instruction sequence.
  426. void SchedulePostRATDList::emitNoop(unsigned CurCycle) {
  427. DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
  428. HazardRec->EmitNoop();
  429. Sequence.push_back(nullptr); // NULL here means noop
  430. ++NumNoops;
  431. }
  432. /// ListScheduleTopDown - The main loop of list scheduling for top-down
  433. /// schedulers.
  434. void SchedulePostRATDList::ListScheduleTopDown() {
  435. unsigned CurCycle = 0;
  436. // We're scheduling top-down but we're visiting the regions in
  437. // bottom-up order, so we don't know the hazards at the start of a
  438. // region. So assume no hazards (this should usually be ok as most
  439. // blocks are a single region).
  440. HazardRec->Reset();
  441. // Release any successors of the special Entry node.
  442. ReleaseSuccessors(&EntrySU);
  443. // Add all leaves to Available queue.
  444. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  445. // It is available if it has no predecessors.
  446. if (!SUnits[i].NumPredsLeft && !SUnits[i].isAvailable) {
  447. AvailableQueue.push(&SUnits[i]);
  448. SUnits[i].isAvailable = true;
  449. }
  450. }
  451. // In any cycle where we can't schedule any instructions, we must
  452. // stall or emit a noop, depending on the target.
  453. bool CycleHasInsts = false;
  454. // While Available queue is not empty, grab the node with the highest
  455. // priority. If it is not ready put it back. Schedule the node.
  456. std::vector<SUnit*> NotReady;
  457. Sequence.reserve(SUnits.size());
  458. while (!AvailableQueue.empty() || !PendingQueue.empty()) {
  459. // Check to see if any of the pending instructions are ready to issue. If
  460. // so, add them to the available queue.
  461. unsigned MinDepth = ~0u;
  462. for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
  463. if (PendingQueue[i]->getDepth() <= CurCycle) {
  464. AvailableQueue.push(PendingQueue[i]);
  465. PendingQueue[i]->isAvailable = true;
  466. PendingQueue[i] = PendingQueue.back();
  467. PendingQueue.pop_back();
  468. --i; --e;
  469. } else if (PendingQueue[i]->getDepth() < MinDepth)
  470. MinDepth = PendingQueue[i]->getDepth();
  471. }
  472. DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
  473. SUnit *FoundSUnit = nullptr, *NotPreferredSUnit = nullptr;
  474. bool HasNoopHazards = false;
  475. while (!AvailableQueue.empty()) {
  476. SUnit *CurSUnit = AvailableQueue.pop();
  477. ScheduleHazardRecognizer::HazardType HT =
  478. HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
  479. if (HT == ScheduleHazardRecognizer::NoHazard) {
  480. if (HazardRec->ShouldPreferAnother(CurSUnit)) {
  481. if (!NotPreferredSUnit) {
  482. // If this is the first non-preferred node for this cycle, then
  483. // record it and continue searching for a preferred node. If this
  484. // is not the first non-preferred node, then treat it as though
  485. // there had been a hazard.
  486. NotPreferredSUnit = CurSUnit;
  487. continue;
  488. }
  489. } else {
  490. FoundSUnit = CurSUnit;
  491. break;
  492. }
  493. }
  494. // Remember if this is a noop hazard.
  495. HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
  496. NotReady.push_back(CurSUnit);
  497. }
  498. // If we have a non-preferred node, push it back onto the available list.
  499. // If we did not find a preferred node, then schedule this first
  500. // non-preferred node.
  501. if (NotPreferredSUnit) {
  502. if (!FoundSUnit) {
  503. DEBUG(dbgs() << "*** Will schedule a non-preferred instruction...\n");
  504. FoundSUnit = NotPreferredSUnit;
  505. } else {
  506. AvailableQueue.push(NotPreferredSUnit);
  507. }
  508. NotPreferredSUnit = nullptr;
  509. }
  510. // Add the nodes that aren't ready back onto the available list.
  511. if (!NotReady.empty()) {
  512. AvailableQueue.push_all(NotReady);
  513. NotReady.clear();
  514. }
  515. // If we found a node to schedule...
  516. if (FoundSUnit) {
  517. // If we need to emit noops prior to this instruction, then do so.
  518. unsigned NumPreNoops = HazardRec->PreEmitNoops(FoundSUnit);
  519. for (unsigned i = 0; i != NumPreNoops; ++i)
  520. emitNoop(CurCycle);
  521. // ... schedule the node...
  522. ScheduleNodeTopDown(FoundSUnit, CurCycle);
  523. HazardRec->EmitInstruction(FoundSUnit);
  524. CycleHasInsts = true;
  525. if (HazardRec->atIssueLimit()) {
  526. DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
  527. HazardRec->AdvanceCycle();
  528. ++CurCycle;
  529. CycleHasInsts = false;
  530. }
  531. } else {
  532. if (CycleHasInsts) {
  533. DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
  534. HazardRec->AdvanceCycle();
  535. } else if (!HasNoopHazards) {
  536. // Otherwise, we have a pipeline stall, but no other problem,
  537. // just advance the current cycle and try again.
  538. DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
  539. HazardRec->AdvanceCycle();
  540. ++NumStalls;
  541. } else {
  542. // Otherwise, we have no instructions to issue and we have instructions
  543. // that will fault if we don't do this right. This is the case for
  544. // processors without pipeline interlocks and other cases.
  545. emitNoop(CurCycle);
  546. }
  547. ++CurCycle;
  548. CycleHasInsts = false;
  549. }
  550. }
  551. #ifndef NDEBUG
  552. unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
  553. unsigned Noops = 0;
  554. for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
  555. if (!Sequence[i])
  556. ++Noops;
  557. assert(Sequence.size() - Noops == ScheduledNodes &&
  558. "The number of nodes scheduled doesn't match the expected number!");
  559. #endif // NDEBUG
  560. }
  561. // EmitSchedule - Emit the machine code in scheduled order.
  562. void SchedulePostRATDList::EmitSchedule() {
  563. RegionBegin = RegionEnd;
  564. // If first instruction was a DBG_VALUE then put it back.
  565. if (FirstDbgValue)
  566. BB->splice(RegionEnd, BB, FirstDbgValue);
  567. // Then re-insert them according to the given schedule.
  568. for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
  569. if (SUnit *SU = Sequence[i])
  570. BB->splice(RegionEnd, BB, SU->getInstr());
  571. else
  572. // Null SUnit* is a noop.
  573. TII->insertNoop(*BB, RegionEnd);
  574. // Update the Begin iterator, as the first instruction in the block
  575. // may have been scheduled later.
  576. if (i == 0)
  577. RegionBegin = std::prev(RegionEnd);
  578. }
  579. // Reinsert any remaining debug_values.
  580. for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
  581. DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
  582. std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
  583. MachineInstr *DbgValue = P.first;
  584. MachineBasicBlock::iterator OrigPrivMI = P.second;
  585. BB->splice(++OrigPrivMI, BB, DbgValue);
  586. }
  587. DbgValues.clear();
  588. FirstDbgValue = nullptr;
  589. }