PostRASchedulerList.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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 "llvm/CodeGen/Passes.h"
  22. #include "AggressiveAntiDepBreaker.h"
  23. #include "AntiDepBreaker.h"
  24. #include "CriticalAntiDepBreaker.h"
  25. #include "llvm/ADT/BitVector.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/Analysis/AliasAnalysis.h"
  28. #include "llvm/CodeGen/LatencyPriorityQueue.h"
  29. #include "llvm/CodeGen/MachineDominators.h"
  30. #include "llvm/CodeGen/MachineFrameInfo.h"
  31. #include "llvm/CodeGen/MachineFunctionPass.h"
  32. #include "llvm/CodeGen/MachineInstrBuilder.h"
  33. #include "llvm/CodeGen/MachineLoopInfo.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/RegisterClassInfo.h"
  36. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  37. #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
  38. #include "llvm/CodeGen/SchedulerRegistry.h"
  39. #include "llvm/Support/CommandLine.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Target/TargetInstrInfo.h"
  44. #include "llvm/Target/TargetLowering.h"
  45. #include "llvm/Target/TargetMachine.h"
  46. #include "llvm/Target/TargetRegisterInfo.h"
  47. #include "llvm/Target/TargetSubtargetInfo.h"
  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. const TargetInstrInfo *TII;
  77. RegisterClassInfo RegClassInfo;
  78. public:
  79. static char ID;
  80. PostRAScheduler() : MachineFunctionPass(ID) {}
  81. void getAnalysisUsage(AnalysisUsage &AU) const {
  82. AU.setPreservesCFG();
  83. AU.addRequired<AliasAnalysis>();
  84. AU.addRequired<TargetPassConfig>();
  85. AU.addRequired<MachineDominatorTree>();
  86. AU.addPreserved<MachineDominatorTree>();
  87. AU.addRequired<MachineLoopInfo>();
  88. AU.addPreserved<MachineLoopInfo>();
  89. MachineFunctionPass::getAnalysisUsage(AU);
  90. }
  91. bool runOnMachineFunction(MachineFunction &Fn);
  92. };
  93. char PostRAScheduler::ID = 0;
  94. class SchedulePostRATDList : public ScheduleDAGInstrs {
  95. /// AvailableQueue - The priority queue to use for the available SUnits.
  96. ///
  97. LatencyPriorityQueue AvailableQueue;
  98. /// PendingQueue - This contains all of the instructions whose operands have
  99. /// been issued, but their results are not ready yet (due to the latency of
  100. /// the operation). Once the operands becomes available, the instruction is
  101. /// added to the AvailableQueue.
  102. std::vector<SUnit*> PendingQueue;
  103. /// HazardRec - The hazard recognizer to use.
  104. ScheduleHazardRecognizer *HazardRec;
  105. /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
  106. AntiDepBreaker *AntiDepBreak;
  107. /// AA - AliasAnalysis for making memory reference queries.
  108. AliasAnalysis *AA;
  109. /// LiveRegs - true if the register is live.
  110. BitVector LiveRegs;
  111. /// The schedule. Null SUnit*'s represent noop instructions.
  112. std::vector<SUnit*> Sequence;
  113. public:
  114. SchedulePostRATDList(
  115. MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
  116. AliasAnalysis *AA, const RegisterClassInfo&,
  117. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
  118. SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs);
  119. ~SchedulePostRATDList();
  120. /// startBlock - Initialize register live-range state for scheduling in
  121. /// this block.
  122. ///
  123. void startBlock(MachineBasicBlock *BB);
  124. /// Initialize the scheduler state for the next scheduling region.
  125. virtual void enterRegion(MachineBasicBlock *bb,
  126. MachineBasicBlock::iterator begin,
  127. MachineBasicBlock::iterator end,
  128. unsigned endcount);
  129. /// Notify that the scheduler has finished scheduling the current region.
  130. virtual void exitRegion();
  131. /// Schedule - Schedule the instruction range using list scheduling.
  132. ///
  133. void schedule();
  134. void EmitSchedule();
  135. /// Observe - Update liveness information to account for the current
  136. /// instruction, which will not be scheduled.
  137. ///
  138. void Observe(MachineInstr *MI, unsigned Count);
  139. /// finishBlock - Clean up register live-range state.
  140. ///
  141. void finishBlock();
  142. /// FixupKills - Fix register kill flags that have been made
  143. /// invalid due to scheduling
  144. ///
  145. void FixupKills(MachineBasicBlock *MBB);
  146. private:
  147. void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
  148. void ReleaseSuccessors(SUnit *SU);
  149. void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
  150. void ListScheduleTopDown();
  151. void StartBlockForKills(MachineBasicBlock *BB);
  152. // ToggleKillFlag - Toggle a register operand kill flag. Other
  153. // adjustments may be made to the instruction if necessary. Return
  154. // true if the operand has been deleted, false if not.
  155. bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
  156. void dumpSchedule() const;
  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),
  168. LiveRegs(TRI->getNumRegs())
  169. {
  170. const TargetMachine &TM = MF.getTarget();
  171. const InstrItineraryData *InstrItins = TM.getInstrItineraryData();
  172. HazardRec =
  173. TM.getInstrInfo()->CreateTargetPostRAHazardRecognizer(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) : NULL));
  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 endcount) {
  192. ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
  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::runOnMachineFunction(MachineFunction &Fn) {
  216. TII = Fn.getTarget().getInstrInfo();
  217. MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
  218. MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
  219. AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
  220. TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
  221. RegClassInfo.runOnMachineFunction(Fn);
  222. // Check for explicit enable/disable of post-ra scheduling.
  223. TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
  224. TargetSubtargetInfo::ANTIDEP_NONE;
  225. SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
  226. if (EnablePostRAScheduler.getPosition() > 0) {
  227. if (!EnablePostRAScheduler)
  228. return false;
  229. } else {
  230. // Check that post-RA scheduling is enabled for this target.
  231. // This may upgrade the AntiDepMode.
  232. const TargetSubtargetInfo &ST = Fn.getTarget().getSubtarget<TargetSubtargetInfo>();
  233. if (!ST.enablePostRAScheduler(PassConfig->getOptLevel(), AntiDepMode,
  234. CriticalPathRCs))
  235. return false;
  236. }
  237. // Check for antidep breaking override...
  238. if (EnableAntiDepBreaking.getPosition() > 0) {
  239. AntiDepMode = (EnableAntiDepBreaking == "all")
  240. ? TargetSubtargetInfo::ANTIDEP_ALL
  241. : ((EnableAntiDepBreaking == "critical")
  242. ? TargetSubtargetInfo::ANTIDEP_CRITICAL
  243. : TargetSubtargetInfo::ANTIDEP_NONE);
  244. }
  245. DEBUG(dbgs() << "PostRAScheduler\n");
  246. SchedulePostRATDList Scheduler(Fn, MLI, MDT, AA, RegClassInfo, AntiDepMode,
  247. CriticalPathRCs);
  248. // Loop over all of the basic blocks
  249. for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
  250. MBB != MBBe; ++MBB) {
  251. #ifndef NDEBUG
  252. // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
  253. if (DebugDiv > 0) {
  254. static int bbcnt = 0;
  255. if (bbcnt++ % DebugDiv != DebugMod)
  256. continue;
  257. dbgs() << "*** DEBUG scheduling " << Fn.getName()
  258. << ":BB#" << MBB->getNumber() << " ***\n";
  259. }
  260. #endif
  261. // Initialize register live-range state for scheduling in this block.
  262. Scheduler.startBlock(MBB);
  263. // Schedule each sequence of instructions not interrupted by a label
  264. // or anything else that effectively needs to shut down scheduling.
  265. MachineBasicBlock::iterator Current = MBB->end();
  266. unsigned Count = MBB->size(), CurrentCount = Count;
  267. for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
  268. MachineInstr *MI = llvm::prior(I);
  269. // Calls are not scheduling boundaries before register allocation, but
  270. // post-ra we don't gain anything by scheduling across calls since we
  271. // don't need to worry about register pressure.
  272. if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
  273. Scheduler.enterRegion(MBB, I, Current, CurrentCount);
  274. Scheduler.schedule();
  275. Scheduler.exitRegion();
  276. Scheduler.EmitSchedule();
  277. Current = MI;
  278. CurrentCount = Count - 1;
  279. Scheduler.Observe(MI, CurrentCount);
  280. }
  281. I = MI;
  282. --Count;
  283. if (MI->isBundle())
  284. Count -= MI->getBundleSize();
  285. }
  286. assert(Count == 0 && "Instruction count mismatch!");
  287. assert((MBB->begin() == Current || CurrentCount != 0) &&
  288. "Instruction count mismatch!");
  289. Scheduler.enterRegion(MBB, MBB->begin(), Current, CurrentCount);
  290. Scheduler.schedule();
  291. Scheduler.exitRegion();
  292. Scheduler.EmitSchedule();
  293. // Clean up register live-range state.
  294. Scheduler.finishBlock();
  295. // Update register kills
  296. Scheduler.FixupKills(MBB);
  297. }
  298. return true;
  299. }
  300. /// StartBlock - Initialize register live-range state for scheduling in
  301. /// this block.
  302. ///
  303. void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
  304. // Call the superclass.
  305. ScheduleDAGInstrs::startBlock(BB);
  306. // Reset the hazard recognizer and anti-dep breaker.
  307. HazardRec->Reset();
  308. if (AntiDepBreak != NULL)
  309. AntiDepBreak->StartBlock(BB);
  310. }
  311. /// Schedule - Schedule the instruction range using list scheduling.
  312. ///
  313. void SchedulePostRATDList::schedule() {
  314. // Build the scheduling graph.
  315. buildSchedGraph(AA);
  316. if (AntiDepBreak != NULL) {
  317. unsigned Broken =
  318. AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
  319. EndIndex, DbgValues);
  320. if (Broken != 0) {
  321. // We made changes. Update the dependency graph.
  322. // Theoretically we could update the graph in place:
  323. // When a live range is changed to use a different register, remove
  324. // the def's anti-dependence *and* output-dependence edges due to
  325. // that register, and add new anti-dependence and output-dependence
  326. // edges based on the next live range of the register.
  327. ScheduleDAG::clearDAG();
  328. buildSchedGraph(AA);
  329. NumFixedAnti += Broken;
  330. }
  331. }
  332. DEBUG(dbgs() << "********** List Scheduling **********\n");
  333. DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
  334. SUnits[su].dumpAll(this));
  335. AvailableQueue.initNodes(SUnits);
  336. ListScheduleTopDown();
  337. AvailableQueue.releaseState();
  338. }
  339. /// Observe - Update liveness information to account for the current
  340. /// instruction, which will not be scheduled.
  341. ///
  342. void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
  343. if (AntiDepBreak != NULL)
  344. AntiDepBreak->Observe(MI, Count, EndIndex);
  345. }
  346. /// FinishBlock - Clean up register live-range state.
  347. ///
  348. void SchedulePostRATDList::finishBlock() {
  349. if (AntiDepBreak != NULL)
  350. AntiDepBreak->FinishBlock();
  351. // Call the superclass.
  352. ScheduleDAGInstrs::finishBlock();
  353. }
  354. /// StartBlockForKills - Initialize register live-range state for updating kills
  355. ///
  356. void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
  357. // Start with no live registers.
  358. LiveRegs.reset();
  359. // Determine the live-out physregs for this block.
  360. if (!BB->empty() && BB->back().isReturn()) {
  361. // In a return block, examine the function live-out regs.
  362. for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
  363. E = MRI.liveout_end(); I != E; ++I) {
  364. unsigned Reg = *I;
  365. LiveRegs.set(Reg);
  366. // Repeat, for all subregs.
  367. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  368. LiveRegs.set(*SubRegs);
  369. }
  370. }
  371. else {
  372. // In a non-return block, examine the live-in regs of all successors.
  373. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  374. SE = BB->succ_end(); SI != SE; ++SI) {
  375. for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
  376. E = (*SI)->livein_end(); I != E; ++I) {
  377. unsigned Reg = *I;
  378. LiveRegs.set(Reg);
  379. // Repeat, for all subregs.
  380. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  381. LiveRegs.set(*SubRegs);
  382. }
  383. }
  384. }
  385. }
  386. bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
  387. MachineOperand &MO) {
  388. // Setting kill flag...
  389. if (!MO.isKill()) {
  390. MO.setIsKill(true);
  391. return false;
  392. }
  393. // If MO itself is live, clear the kill flag...
  394. if (LiveRegs.test(MO.getReg())) {
  395. MO.setIsKill(false);
  396. return false;
  397. }
  398. // If any subreg of MO is live, then create an imp-def for that
  399. // subreg and keep MO marked as killed.
  400. MO.setIsKill(false);
  401. bool AllDead = true;
  402. const unsigned SuperReg = MO.getReg();
  403. MachineInstrBuilder MIB(MF, MI);
  404. for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
  405. if (LiveRegs.test(*SubRegs)) {
  406. MIB.addReg(*SubRegs, RegState::ImplicitDefine);
  407. AllDead = false;
  408. }
  409. }
  410. if(AllDead)
  411. MO.setIsKill(true);
  412. return false;
  413. }
  414. /// FixupKills - Fix the register kill flags, they may have been made
  415. /// incorrect by instruction reordering.
  416. ///
  417. void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
  418. DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
  419. BitVector killedRegs(TRI->getNumRegs());
  420. StartBlockForKills(MBB);
  421. // Examine block from end to start...
  422. unsigned Count = MBB->size();
  423. for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
  424. I != E; --Count) {
  425. MachineInstr *MI = --I;
  426. if (MI->isDebugValue())
  427. continue;
  428. // Update liveness. Registers that are defed but not used in this
  429. // instruction are now dead. Mark register and all subregs as they
  430. // are completely defined.
  431. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  432. MachineOperand &MO = MI->getOperand(i);
  433. if (MO.isRegMask())
  434. LiveRegs.clearBitsNotInMask(MO.getRegMask());
  435. if (!MO.isReg()) continue;
  436. unsigned Reg = MO.getReg();
  437. if (Reg == 0) continue;
  438. if (!MO.isDef()) continue;
  439. // Ignore two-addr defs.
  440. if (MI->isRegTiedToUseOperand(i)) continue;
  441. LiveRegs.reset(Reg);
  442. // Repeat for all subregs.
  443. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  444. LiveRegs.reset(*SubRegs);
  445. }
  446. // Examine all used registers and set/clear kill flag. When a
  447. // register is used multiple times we only set the kill flag on
  448. // the first use.
  449. killedRegs.reset();
  450. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  451. MachineOperand &MO = MI->getOperand(i);
  452. if (!MO.isReg() || !MO.isUse()) continue;
  453. unsigned Reg = MO.getReg();
  454. if ((Reg == 0) || MRI.isReserved(Reg)) continue;
  455. bool kill = false;
  456. if (!killedRegs.test(Reg)) {
  457. kill = true;
  458. // A register is not killed if any subregs are live...
  459. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
  460. if (LiveRegs.test(*SubRegs)) {
  461. kill = false;
  462. break;
  463. }
  464. }
  465. // If subreg is not live, then register is killed if it became
  466. // live in this instruction
  467. if (kill)
  468. kill = !LiveRegs.test(Reg);
  469. }
  470. if (MO.isKill() != kill) {
  471. DEBUG(dbgs() << "Fixing " << MO << " in ");
  472. // Warning: ToggleKillFlag may invalidate MO.
  473. ToggleKillFlag(MI, MO);
  474. DEBUG(MI->dump());
  475. }
  476. killedRegs.set(Reg);
  477. }
  478. // Mark any used register (that is not using undef) and subregs as
  479. // now live...
  480. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  481. MachineOperand &MO = MI->getOperand(i);
  482. if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
  483. unsigned Reg = MO.getReg();
  484. if ((Reg == 0) || MRI.isReserved(Reg)) continue;
  485. LiveRegs.set(Reg);
  486. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  487. LiveRegs.set(*SubRegs);
  488. }
  489. }
  490. }
  491. //===----------------------------------------------------------------------===//
  492. // Top-Down Scheduling
  493. //===----------------------------------------------------------------------===//
  494. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
  495. /// the PendingQueue if the count reaches zero.
  496. void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
  497. SUnit *SuccSU = SuccEdge->getSUnit();
  498. if (SuccEdge->isWeak()) {
  499. --SuccSU->WeakPredsLeft;
  500. return;
  501. }
  502. #ifndef NDEBUG
  503. if (SuccSU->NumPredsLeft == 0) {
  504. dbgs() << "*** Scheduling failed! ***\n";
  505. SuccSU->dump(this);
  506. dbgs() << " has been released too many times!\n";
  507. llvm_unreachable(0);
  508. }
  509. #endif
  510. --SuccSU->NumPredsLeft;
  511. // Standard scheduler algorithms will recompute the depth of the successor
  512. // here as such:
  513. // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
  514. //
  515. // However, we lazily compute node depth instead. Note that
  516. // ScheduleNodeTopDown has already updated the depth of this node which causes
  517. // all descendents to be marked dirty. Setting the successor depth explicitly
  518. // here would cause depth to be recomputed for all its ancestors. If the
  519. // successor is not yet ready (because of a transitively redundant edge) then
  520. // this causes depth computation to be quadratic in the size of the DAG.
  521. // If all the node's predecessors are scheduled, this node is ready
  522. // to be scheduled. Ignore the special ExitSU node.
  523. if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
  524. PendingQueue.push_back(SuccSU);
  525. }
  526. /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
  527. void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
  528. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  529. I != E; ++I) {
  530. ReleaseSucc(SU, &*I);
  531. }
  532. }
  533. /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
  534. /// count of its successors. If a successor pending count is zero, add it to
  535. /// the Available queue.
  536. void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
  537. DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
  538. DEBUG(SU->dump(this));
  539. Sequence.push_back(SU);
  540. assert(CurCycle >= SU->getDepth() &&
  541. "Node scheduled above its depth!");
  542. SU->setDepthToAtLeast(CurCycle);
  543. ReleaseSuccessors(SU);
  544. SU->isScheduled = true;
  545. AvailableQueue.scheduledNode(SU);
  546. }
  547. /// ListScheduleTopDown - The main loop of list scheduling for top-down
  548. /// schedulers.
  549. void SchedulePostRATDList::ListScheduleTopDown() {
  550. unsigned CurCycle = 0;
  551. // We're scheduling top-down but we're visiting the regions in
  552. // bottom-up order, so we don't know the hazards at the start of a
  553. // region. So assume no hazards (this should usually be ok as most
  554. // blocks are a single region).
  555. HazardRec->Reset();
  556. // Release any successors of the special Entry node.
  557. ReleaseSuccessors(&EntrySU);
  558. // Add all leaves to Available queue.
  559. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  560. // It is available if it has no predecessors.
  561. if (!SUnits[i].NumPredsLeft && !SUnits[i].isAvailable) {
  562. AvailableQueue.push(&SUnits[i]);
  563. SUnits[i].isAvailable = true;
  564. }
  565. }
  566. // In any cycle where we can't schedule any instructions, we must
  567. // stall or emit a noop, depending on the target.
  568. bool CycleHasInsts = false;
  569. // While Available queue is not empty, grab the node with the highest
  570. // priority. If it is not ready put it back. Schedule the node.
  571. std::vector<SUnit*> NotReady;
  572. Sequence.reserve(SUnits.size());
  573. while (!AvailableQueue.empty() || !PendingQueue.empty()) {
  574. // Check to see if any of the pending instructions are ready to issue. If
  575. // so, add them to the available queue.
  576. unsigned MinDepth = ~0u;
  577. for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
  578. if (PendingQueue[i]->getDepth() <= CurCycle) {
  579. AvailableQueue.push(PendingQueue[i]);
  580. PendingQueue[i]->isAvailable = true;
  581. PendingQueue[i] = PendingQueue.back();
  582. PendingQueue.pop_back();
  583. --i; --e;
  584. } else if (PendingQueue[i]->getDepth() < MinDepth)
  585. MinDepth = PendingQueue[i]->getDepth();
  586. }
  587. DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
  588. SUnit *FoundSUnit = 0;
  589. bool HasNoopHazards = false;
  590. while (!AvailableQueue.empty()) {
  591. SUnit *CurSUnit = AvailableQueue.pop();
  592. ScheduleHazardRecognizer::HazardType HT =
  593. HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
  594. if (HT == ScheduleHazardRecognizer::NoHazard) {
  595. FoundSUnit = CurSUnit;
  596. break;
  597. }
  598. // Remember if this is a noop hazard.
  599. HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
  600. NotReady.push_back(CurSUnit);
  601. }
  602. // Add the nodes that aren't ready back onto the available list.
  603. if (!NotReady.empty()) {
  604. AvailableQueue.push_all(NotReady);
  605. NotReady.clear();
  606. }
  607. // If we found a node to schedule...
  608. if (FoundSUnit) {
  609. // ... schedule the node...
  610. ScheduleNodeTopDown(FoundSUnit, CurCycle);
  611. HazardRec->EmitInstruction(FoundSUnit);
  612. CycleHasInsts = true;
  613. if (HazardRec->atIssueLimit()) {
  614. DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
  615. HazardRec->AdvanceCycle();
  616. ++CurCycle;
  617. CycleHasInsts = false;
  618. }
  619. } else {
  620. if (CycleHasInsts) {
  621. DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
  622. HazardRec->AdvanceCycle();
  623. } else if (!HasNoopHazards) {
  624. // Otherwise, we have a pipeline stall, but no other problem,
  625. // just advance the current cycle and try again.
  626. DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
  627. HazardRec->AdvanceCycle();
  628. ++NumStalls;
  629. } else {
  630. // Otherwise, we have no instructions to issue and we have instructions
  631. // that will fault if we don't do this right. This is the case for
  632. // processors without pipeline interlocks and other cases.
  633. DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
  634. HazardRec->EmitNoop();
  635. Sequence.push_back(0); // NULL here means noop
  636. ++NumNoops;
  637. }
  638. ++CurCycle;
  639. CycleHasInsts = false;
  640. }
  641. }
  642. #ifndef NDEBUG
  643. unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
  644. unsigned Noops = 0;
  645. for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
  646. if (!Sequence[i])
  647. ++Noops;
  648. assert(Sequence.size() - Noops == ScheduledNodes &&
  649. "The number of nodes scheduled doesn't match the expected number!");
  650. #endif // NDEBUG
  651. }
  652. // EmitSchedule - Emit the machine code in scheduled order.
  653. void SchedulePostRATDList::EmitSchedule() {
  654. RegionBegin = RegionEnd;
  655. // If first instruction was a DBG_VALUE then put it back.
  656. if (FirstDbgValue)
  657. BB->splice(RegionEnd, BB, FirstDbgValue);
  658. // Then re-insert them according to the given schedule.
  659. for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
  660. if (SUnit *SU = Sequence[i])
  661. BB->splice(RegionEnd, BB, SU->getInstr());
  662. else
  663. // Null SUnit* is a noop.
  664. TII->insertNoop(*BB, RegionEnd);
  665. // Update the Begin iterator, as the first instruction in the block
  666. // may have been scheduled later.
  667. if (i == 0)
  668. RegionBegin = prior(RegionEnd);
  669. }
  670. // Reinsert any remaining debug_values.
  671. for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
  672. DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
  673. std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
  674. MachineInstr *DbgValue = P.first;
  675. MachineBasicBlock::iterator OrigPrivMI = P.second;
  676. BB->splice(++OrigPrivMI, BB, DbgValue);
  677. }
  678. DbgValues.clear();
  679. FirstDbgValue = NULL;
  680. }