PostRASchedulerList.cpp 26 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. #define DEBUG_TYPE "post-RA-sched"
  21. #include "llvm/CodeGen/Passes.h"
  22. #include "llvm/CodeGen/ScheduleDAGInstrs.h"
  23. #include "llvm/CodeGen/LatencyPriorityQueue.h"
  24. #include "llvm/CodeGen/SchedulerRegistry.h"
  25. #include "llvm/CodeGen/MachineDominators.h"
  26. #include "llvm/CodeGen/MachineFunctionPass.h"
  27. #include "llvm/CodeGen/MachineLoopInfo.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/Target/TargetInstrInfo.h"
  30. #include "llvm/Target/TargetRegisterInfo.h"
  31. #include "llvm/Support/Compiler.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/ADT/Statistic.h"
  34. #include <map>
  35. using namespace llvm;
  36. STATISTIC(NumStalls, "Number of pipeline stalls");
  37. static cl::opt<bool>
  38. EnableAntiDepBreaking("break-anti-dependencies",
  39. cl::desc("Break post-RA scheduling anti-dependencies"),
  40. cl::init(true), cl::Hidden);
  41. namespace {
  42. class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
  43. public:
  44. static char ID;
  45. PostRAScheduler() : MachineFunctionPass(&ID) {}
  46. void getAnalysisUsage(AnalysisUsage &AU) const {
  47. AU.addRequired<MachineDominatorTree>();
  48. AU.addPreserved<MachineDominatorTree>();
  49. AU.addRequired<MachineLoopInfo>();
  50. AU.addPreserved<MachineLoopInfo>();
  51. MachineFunctionPass::getAnalysisUsage(AU);
  52. }
  53. const char *getPassName() const {
  54. return "Post RA top-down list latency scheduler";
  55. }
  56. bool runOnMachineFunction(MachineFunction &Fn);
  57. };
  58. char PostRAScheduler::ID = 0;
  59. class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
  60. /// AvailableQueue - The priority queue to use for the available SUnits.
  61. ///
  62. LatencyPriorityQueue AvailableQueue;
  63. /// PendingQueue - This contains all of the instructions whose operands have
  64. /// been issued, but their results are not ready yet (due to the latency of
  65. /// the operation). Once the operands becomes available, the instruction is
  66. /// added to the AvailableQueue.
  67. std::vector<SUnit*> PendingQueue;
  68. /// Topo - A topological ordering for SUnits.
  69. ScheduleDAGTopologicalSort Topo;
  70. public:
  71. SchedulePostRATDList(MachineBasicBlock *mbb, const TargetMachine &tm,
  72. const MachineLoopInfo &MLI,
  73. const MachineDominatorTree &MDT)
  74. : ScheduleDAGInstrs(mbb, tm, MLI, MDT), Topo(SUnits) {}
  75. void Schedule();
  76. private:
  77. void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
  78. void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
  79. void ListScheduleTopDown();
  80. bool BreakAntiDependencies();
  81. };
  82. }
  83. bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
  84. DOUT << "PostRAScheduler\n";
  85. const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
  86. const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
  87. // Loop over all of the basic blocks
  88. for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
  89. MBB != MBBe; ++MBB) {
  90. SchedulePostRATDList Scheduler(MBB, Fn.getTarget(), MLI, MDT);
  91. Scheduler.Run();
  92. Scheduler.EmitSchedule();
  93. }
  94. return true;
  95. }
  96. /// Schedule - Schedule the DAG using list scheduling.
  97. void SchedulePostRATDList::Schedule() {
  98. DOUT << "********** List Scheduling **********\n";
  99. // Build the scheduling graph.
  100. BuildSchedGraph();
  101. if (EnableAntiDepBreaking) {
  102. if (BreakAntiDependencies()) {
  103. // We made changes. Update the dependency graph.
  104. // Theoretically we could update the graph in place:
  105. // When a live range is changed to use a different register, remove
  106. // the def's anti-dependence *and* output-dependence edges due to
  107. // that register, and add new anti-dependence and output-dependence
  108. // edges based on the next live range of the register.
  109. SUnits.clear();
  110. BuildSchedGraph();
  111. }
  112. }
  113. AvailableQueue.initNodes(SUnits);
  114. ListScheduleTopDown();
  115. AvailableQueue.releaseState();
  116. }
  117. /// getInstrOperandRegClass - Return register class of the operand of an
  118. /// instruction of the specified TargetInstrDesc.
  119. static const TargetRegisterClass*
  120. getInstrOperandRegClass(const TargetRegisterInfo *TRI,
  121. const TargetInstrInfo *TII, const TargetInstrDesc &II,
  122. unsigned Op) {
  123. if (Op >= II.getNumOperands())
  124. return NULL;
  125. if (II.OpInfo[Op].isLookupPtrRegClass())
  126. return TII->getPointerRegClass();
  127. return TRI->getRegClass(II.OpInfo[Op].RegClass);
  128. }
  129. /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
  130. /// critical path.
  131. static SDep *CriticalPathStep(SUnit *SU) {
  132. SDep *Next = 0;
  133. unsigned NextDepth = 0;
  134. // Find the predecessor edge with the greatest depth.
  135. for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
  136. P != PE; ++P) {
  137. SUnit *PredSU = P->getSUnit();
  138. unsigned PredLatency = P->getLatency();
  139. unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
  140. // In the case of a latency tie, prefer an anti-dependency edge over
  141. // other types of edges.
  142. if (NextDepth < PredTotalLatency ||
  143. (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
  144. NextDepth = PredTotalLatency;
  145. Next = &*P;
  146. }
  147. }
  148. return Next;
  149. }
  150. /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
  151. /// of the ScheduleDAG and break them by renaming registers.
  152. ///
  153. bool SchedulePostRATDList::BreakAntiDependencies() {
  154. // The code below assumes that there is at least one instruction,
  155. // so just duck out immediately if the block is empty.
  156. if (BB->empty()) return false;
  157. // Find the node at the bottom of the critical path.
  158. SUnit *Max = 0;
  159. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  160. SUnit *SU = &SUnits[i];
  161. if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
  162. Max = SU;
  163. }
  164. DOUT << "Critical path has total latency "
  165. << (Max ? Max->getDepth() + Max->Latency : 0) << "\n";
  166. // We'll be ignoring anti-dependencies on non-allocatable registers, because
  167. // they may not be safe to break.
  168. const BitVector AllocatableSet = TRI->getAllocatableSet(*MF);
  169. // Track progress along the critical path through the SUnit graph as we walk
  170. // the instructions.
  171. SUnit *CriticalPathSU = Max;
  172. MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
  173. // For live regs that are only used in one register class in a live range,
  174. // the register class. If the register is not live, the corresponding value
  175. // is null. If the register is live but used in multiple register classes,
  176. // the corresponding value is -1 casted to a pointer.
  177. const TargetRegisterClass *
  178. Classes[TargetRegisterInfo::FirstVirtualRegister] = {};
  179. // Map registers to all their references within a live range.
  180. std::multimap<unsigned, MachineOperand *> RegRefs;
  181. // The index of the most recent kill (proceding bottom-up), or ~0u if
  182. // the register is not live.
  183. unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
  184. std::fill(KillIndices, array_endof(KillIndices), ~0u);
  185. // The index of the most recent complete def (proceding bottom up), or ~0u if
  186. // the register is live.
  187. unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
  188. std::fill(DefIndices, array_endof(DefIndices), BB->size());
  189. // Determine the live-out physregs for this block.
  190. if (BB->back().getDesc().isReturn())
  191. // In a return block, examine the function live-out regs.
  192. for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
  193. E = MRI.liveout_end(); I != E; ++I) {
  194. unsigned Reg = *I;
  195. Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
  196. KillIndices[Reg] = BB->size();
  197. DefIndices[Reg] = ~0u;
  198. // Repeat, for all aliases.
  199. for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
  200. unsigned AliasReg = *Alias;
  201. Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
  202. KillIndices[AliasReg] = BB->size();
  203. DefIndices[AliasReg] = ~0u;
  204. }
  205. }
  206. else
  207. // In a non-return block, examine the live-in regs of all successors.
  208. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  209. SE = BB->succ_end(); SI != SE; ++SI)
  210. for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
  211. E = (*SI)->livein_end(); I != E; ++I) {
  212. unsigned Reg = *I;
  213. Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
  214. KillIndices[Reg] = BB->size();
  215. DefIndices[Reg] = ~0u;
  216. // Repeat, for all aliases.
  217. for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
  218. unsigned AliasReg = *Alias;
  219. Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
  220. KillIndices[AliasReg] = BB->size();
  221. DefIndices[AliasReg] = ~0u;
  222. }
  223. }
  224. // Consider callee-saved registers as live-out, since we're running after
  225. // prologue/epilogue insertion so there's no way to add additional
  226. // saved registers.
  227. //
  228. // TODO: If the callee saves and restores these, then we can potentially
  229. // use them between the save and the restore. To do that, we could scan
  230. // the exit blocks to see which of these registers are defined.
  231. // Alternatively, callee-saved registers that aren't saved and restored
  232. // could be marked live-in in every block.
  233. for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
  234. unsigned Reg = *I;
  235. Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
  236. KillIndices[Reg] = BB->size();
  237. DefIndices[Reg] = ~0u;
  238. // Repeat, for all aliases.
  239. for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
  240. unsigned AliasReg = *Alias;
  241. Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
  242. KillIndices[AliasReg] = BB->size();
  243. DefIndices[AliasReg] = ~0u;
  244. }
  245. }
  246. // Consider this pattern:
  247. // A = ...
  248. // ... = A
  249. // A = ...
  250. // ... = A
  251. // A = ...
  252. // ... = A
  253. // A = ...
  254. // ... = A
  255. // There are three anti-dependencies here, and without special care,
  256. // we'd break all of them using the same register:
  257. // A = ...
  258. // ... = A
  259. // B = ...
  260. // ... = B
  261. // B = ...
  262. // ... = B
  263. // B = ...
  264. // ... = B
  265. // because at each anti-dependence, B is the first register that
  266. // isn't A which is free. This re-introduces anti-dependencies
  267. // at all but one of the original anti-dependencies that we were
  268. // trying to break. To avoid this, keep track of the most recent
  269. // register that each register was replaced with, avoid avoid
  270. // using it to repair an anti-dependence on the same register.
  271. // This lets us produce this:
  272. // A = ...
  273. // ... = A
  274. // B = ...
  275. // ... = B
  276. // C = ...
  277. // ... = C
  278. // B = ...
  279. // ... = B
  280. // This still has an anti-dependence on B, but at least it isn't on the
  281. // original critical path.
  282. //
  283. // TODO: If we tracked more than one register here, we could potentially
  284. // fix that remaining critical edge too. This is a little more involved,
  285. // because unlike the most recent register, less recent registers should
  286. // still be considered, though only if no other registers are available.
  287. unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
  288. // Attempt to break anti-dependence edges on the critical path. Walk the
  289. // instructions from the bottom up, tracking information about liveness
  290. // as we go to help determine which registers are available.
  291. bool Changed = false;
  292. unsigned Count = BB->size() - 1;
  293. for (MachineBasicBlock::reverse_iterator I = BB->rbegin(), E = BB->rend();
  294. I != E; ++I, --Count) {
  295. MachineInstr *MI = &*I;
  296. // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
  297. // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
  298. // is left behind appearing to clobber the super-register, while the
  299. // subregister needs to remain live. So we just ignore them.
  300. if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
  301. continue;
  302. // Check if this instruction has a dependence on the critical path that
  303. // is an anti-dependence that we may be able to break. If it is, set
  304. // AntiDepReg to the non-zero register associated with the anti-dependence.
  305. //
  306. // We limit our attention to the critical path as a heuristic to avoid
  307. // breaking anti-dependence edges that aren't going to significantly
  308. // impact the overall schedule. There are a limited number of registers
  309. // and we want to save them for the important edges.
  310. //
  311. // TODO: Instructions with multiple defs could have multiple
  312. // anti-dependencies. The current code here only knows how to break one
  313. // edge per instruction. Note that we'd have to be able to break all of
  314. // the anti-dependencies in an instruction in order to be effective.
  315. unsigned AntiDepReg = 0;
  316. if (MI == CriticalPathMI) {
  317. if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
  318. SUnit *NextSU = Edge->getSUnit();
  319. // Only consider anti-dependence edges.
  320. if (Edge->getKind() == SDep::Anti) {
  321. AntiDepReg = Edge->getReg();
  322. assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
  323. // Don't break anti-dependencies on non-allocatable registers.
  324. if (AllocatableSet.test(AntiDepReg)) {
  325. // If the SUnit has other dependencies on the SUnit that it
  326. // anti-depends on, don't bother breaking the anti-dependency
  327. // since those edges would prevent such units from being
  328. // scheduled past each other regardless.
  329. //
  330. // Also, if there are dependencies on other SUnits with the
  331. // same register as the anti-dependency, don't attempt to
  332. // break it.
  333. for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
  334. PE = CriticalPathSU->Preds.end(); P != PE; ++P)
  335. if (P->getSUnit() == NextSU ?
  336. (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
  337. (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
  338. AntiDepReg = 0;
  339. break;
  340. }
  341. }
  342. }
  343. CriticalPathSU = NextSU;
  344. CriticalPathMI = CriticalPathSU->getInstr();
  345. } else {
  346. // We've reached the end of the critical path.
  347. CriticalPathSU = 0;
  348. CriticalPathMI = 0;
  349. }
  350. }
  351. // Scan the register operands for this instruction and update
  352. // Classes and RegRefs.
  353. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  354. MachineOperand &MO = MI->getOperand(i);
  355. if (!MO.isReg()) continue;
  356. unsigned Reg = MO.getReg();
  357. if (Reg == 0) continue;
  358. const TargetRegisterClass *NewRC =
  359. getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
  360. // If this instruction has a use of AntiDepReg, breaking it
  361. // is invalid.
  362. if (MO.isUse() && AntiDepReg == Reg)
  363. AntiDepReg = 0;
  364. // For now, only allow the register to be changed if its register
  365. // class is consistent across all uses.
  366. if (!Classes[Reg] && NewRC)
  367. Classes[Reg] = NewRC;
  368. else if (!NewRC || Classes[Reg] != NewRC)
  369. Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
  370. // Now check for aliases.
  371. for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
  372. // If an alias of the reg is used during the live range, give up.
  373. // Note that this allows us to skip checking if AntiDepReg
  374. // overlaps with any of the aliases, among other things.
  375. unsigned AliasReg = *Alias;
  376. if (Classes[AliasReg]) {
  377. Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
  378. Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
  379. }
  380. }
  381. // If we're still willing to consider this register, note the reference.
  382. if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
  383. RegRefs.insert(std::make_pair(Reg, &MO));
  384. }
  385. // Determine AntiDepReg's register class, if it is live and is
  386. // consistently used within a single class.
  387. const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
  388. assert((AntiDepReg == 0 || RC != NULL) &&
  389. "Register should be live if it's causing an anti-dependence!");
  390. if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
  391. AntiDepReg = 0;
  392. // Look for a suitable register to use to break the anti-depenence.
  393. //
  394. // TODO: Instead of picking the first free register, consider which might
  395. // be the best.
  396. if (AntiDepReg != 0) {
  397. for (TargetRegisterClass::iterator R = RC->allocation_order_begin(*MF),
  398. RE = RC->allocation_order_end(*MF); R != RE; ++R) {
  399. unsigned NewReg = *R;
  400. // Don't replace a register with itself.
  401. if (NewReg == AntiDepReg) continue;
  402. // Don't replace a register with one that was recently used to repair
  403. // an anti-dependence with this AntiDepReg, because that would
  404. // re-introduce that anti-dependence.
  405. if (NewReg == LastNewReg[AntiDepReg]) continue;
  406. // If NewReg is dead and NewReg's most recent def is not before
  407. // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
  408. assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
  409. "Kill and Def maps aren't consistent for AntiDepReg!");
  410. assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
  411. "Kill and Def maps aren't consistent for NewReg!");
  412. if (KillIndices[NewReg] == ~0u &&
  413. Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
  414. KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
  415. DOUT << "Breaking anti-dependence edge on "
  416. << TRI->getName(AntiDepReg)
  417. << " with " << RegRefs.count(AntiDepReg) << " references"
  418. << " using " << TRI->getName(NewReg) << "!\n";
  419. // Update the references to the old register to refer to the new
  420. // register.
  421. std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
  422. std::multimap<unsigned, MachineOperand *>::iterator>
  423. Range = RegRefs.equal_range(AntiDepReg);
  424. for (std::multimap<unsigned, MachineOperand *>::iterator
  425. Q = Range.first, QE = Range.second; Q != QE; ++Q)
  426. Q->second->setReg(NewReg);
  427. // We just went back in time and modified history; the
  428. // liveness information for the anti-depenence reg is now
  429. // inconsistent. Set the state as if it were dead.
  430. Classes[NewReg] = Classes[AntiDepReg];
  431. DefIndices[NewReg] = DefIndices[AntiDepReg];
  432. KillIndices[NewReg] = KillIndices[AntiDepReg];
  433. Classes[AntiDepReg] = 0;
  434. DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
  435. KillIndices[AntiDepReg] = ~0u;
  436. RegRefs.erase(AntiDepReg);
  437. Changed = true;
  438. LastNewReg[AntiDepReg] = NewReg;
  439. break;
  440. }
  441. }
  442. }
  443. // Update liveness.
  444. // Proceding upwards, registers that are defed but not used in this
  445. // instruction are now dead.
  446. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  447. MachineOperand &MO = MI->getOperand(i);
  448. if (!MO.isReg()) continue;
  449. unsigned Reg = MO.getReg();
  450. if (Reg == 0) continue;
  451. if (!MO.isDef()) continue;
  452. // Ignore two-addr defs.
  453. if (MI->isRegReDefinedByTwoAddr(i)) continue;
  454. DefIndices[Reg] = Count;
  455. KillIndices[Reg] = ~0u;
  456. Classes[Reg] = 0;
  457. RegRefs.erase(Reg);
  458. // Repeat, for all subregs.
  459. for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
  460. *Subreg; ++Subreg) {
  461. unsigned SubregReg = *Subreg;
  462. DefIndices[SubregReg] = Count;
  463. KillIndices[SubregReg] = ~0u;
  464. Classes[SubregReg] = 0;
  465. RegRefs.erase(SubregReg);
  466. }
  467. // Conservatively mark super-registers as unusable.
  468. for (const unsigned *Super = TRI->getSuperRegisters(Reg);
  469. *Super; ++Super) {
  470. unsigned SuperReg = *Super;
  471. Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
  472. }
  473. }
  474. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  475. MachineOperand &MO = MI->getOperand(i);
  476. if (!MO.isReg()) continue;
  477. unsigned Reg = MO.getReg();
  478. if (Reg == 0) continue;
  479. if (!MO.isUse()) continue;
  480. const TargetRegisterClass *NewRC =
  481. getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
  482. // For now, only allow the register to be changed if its register
  483. // class is consistent across all uses.
  484. if (!Classes[Reg] && NewRC)
  485. Classes[Reg] = NewRC;
  486. else if (!NewRC || Classes[Reg] != NewRC)
  487. Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
  488. RegRefs.insert(std::make_pair(Reg, &MO));
  489. // It wasn't previously live but now it is, this is a kill.
  490. if (KillIndices[Reg] == ~0u) {
  491. KillIndices[Reg] = Count;
  492. DefIndices[Reg] = ~0u;
  493. }
  494. // Repeat, for all aliases.
  495. for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
  496. unsigned AliasReg = *Alias;
  497. if (KillIndices[AliasReg] == ~0u) {
  498. KillIndices[AliasReg] = Count;
  499. DefIndices[AliasReg] = ~0u;
  500. }
  501. }
  502. }
  503. }
  504. assert(Count == ~0u && "Count mismatch!");
  505. return Changed;
  506. }
  507. //===----------------------------------------------------------------------===//
  508. // Top-Down Scheduling
  509. //===----------------------------------------------------------------------===//
  510. /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
  511. /// the PendingQueue if the count reaches zero. Also update its cycle bound.
  512. void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
  513. SUnit *SuccSU = SuccEdge->getSUnit();
  514. --SuccSU->NumPredsLeft;
  515. #ifndef NDEBUG
  516. if (SuccSU->NumPredsLeft < 0) {
  517. cerr << "*** Scheduling failed! ***\n";
  518. SuccSU->dump(this);
  519. cerr << " has been released too many times!\n";
  520. assert(0);
  521. }
  522. #endif
  523. // Compute how many cycles it will be before this actually becomes
  524. // available. This is the max of the start time of all predecessors plus
  525. // their latencies.
  526. SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
  527. if (SuccSU->NumPredsLeft == 0) {
  528. PendingQueue.push_back(SuccSU);
  529. }
  530. }
  531. /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
  532. /// count of its successors. If a successor pending count is zero, add it to
  533. /// the Available queue.
  534. void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
  535. DOUT << "*** Scheduling [" << CurCycle << "]: ";
  536. DEBUG(SU->dump(this));
  537. Sequence.push_back(SU);
  538. assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
  539. SU->setDepthToAtLeast(CurCycle);
  540. // Top down: release successors.
  541. for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
  542. I != E; ++I)
  543. ReleaseSucc(SU, &*I);
  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. // All leaves to Available queue.
  552. for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
  553. // It is available if it has no predecessors.
  554. if (SUnits[i].Preds.empty()) {
  555. AvailableQueue.push(&SUnits[i]);
  556. SUnits[i].isAvailable = true;
  557. }
  558. }
  559. // While Available queue is not empty, grab the node with the highest
  560. // priority. If it is not ready put it back. Schedule the node.
  561. Sequence.reserve(SUnits.size());
  562. while (!AvailableQueue.empty() || !PendingQueue.empty()) {
  563. // Check to see if any of the pending instructions are ready to issue. If
  564. // so, add them to the available queue.
  565. unsigned MinDepth = ~0u;
  566. for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
  567. if (PendingQueue[i]->getDepth() <= CurCycle) {
  568. AvailableQueue.push(PendingQueue[i]);
  569. PendingQueue[i]->isAvailable = true;
  570. PendingQueue[i] = PendingQueue.back();
  571. PendingQueue.pop_back();
  572. --i; --e;
  573. } else if (PendingQueue[i]->getDepth() < MinDepth)
  574. MinDepth = PendingQueue[i]->getDepth();
  575. }
  576. // If there are no instructions available, don't try to issue anything.
  577. if (AvailableQueue.empty()) {
  578. CurCycle = MinDepth != ~0u ? MinDepth : CurCycle + 1;
  579. continue;
  580. }
  581. SUnit *FoundSUnit = AvailableQueue.pop();
  582. // If we found a node to schedule, do it now.
  583. if (FoundSUnit) {
  584. ScheduleNodeTopDown(FoundSUnit, CurCycle);
  585. // If this is a pseudo-op node, we don't want to increment the current
  586. // cycle.
  587. if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
  588. ++CurCycle;
  589. } else {
  590. // Otherwise, we have a pipeline stall, but no other problem, just advance
  591. // the current cycle and try again.
  592. DOUT << "*** Advancing cycle, no work to do\n";
  593. ++NumStalls;
  594. ++CurCycle;
  595. }
  596. }
  597. #ifndef NDEBUG
  598. VerifySchedule(/*isBottomUp=*/false);
  599. #endif
  600. }
  601. //===----------------------------------------------------------------------===//
  602. // Public Constructor Functions
  603. //===----------------------------------------------------------------------===//
  604. FunctionPass *llvm::createPostRAScheduler() {
  605. return new PostRAScheduler();
  606. }