PostRASchedulerList.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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. #define DEBUG_TYPE "post-RA-sched"
  21. #include "AntiDepBreaker.h"
  22. #include "AggressiveAntiDepBreaker.h"
  23. #include "CriticalAntiDepBreaker.h"
  24. #include "RegisterClassInfo.h"
  25. #include "ScheduleDAGInstrs.h"
  26. #include "llvm/CodeGen/Passes.h"
  27. #include "llvm/CodeGen/LatencyPriorityQueue.h"
  28. #include "llvm/CodeGen/SchedulerRegistry.h"
  29. #include "llvm/CodeGen/MachineDominators.h"
  30. #include "llvm/CodeGen/MachineFrameInfo.h"
  31. #include "llvm/CodeGen/MachineFunctionPass.h"
  32. #include "llvm/CodeGen/MachineLoopInfo.h"
  33. #include "llvm/CodeGen/MachineRegisterInfo.h"
  34. #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
  35. #include "llvm/Analysis/AliasAnalysis.h"
  36. #include "llvm/Target/TargetLowering.h"
  37. #include "llvm/Target/TargetMachine.h"
  38. #include "llvm/Target/TargetInstrInfo.h"
  39. #include "llvm/Target/TargetRegisterInfo.h"
  40. #include "llvm/Target/TargetSubtargetInfo.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. #include "llvm/ADT/BitVector.h"
  46. #include "llvm/ADT/Statistic.h"
  47. #include <set>
  48. using namespace llvm;
  49. STATISTIC(NumNoops, "Number of noops inserted");
  50. STATISTIC(NumStalls, "Number of pipeline stalls");
  51. STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
  52. // Post-RA scheduling is enabled with
  53. // TargetSubtargetInfo.enablePostRAScheduler(). This flag can be used to
  54. // override the target.
  55. static cl::opt<bool>
  56. EnablePostRAScheduler("post-RA-scheduler",
  57. cl::desc("Enable scheduling after register allocation"),
  58. cl::init(false), cl::Hidden);
  59. static cl::opt<std::string>
  60. EnableAntiDepBreaking("break-anti-dependencies",
  61. cl::desc("Break post-RA scheduling anti-dependencies: "
  62. "\"critical\", \"all\", or \"none\""),
  63. cl::init("none"), cl::Hidden);
  64. // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
  65. static cl::opt<int>
  66. DebugDiv("postra-sched-debugdiv",
  67. cl::desc("Debug control MBBs that are scheduled"),
  68. cl::init(0), cl::Hidden);
  69. static cl::opt<int>
  70. DebugMod("postra-sched-debugmod",
  71. cl::desc("Debug control MBBs that are scheduled"),
  72. cl::init(0), cl::Hidden);
  73. AntiDepBreaker::~AntiDepBreaker() { }
  74. namespace {
  75. class PostRAScheduler : public MachineFunctionPass {
  76. AliasAnalysis *AA;
  77. const TargetInstrInfo *TII;
  78. RegisterClassInfo RegClassInfo;
  79. CodeGenOpt::Level OptLevel;
  80. public:
  81. static char ID;
  82. PostRAScheduler(CodeGenOpt::Level ol) :
  83. MachineFunctionPass(ID), OptLevel(ol) {}
  84. void getAnalysisUsage(AnalysisUsage &AU) const {
  85. AU.setPreservesCFG();
  86. AU.addRequired<AliasAnalysis>();
  87. AU.addRequired<MachineDominatorTree>();
  88. AU.addPreserved<MachineDominatorTree>();
  89. AU.addRequired<MachineLoopInfo>();
  90. AU.addPreserved<MachineLoopInfo>();
  91. MachineFunctionPass::getAnalysisUsage(AU);
  92. }
  93. const char *getPassName() const {
  94. return "Post RA top-down list latency scheduler";
  95. }
  96. bool runOnMachineFunction(MachineFunction &Fn);
  97. };
  98. char PostRAScheduler::ID = 0;
  99. class SchedulePostRATDList : public ScheduleDAGInstrs {
  100. /// AvailableQueue - The priority queue to use for the available SUnits.
  101. ///
  102. LatencyPriorityQueue AvailableQueue;
  103. /// PendingQueue - This contains all of the instructions whose operands have
  104. /// been issued, but their results are not ready yet (due to the latency of
  105. /// the operation). Once the operands becomes available, the instruction is
  106. /// added to the AvailableQueue.
  107. std::vector<SUnit*> PendingQueue;
  108. /// Topo - A topological ordering for SUnits.
  109. ScheduleDAGTopologicalSort Topo;
  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. /// KillIndices - The index of the most recent kill (proceding bottom-up),
  117. /// or ~0u if the register is not live.
  118. std::vector<unsigned> KillIndices;
  119. public:
  120. SchedulePostRATDList(
  121. MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
  122. AliasAnalysis *AA, const RegisterClassInfo&,
  123. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
  124. SmallVectorImpl<TargetRegisterClass*> &CriticalPathRCs);
  125. ~SchedulePostRATDList();
  126. /// StartBlock - Initialize register live-range state for scheduling in
  127. /// this block.
  128. ///
  129. void StartBlock(MachineBasicBlock *BB);
  130. /// Schedule - Schedule the instruction range using list scheduling.
  131. ///
  132. void Schedule();
  133. /// Observe - Update liveness information to account for the current
  134. /// instruction, which will not be scheduled.
  135. ///
  136. void Observe(MachineInstr *MI, unsigned Count);
  137. /// FinishBlock - Clean up register live-range state.
  138. ///
  139. void FinishBlock();
  140. /// FixupKills - Fix register kill flags that have been made
  141. /// invalid due to scheduling
  142. ///
  143. void FixupKills(MachineBasicBlock *MBB);
  144. private:
  145. void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
  146. void ReleaseSuccessors(SUnit *SU);
  147. void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
  148. void ListScheduleTopDown();
  149. void StartBlockForKills(MachineBasicBlock *BB);
  150. // ToggleKillFlag - Toggle a register operand kill flag. Other
  151. // adjustments may be made to the instruction if necessary. Return
  152. // true if the operand has been deleted, false if not.
  153. bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
  154. };
  155. }
  156. SchedulePostRATDList::SchedulePostRATDList(
  157. MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
  158. AliasAnalysis *AA, const RegisterClassInfo &RCI,
  159. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
  160. SmallVectorImpl<TargetRegisterClass*> &CriticalPathRCs)
  161. : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits), AA(AA),
  162. KillIndices(TRI->getNumRegs())
  163. {
  164. const TargetMachine &TM = MF.getTarget();
  165. const InstrItineraryData *InstrItins = TM.getInstrItineraryData();
  166. HazardRec =
  167. TM.getInstrInfo()->CreateTargetPostRAHazardRecognizer(InstrItins, this);
  168. AntiDepBreak =
  169. ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) ?
  170. (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs) :
  171. ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL) ?
  172. (AntiDepBreaker *)new CriticalAntiDepBreaker(MF, RCI) : NULL));
  173. }
  174. SchedulePostRATDList::~SchedulePostRATDList() {
  175. delete HazardRec;
  176. delete AntiDepBreak;
  177. }
  178. bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
  179. TII = Fn.getTarget().getInstrInfo();
  180. MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
  181. MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
  182. AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
  183. RegClassInfo.runOnMachineFunction(Fn);
  184. // Check for explicit enable/disable of post-ra scheduling.
  185. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
  186. TargetSubtargetInfo::ANTIDEP_NONE;
  187. SmallVector<TargetRegisterClass*, 4> CriticalPathRCs;
  188. if (EnablePostRAScheduler.getPosition() > 0) {
  189. if (!EnablePostRAScheduler)
  190. return false;
  191. } else {
  192. // Check that post-RA scheduling is enabled for this target.
  193. // This may upgrade the AntiDepMode.
  194. const TargetSubtargetInfo &ST = Fn.getTarget().getSubtarget<TargetSubtargetInfo>();
  195. if (!ST.enablePostRAScheduler(OptLevel, AntiDepMode, CriticalPathRCs))
  196. return false;
  197. }
  198. // Check for antidep breaking override...
  199. if (EnableAntiDepBreaking.getPosition() > 0) {
  200. AntiDepMode = (EnableAntiDepBreaking == "all")
  201. ? TargetSubtargetInfo::ANTIDEP_ALL
  202. : ((EnableAntiDepBreaking == "critical")
  203. ? TargetSubtargetInfo::ANTIDEP_CRITICAL
  204. : TargetSubtargetInfo::ANTIDEP_NONE);
  205. }
  206. DEBUG(dbgs() << "PostRAScheduler\n");
  207. SchedulePostRATDList Scheduler(Fn, MLI, MDT, AA, RegClassInfo, AntiDepMode,
  208. CriticalPathRCs);
  209. // Loop over all of the basic blocks
  210. for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
  211. MBB != MBBe; ++MBB) {
  212. #ifndef NDEBUG
  213. // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
  214. if (DebugDiv > 0) {
  215. static int bbcnt = 0;
  216. if (bbcnt++ % DebugDiv != DebugMod)
  217. continue;
  218. dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getName()
  219. << ":BB#" << MBB->getNumber() << " ***\n";
  220. }
  221. #endif
  222. // Initialize register live-range state for scheduling in this block.
  223. Scheduler.StartBlock(MBB);
  224. // Schedule each sequence of instructions not interrupted by a label
  225. // or anything else that effectively needs to shut down scheduling.
  226. MachineBasicBlock::iterator Current = MBB->end();
  227. unsigned Count = MBB->size(), CurrentCount = Count;
  228. for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
  229. MachineInstr *MI = llvm::prior(I);
  230. if (TII->isSchedulingBoundary(MI, MBB, Fn)) {
  231. Scheduler.Run(MBB, I, Current, CurrentCount);
  232. Scheduler.EmitSchedule();
  233. Current = MI;
  234. CurrentCount = Count - 1;
  235. Scheduler.Observe(MI, CurrentCount);
  236. }
  237. I = MI;
  238. --Count;
  239. if (MI->isBundle())
  240. Count -= MI->getBundleSize();
  241. }
  242. assert(Count == 0 && "Instruction count mismatch!");
  243. assert((MBB->begin() == Current || CurrentCount != 0) &&
  244. "Instruction count mismatch!");
  245. Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
  246. Scheduler.EmitSchedule();
  247. // Clean up register live-range state.
  248. Scheduler.FinishBlock();
  249. // Update register kills
  250. Scheduler.FixupKills(MBB);
  251. }
  252. return true;
  253. }
  254. /// StartBlock - Initialize register live-range state for scheduling in
  255. /// this block.
  256. ///
  257. void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
  258. // Call the superclass.
  259. ScheduleDAGInstrs::StartBlock(BB);
  260. // Reset the hazard recognizer and anti-dep breaker.
  261. HazardRec->Reset();
  262. if (AntiDepBreak != NULL)
  263. AntiDepBreak->StartBlock(BB);
  264. }
  265. /// Schedule - Schedule the instruction range using list scheduling.
  266. ///
  267. void SchedulePostRATDList::Schedule() {
  268. // Build the scheduling graph.
  269. BuildSchedGraph(AA);
  270. if (AntiDepBreak != NULL) {
  271. unsigned Broken =
  272. AntiDepBreak->BreakAntiDependencies(SUnits, Begin, InsertPos,
  273. InsertPosIndex, DbgValues);
  274. if (Broken != 0) {
  275. // We made changes. Update the dependency graph.
  276. // Theoretically we could update the graph in place:
  277. // When a live range is changed to use a different register, remove
  278. // the def's anti-dependence *and* output-dependence edges due to
  279. // that register, and add new anti-dependence and output-dependence
  280. // edges based on the next live range of the register.
  281. SUnits.clear();
  282. Sequence.clear();
  283. EntrySU = SUnit();
  284. ExitSU = SUnit();
  285. BuildSchedGraph(AA);
  286. NumFixedAnti += Broken;
  287. }
  288. }
  289. DEBUG(dbgs() << "********** List Scheduling **********\n");
  290. DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  291. SUnits[su].dumpAll(this));
  292. AvailableQueue.initNodes(SUnits);
  293. ListScheduleTopDown();
  294. AvailableQueue.releaseState();
  295. }
  296. /// Observe - Update liveness information to account for the current
  297. /// instruction, which will not be scheduled.
  298. ///
  299. void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
  300. if (AntiDepBreak != NULL)
  301. AntiDepBreak->Observe(MI, Count, InsertPosIndex);
  302. }
  303. /// FinishBlock - Clean up register live-range state.
  304. ///
  305. void SchedulePostRATDList::FinishBlock() {
  306. if (AntiDepBreak != NULL)
  307. AntiDepBreak->FinishBlock();
  308. // Call the superclass.
  309. ScheduleDAGInstrs::FinishBlock();
  310. }
  311. /// StartBlockForKills - Initialize register live-range state for updating kills
  312. ///
  313. void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
  314. // Initialize the indices to indicate that no registers are live.
  315. for (unsigned i = 0; i < TRI->getNumRegs(); ++i)
  316. KillIndices[i] = ~0u;
  317. // Determine the live-out physregs for this block.
  318. if (!BB->empty() && BB->back().isReturn()) {
  319. // In a return block, examine the function live-out regs.
  320. for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
  321. E = MRI.liveout_end(); I != E; ++I) {
  322. unsigned Reg = *I;
  323. KillIndices[Reg] = BB->size();
  324. // Repeat, for all subregs.
  325. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  326. *Subreg; ++Subreg) {
  327. KillIndices[*Subreg] = BB->size();
  328. }
  329. }
  330. }
  331. else {
  332. // In a non-return block, examine the live-in regs of all successors.
  333. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  334. SE = BB->succ_end(); SI != SE; ++SI) {
  335. for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
  336. E = (*SI)->livein_end(); I != E; ++I) {
  337. unsigned Reg = *I;
  338. KillIndices[Reg] = BB->size();
  339. // Repeat, for all subregs.
  340. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  341. *Subreg; ++Subreg) {
  342. KillIndices[*Subreg] = BB->size();
  343. }
  344. }
  345. }
  346. }
  347. }
  348. bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
  349. MachineOperand &MO) {
  350. // Setting kill flag...
  351. if (!MO.isKill()) {
  352. MO.setIsKill(true);
  353. return false;
  354. }
  355. // If MO itself is live, clear the kill flag...
  356. if (KillIndices[MO.getReg()] != ~0u) {
  357. MO.setIsKill(false);
  358. return false;
  359. }
  360. // If any subreg of MO is live, then create an imp-def for that
  361. // subreg and keep MO marked as killed.
  362. MO.setIsKill(false);
  363. bool AllDead = true;
  364. const unsigned SuperReg = MO.getReg();
  365. for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
  366. *Subreg; ++Subreg) {
  367. if (KillIndices[*Subreg] != ~0u) {
  368. MI->addOperand(MachineOperand::CreateReg(*Subreg,
  369. true /*IsDef*/,
  370. true /*IsImp*/,
  371. false /*IsKill*/,
  372. false /*IsDead*/));
  373. AllDead = false;
  374. }
  375. }
  376. if(AllDead)
  377. MO.setIsKill(true);
  378. return false;
  379. }
  380. /// FixupKills - Fix the register kill flags, they may have been made
  381. /// incorrect by instruction reordering.
  382. ///
  383. void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
  384. DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
  385. std::set<unsigned> killedRegs;
  386. BitVector ReservedRegs = TRI->getReservedRegs(MF);
  387. StartBlockForKills(MBB);
  388. // Examine block from end to start...
  389. unsigned Count = MBB->size();
  390. for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
  391. I != E; --Count) {
  392. MachineInstr *MI = --I;
  393. if (MI->isDebugValue())
  394. continue;
  395. // Update liveness. Registers that are defed but not used in this
  396. // instruction are now dead. Mark register and all subregs as they
  397. // are completely defined.
  398. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  399. MachineOperand &MO = MI->getOperand(i);
  400. if (!MO.isReg()) continue;
  401. unsigned Reg = MO.getReg();
  402. if (Reg == 0) continue;
  403. if (!MO.isDef()) continue;
  404. // Ignore two-addr defs.
  405. if (MI->isRegTiedToUseOperand(i)) continue;
  406. KillIndices[Reg] = ~0u;
  407. // Repeat for all subregs.
  408. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  409. *Subreg; ++Subreg) {
  410. KillIndices[*Subreg] = ~0u;
  411. }
  412. }
  413. // Examine all used registers and set/clear kill flag. When a
  414. // register is used multiple times we only set the kill flag on
  415. // the first use.
  416. killedRegs.clear();
  417. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  418. MachineOperand &MO = MI->getOperand(i);
  419. if (!MO.isReg() || !MO.isUse()) continue;
  420. unsigned Reg = MO.getReg();
  421. if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
  422. bool kill = false;
  423. if (killedRegs.find(Reg) == killedRegs.end()) {
  424. kill = true;
  425. // A register is not killed if any subregs are live...
  426. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  427. *Subreg; ++Subreg) {
  428. if (KillIndices[*Subreg] != ~0u) {
  429. kill = false;
  430. break;
  431. }
  432. }
  433. // If subreg is not live, then register is killed if it became
  434. // live in this instruction
  435. if (kill)
  436. kill = (KillIndices[Reg] == ~0u);
  437. }
  438. if (MO.isKill() != kill) {
  439. DEBUG(dbgs() << "Fixing " << MO << " in ");
  440. // Warning: ToggleKillFlag may invalidate MO.
  441. ToggleKillFlag(MI, MO);
  442. DEBUG(MI->dump());
  443. }
  444. killedRegs.insert(Reg);
  445. }
  446. // Mark any used register (that is not using undef) and subregs as
  447. // now live...
  448. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  449. MachineOperand &MO = MI->getOperand(i);
  450. if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
  451. unsigned Reg = MO.getReg();
  452. if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
  453. KillIndices[Reg] = Count;
  454. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  455. *Subreg; ++Subreg) {
  456. KillIndices[*Subreg] = Count;
  457. }
  458. }
  459. }
  460. }
  461. //===----------------------------------------------------------------------===//
  462. // Top-Down Scheduling
  463. //===----------------------------------------------------------------------===//
  464. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
  465. /// the PendingQueue if the count reaches zero. Also update its cycle bound.
  466. void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
  467. SUnit *SuccSU = SuccEdge->getSUnit();
  468. #ifndef NDEBUG
  469. if (SuccSU->NumPredsLeft == 0) {
  470. dbgs() << "*** Scheduling failed! ***\n";
  471. SuccSU->dump(this);
  472. dbgs() << " has been released too many times!\n";
  473. llvm_unreachable(0);
  474. }
  475. #endif
  476. --SuccSU->NumPredsLeft;
  477. // Standard scheduler algorithms will recompute the depth of the successor
  478. // here as such:
  479. // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
  480. //
  481. // However, we lazily compute node depth instead. Note that
  482. // ScheduleNodeTopDown has already updated the depth of this node which causes
  483. // all descendents to be marked dirty. Setting the successor depth explicitly
  484. // here would cause depth to be recomputed for all its ancestors. If the
  485. // successor is not yet ready (because of a transitively redundant edge) then
  486. // this causes depth computation to be quadratic in the size of the DAG.
  487. // If all the node's predecessors are scheduled, this node is ready
  488. // to be scheduled. Ignore the special ExitSU node.
  489. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  490. PendingQueue.push_back(SuccSU);
  491. }
  492. /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
  493. void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
  494. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  495. I != E; ++I) {
  496. ReleaseSucc(SU, &*I);
  497. }
  498. }
  499. /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
  500. /// count of its successors. If a successor pending count is zero, add it to
  501. /// the Available queue.
  502. void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
  503. DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
  504. DEBUG(SU->dump(this));
  505. Sequence.push_back(SU);
  506. assert(CurCycle >= SU->getDepth() &&
  507. "Node scheduled above its depth!");
  508. SU->setDepthToAtLeast(CurCycle);
  509. ReleaseSuccessors(SU);
  510. SU->isScheduled = true;
  511. AvailableQueue.ScheduledNode(SU);
  512. }
  513. /// ListScheduleTopDown - The main loop of list scheduling for top-down
  514. /// schedulers.
  515. void SchedulePostRATDList::ListScheduleTopDown() {
  516. unsigned CurCycle = 0;
  517. // We're scheduling top-down but we're visiting the regions in
  518. // bottom-up order, so we don't know the hazards at the start of a
  519. // region. So assume no hazards (this should usually be ok as most
  520. // blocks are a single region).
  521. HazardRec->Reset();
  522. // Release any successors of the special Entry node.
  523. ReleaseSuccessors(&EntrySU);
  524. // Add all leaves to Available queue.
  525. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  526. // It is available if it has no predecessors.
  527. bool available = SUnits[i].Preds.empty();
  528. if (available) {
  529. AvailableQueue.push(&SUnits[i]);
  530. SUnits[i].isAvailable = true;
  531. }
  532. }
  533. // In any cycle where we can't schedule any instructions, we must
  534. // stall or emit a noop, depending on the target.
  535. bool CycleHasInsts = false;
  536. // While Available queue is not empty, grab the node with the highest
  537. // priority. If it is not ready put it back. Schedule the node.
  538. std::vector<SUnit*> NotReady;
  539. Sequence.reserve(SUnits.size());
  540. while (!AvailableQueue.empty() || !PendingQueue.empty()) {
  541. // Check to see if any of the pending instructions are ready to issue. If
  542. // so, add them to the available queue.
  543. unsigned MinDepth = ~0u;
  544. for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
  545. if (PendingQueue[i]->getDepth() <= CurCycle) {
  546. AvailableQueue.push(PendingQueue[i]);
  547. PendingQueue[i]->isAvailable = true;
  548. PendingQueue[i] = PendingQueue.back();
  549. PendingQueue.pop_back();
  550. --i; --e;
  551. } else if (PendingQueue[i]->getDepth() < MinDepth)
  552. MinDepth = PendingQueue[i]->getDepth();
  553. }
  554. DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
  555. SUnit *FoundSUnit = 0;
  556. bool HasNoopHazards = false;
  557. while (!AvailableQueue.empty()) {
  558. SUnit *CurSUnit = AvailableQueue.pop();
  559. ScheduleHazardRecognizer::HazardType HT =
  560. HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
  561. if (HT == ScheduleHazardRecognizer::NoHazard) {
  562. FoundSUnit = CurSUnit;
  563. break;
  564. }
  565. // Remember if this is a noop hazard.
  566. HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
  567. NotReady.push_back(CurSUnit);
  568. }
  569. // Add the nodes that aren't ready back onto the available list.
  570. if (!NotReady.empty()) {
  571. AvailableQueue.push_all(NotReady);
  572. NotReady.clear();
  573. }
  574. // If we found a node to schedule...
  575. if (FoundSUnit) {
  576. // ... schedule the node...
  577. ScheduleNodeTopDown(FoundSUnit, CurCycle);
  578. HazardRec->EmitInstruction(FoundSUnit);
  579. CycleHasInsts = true;
  580. if (HazardRec->atIssueLimit()) {
  581. DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
  582. HazardRec->AdvanceCycle();
  583. ++CurCycle;
  584. CycleHasInsts = false;
  585. }
  586. } else {
  587. if (CycleHasInsts) {
  588. DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
  589. HazardRec->AdvanceCycle();
  590. } else if (!HasNoopHazards) {
  591. // Otherwise, we have a pipeline stall, but no other problem,
  592. // just advance the current cycle and try again.
  593. DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
  594. HazardRec->AdvanceCycle();
  595. ++NumStalls;
  596. } else {
  597. // Otherwise, we have no instructions to issue and we have instructions
  598. // that will fault if we don't do this right. This is the case for
  599. // processors without pipeline interlocks and other cases.
  600. DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
  601. HazardRec->EmitNoop();
  602. Sequence.push_back(0); // NULL here means noop
  603. ++NumNoops;
  604. }
  605. ++CurCycle;
  606. CycleHasInsts = false;
  607. }
  608. }
  609. #ifndef NDEBUG
  610. VerifySchedule(/*isBottomUp=*/false);
  611. #endif
  612. }
  613. //===----------------------------------------------------------------------===//
  614. // Public Constructor Functions
  615. //===----------------------------------------------------------------------===//
  616. FunctionPass *llvm::createPostRAScheduler(CodeGenOpt::Level OptLevel) {
  617. return new PostRAScheduler(OptLevel);
  618. }