blob: 1606532e47fe8145feadf876f093cbe3ec654a8a [file] [log] [blame]
Dale Johannesen72f15962007-07-13 17:31:29 +00001//===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00007//
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
21#define DEBUG_TYPE "post-RA-sched"
David Goodwind94a4e52009-08-10 15:55:25 +000022#include "ExactHazardRecognizer.h"
23#include "SimpleHazardRecognizer.h"
Dan Gohman6dc75fe2009-02-06 17:12:10 +000024#include "ScheduleDAGInstrs.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000025#include "llvm/CodeGen/Passes.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000026#include "llvm/CodeGen/LatencyPriorityQueue.h"
27#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman3f237442008-12-16 03:25:46 +000028#include "llvm/CodeGen/MachineDominators.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000029#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman3f237442008-12-16 03:25:46 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman21d90032008-11-25 00:52:40 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman2836c282009-01-16 01:33:36 +000032#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohmanbed353d2009-02-10 23:29:38 +000033#include "llvm/Target/TargetLowering.h"
Dan Gohman79ce2762009-01-15 19:20:50 +000034#include "llvm/Target/TargetMachine.h"
Dan Gohman21d90032008-11-25 00:52:40 +000035#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner459525d2008-01-14 19:00:06 +000037#include "llvm/Support/Compiler.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000038#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000039#include "llvm/Support/ErrorHandling.h"
David Goodwin3a5f0d42009-08-11 01:44:26 +000040#include "llvm/Support/raw_ostream.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000041#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000042#include <map>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000043using namespace llvm;
44
Dan Gohman2836c282009-01-16 01:33:36 +000045STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000046STATISTIC(NumStalls, "Number of pipeline stalls");
47
Dan Gohman21d90032008-11-25 00:52:40 +000048static cl::opt<bool>
49EnableAntiDepBreaking("break-anti-dependencies",
Dan Gohman00dc84a2008-12-16 19:27:52 +000050 cl::desc("Break post-RA scheduling anti-dependencies"),
51 cl::init(true), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000052
Dan Gohman2836c282009-01-16 01:33:36 +000053static cl::opt<bool>
54EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwind94a4e52009-08-10 15:55:25 +000055 cl::desc("Enable exact hazard avoidance"),
56 cl::init(false), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000057
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000058namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000059 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000060 public:
61 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000062 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000063
Dan Gohman3f237442008-12-16 03:25:46 +000064 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000065 AU.setPreservesCFG();
Dan Gohman3f237442008-12-16 03:25:46 +000066 AU.addRequired<MachineDominatorTree>();
67 AU.addPreserved<MachineDominatorTree>();
68 AU.addRequired<MachineLoopInfo>();
69 AU.addPreserved<MachineLoopInfo>();
70 MachineFunctionPass::getAnalysisUsage(AU);
71 }
72
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000073 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000074 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000075 }
76
77 bool runOnMachineFunction(MachineFunction &Fn);
78 };
Dan Gohman343f0c02008-11-19 23:18:57 +000079 char PostRAScheduler::ID = 0;
80
81 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000082 /// AvailableQueue - The priority queue to use for the available SUnits.
83 ///
84 LatencyPriorityQueue AvailableQueue;
85
86 /// PendingQueue - This contains all of the instructions whose operands have
87 /// been issued, but their results are not ready yet (due to the latency of
88 /// the operation). Once the operands becomes available, the instruction is
89 /// added to the AvailableQueue.
90 std::vector<SUnit*> PendingQueue;
91
Dan Gohman21d90032008-11-25 00:52:40 +000092 /// Topo - A topological ordering for SUnits.
93 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +000094
Dan Gohman79ce2762009-01-15 19:20:50 +000095 /// AllocatableSet - The set of allocatable registers.
96 /// We'll be ignoring anti-dependencies on non-allocatable registers,
97 /// because they may not be safe to break.
98 const BitVector AllocatableSet;
99
Dan Gohman2836c282009-01-16 01:33:36 +0000100 /// HazardRec - The hazard recognizer to use.
101 ScheduleHazardRecognizer *HazardRec;
102
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000103 /// Classes - For live regs that are only used in one register class in a
104 /// live range, the register class. If the register is not live, the
105 /// corresponding value is null. If the register is live but used in
106 /// multiple register classes, the corresponding value is -1 casted to a
107 /// pointer.
108 const TargetRegisterClass *
109 Classes[TargetRegisterInfo::FirstVirtualRegister];
110
111 /// RegRegs - Map registers to all their references within a live range.
112 std::multimap<unsigned, MachineOperand *> RegRefs;
113
114 /// The index of the most recent kill (proceding bottom-up), or ~0u if
115 /// the register is not live.
116 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
117
118 /// The index of the most recent complete def (proceding bottom up), or ~0u
119 /// if the register is live.
120 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
121
Dan Gohman21d90032008-11-25 00:52:40 +0000122 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000123 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000124 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000125 const MachineDominatorTree &MDT,
126 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000127 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000128 AllocatableSet(TRI->getAllocatableSet(MF)),
129 HazardRec(HR) {}
130
131 ~SchedulePostRATDList() {
132 delete HazardRec;
133 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000134
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000135 /// StartBlock - Initialize register live-range state for scheduling in
136 /// this block.
137 ///
138 void StartBlock(MachineBasicBlock *BB);
139
140 /// Schedule - Schedule the instruction range using list scheduling.
141 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000142 void Schedule();
143
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000144 /// Observe - Update liveness information to account for the current
145 /// instruction, which will not be scheduled.
146 ///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000147 void Observe(MachineInstr *MI, unsigned Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000148
149 /// FinishBlock - Clean up register live-range state.
150 ///
151 void FinishBlock();
152
Dan Gohman343f0c02008-11-19 23:18:57 +0000153 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000154 void PrescanInstruction(MachineInstr *MI);
155 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000156 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000157 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000158 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
159 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000160 bool BreakAntiDependencies();
Dan Gohman343f0c02008-11-19 23:18:57 +0000161 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000162}
163
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000164/// isSchedulingBoundary - Test if the given instruction should be
165/// considered a scheduling boundary. This primarily includes labels
166/// and terminators.
167///
168static bool isSchedulingBoundary(const MachineInstr *MI,
169 const MachineFunction &MF) {
170 // Terminators and labels can't be scheduled around.
171 if (MI->getDesc().isTerminator() || MI->isLabel())
172 return true;
173
Dan Gohmanbed353d2009-02-10 23:29:38 +0000174 // Don't attempt to schedule around any instruction that modifies
175 // a stack-oriented pointer, as it's unlikely to be profitable. This
176 // saves compile time, because it doesn't require every single
177 // stack slot reference to depend on the instruction that does the
178 // modification.
179 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
180 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
181 return true;
182
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000183 return false;
184}
185
Dan Gohman343f0c02008-11-19 23:18:57 +0000186bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000187 DEBUG(errs() << "PostRAScheduler\n");
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000188
Dan Gohman3f237442008-12-16 03:25:46 +0000189 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
190 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000191 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000192 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000193 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
194 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000195
Dan Gohman2836c282009-01-16 01:33:36 +0000196 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000197
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000198 // Loop over all of the basic blocks
199 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000200 MBB != MBBe; ++MBB) {
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000201 // Initialize register live-range state for scheduling in this block.
202 Scheduler.StartBlock(MBB);
203
Dan Gohmanf7119392009-01-16 22:10:20 +0000204 // Schedule each sequence of instructions not interrupted by a label
205 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000206 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000207 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000208 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
209 MachineInstr *MI = prior(I);
210 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000211 Scheduler.Run(MBB, I, Current, CurrentCount);
212 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000213 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000214 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000215 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000216 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000217 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000218 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000219 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000220 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000221 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000222 "Instruction count mismatch!");
223 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Dan Gohman343f0c02008-11-19 23:18:57 +0000224 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000225
226 // Clean up register live-range state.
227 Scheduler.FinishBlock();
Dan Gohman343f0c02008-11-19 23:18:57 +0000228 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000229
230 return true;
231}
232
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000233/// StartBlock - Initialize register live-range state for scheduling in
234/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000235///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000236void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
237 // Call the superclass.
238 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000239
David Goodwind94a4e52009-08-10 15:55:25 +0000240 // Reset the hazard recognizer.
241 HazardRec->Reset();
242
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000243 // Clear out the register class data.
244 std::fill(Classes, array_endof(Classes),
245 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000246
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000247 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000248 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000249 std::fill(DefIndices, array_endof(DefIndices), BB->size());
250
251 // Determine the live-out physregs for this block.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000252 if (!BB->empty() && BB->back().getDesc().isReturn())
Dan Gohman21d90032008-11-25 00:52:40 +0000253 // In a return block, examine the function live-out regs.
254 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
255 E = MRI.liveout_end(); I != E; ++I) {
256 unsigned Reg = *I;
257 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
258 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000259 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000260 // Repeat, for all aliases.
261 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
262 unsigned AliasReg = *Alias;
263 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
264 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000265 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000266 }
267 }
268 else
269 // In a non-return block, examine the live-in regs of all successors.
270 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
Dan Gohman47ac0f02009-02-11 04:27:20 +0000271 SE = BB->succ_end(); SI != SE; ++SI)
Dan Gohman21d90032008-11-25 00:52:40 +0000272 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
273 E = (*SI)->livein_end(); I != E; ++I) {
274 unsigned Reg = *I;
275 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
276 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000277 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000278 // Repeat, for all aliases.
279 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
280 unsigned AliasReg = *Alias;
281 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
282 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000283 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000284 }
285 }
286
287 // Consider callee-saved registers as live-out, since we're running after
288 // prologue/epilogue insertion so there's no way to add additional
289 // saved registers.
290 //
291 // TODO: If the callee saves and restores these, then we can potentially
292 // use them between the save and the restore. To do that, we could scan
293 // the exit blocks to see which of these registers are defined.
Dan Gohman00dc84a2008-12-16 19:27:52 +0000294 // Alternatively, callee-saved registers that aren't saved and restored
Dan Gohmanebb0a312008-12-03 19:30:13 +0000295 // could be marked live-in in every block.
Dan Gohman21d90032008-11-25 00:52:40 +0000296 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
297 unsigned Reg = *I;
298 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
299 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000300 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000301 // Repeat, for all aliases.
302 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
303 unsigned AliasReg = *Alias;
304 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
305 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000306 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000307 }
308 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000309}
310
311/// Schedule - Schedule the instruction range using list scheduling.
312///
313void SchedulePostRATDList::Schedule() {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000314 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000315
316 // Build the scheduling graph.
317 BuildSchedGraph();
318
319 if (EnableAntiDepBreaking) {
320 if (BreakAntiDependencies()) {
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 SUnits.clear();
328 EntrySU = SUnit();
329 ExitSU = SUnit();
330 BuildSchedGraph();
331 }
332 }
333
David Goodwind94a4e52009-08-10 15:55:25 +0000334 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
335 SUnits[su].dumpAll(this));
336
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000337 AvailableQueue.initNodes(SUnits);
338
339 ListScheduleTopDown();
340
341 AvailableQueue.releaseState();
342}
343
344/// Observe - Update liveness information to account for the current
345/// instruction, which will not be scheduled.
346///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000347void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000348 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
349
350 // Any register which was defined within the previous scheduling region
351 // may have been rescheduled and its lifetime may overlap with registers
352 // in ways not reflected in our current liveness state. For each such
353 // register, adjust the liveness state to be conservatively correct.
354 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
355 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
356 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
357 // Mark this register to be non-renamable.
358 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
359 // Move the def index to the end of the previous region, to reflect
360 // that the def could theoretically have been scheduled at the end.
361 DefIndices[Reg] = InsertPosIndex;
362 }
363
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000364 PrescanInstruction(MI);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000365 ScanInstruction(MI, Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000366}
367
368/// FinishBlock - Clean up register live-range state.
369///
370void SchedulePostRATDList::FinishBlock() {
371 RegRefs.clear();
372
373 // Call the superclass.
374 ScheduleDAGInstrs::FinishBlock();
375}
376
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000377/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
378/// critical path.
379static SDep *CriticalPathStep(SUnit *SU) {
380 SDep *Next = 0;
381 unsigned NextDepth = 0;
382 // Find the predecessor edge with the greatest depth.
383 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
384 P != PE; ++P) {
385 SUnit *PredSU = P->getSUnit();
386 unsigned PredLatency = P->getLatency();
387 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
388 // In the case of a latency tie, prefer an anti-dependency edge over
389 // other types of edges.
390 if (NextDepth < PredTotalLatency ||
391 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
392 NextDepth = PredTotalLatency;
393 Next = &*P;
394 }
395 }
396 return Next;
397}
398
399void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
400 // Scan the register operands for this instruction and update
401 // Classes and RegRefs.
402 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
403 MachineOperand &MO = MI->getOperand(i);
404 if (!MO.isReg()) continue;
405 unsigned Reg = MO.getReg();
406 if (Reg == 0) continue;
Chris Lattner2a386882009-07-29 21:36:49 +0000407 const TargetRegisterClass *NewRC = 0;
408
409 if (i < MI->getDesc().getNumOperands())
410 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000411
412 // For now, only allow the register to be changed if its register
413 // class is consistent across all uses.
414 if (!Classes[Reg] && NewRC)
415 Classes[Reg] = NewRC;
416 else if (!NewRC || Classes[Reg] != NewRC)
417 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
418
419 // Now check for aliases.
420 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
421 // If an alias of the reg is used during the live range, give up.
422 // Note that this allows us to skip checking if AntiDepReg
423 // overlaps with any of the aliases, among other things.
424 unsigned AliasReg = *Alias;
425 if (Classes[AliasReg]) {
426 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
427 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
428 }
429 }
430
431 // If we're still willing to consider this register, note the reference.
432 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
433 RegRefs.insert(std::make_pair(Reg, &MO));
434 }
435}
436
437void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
438 unsigned Count) {
439 // Update liveness.
440 // Proceding upwards, registers that are defed but not used in this
441 // instruction are now dead.
442 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
443 MachineOperand &MO = MI->getOperand(i);
444 if (!MO.isReg()) continue;
445 unsigned Reg = MO.getReg();
446 if (Reg == 0) continue;
447 if (!MO.isDef()) continue;
448 // Ignore two-addr defs.
Bob Wilsond9df5012009-04-09 17:16:43 +0000449 if (MI->isRegTiedToUseOperand(i)) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000450
451 DefIndices[Reg] = Count;
452 KillIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000453 assert(((KillIndices[Reg] == ~0u) !=
454 (DefIndices[Reg] == ~0u)) &&
455 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000456 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
Chris Lattner2a386882009-07-29 21:36:49 +0000481 const TargetRegisterClass *NewRC = 0;
482 if (i < MI->getDesc().getNumOperands())
483 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000484
485 // For now, only allow the register to be changed if its register
486 // class is consistent across all uses.
487 if (!Classes[Reg] && NewRC)
488 Classes[Reg] = NewRC;
489 else if (!NewRC || Classes[Reg] != NewRC)
490 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
491
492 RegRefs.insert(std::make_pair(Reg, &MO));
493
494 // It wasn't previously live but now it is, this is a kill.
495 if (KillIndices[Reg] == ~0u) {
496 KillIndices[Reg] = Count;
497 DefIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000498 assert(((KillIndices[Reg] == ~0u) !=
499 (DefIndices[Reg] == ~0u)) &&
500 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000501 }
502 // Repeat, for all aliases.
503 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
504 unsigned AliasReg = *Alias;
505 if (KillIndices[AliasReg] == ~0u) {
506 KillIndices[AliasReg] = Count;
507 DefIndices[AliasReg] = ~0u;
508 }
509 }
510 }
511}
512
513/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
514/// of the ScheduleDAG and break them by renaming registers.
515///
516bool SchedulePostRATDList::BreakAntiDependencies() {
517 // The code below assumes that there is at least one instruction,
518 // so just duck out immediately if the block is empty.
519 if (SUnits.empty()) return false;
520
521 // Find the node at the bottom of the critical path.
522 SUnit *Max = 0;
523 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
524 SUnit *SU = &SUnits[i];
525 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
526 Max = SU;
527 }
528
David Goodwin3a5f0d42009-08-11 01:44:26 +0000529 DEBUG(errs() << "Critical path has total latency "
530 << (Max->getDepth() + Max->Latency) << "\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000531
532 // Track progress along the critical path through the SUnit graph as we walk
533 // the instructions.
534 SUnit *CriticalPathSU = Max;
535 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000536
537 // Consider this pattern:
538 // A = ...
539 // ... = A
540 // A = ...
541 // ... = A
542 // A = ...
543 // ... = A
544 // A = ...
545 // ... = A
546 // There are three anti-dependencies here, and without special care,
547 // we'd break all of them using the same register:
548 // A = ...
549 // ... = A
550 // B = ...
551 // ... = B
552 // B = ...
553 // ... = B
554 // B = ...
555 // ... = B
556 // because at each anti-dependence, B is the first register that
557 // isn't A which is free. This re-introduces anti-dependencies
558 // at all but one of the original anti-dependencies that we were
559 // trying to break. To avoid this, keep track of the most recent
David Goodwinc93d8372009-08-11 17:35:23 +0000560 // register that each register was replaced with, avoid
Dan Gohman21d90032008-11-25 00:52:40 +0000561 // using it to repair an anti-dependence on the same register.
562 // This lets us produce this:
563 // A = ...
564 // ... = A
565 // B = ...
566 // ... = B
567 // C = ...
568 // ... = C
569 // B = ...
570 // ... = B
571 // This still has an anti-dependence on B, but at least it isn't on the
572 // original critical path.
573 //
574 // TODO: If we tracked more than one register here, we could potentially
575 // fix that remaining critical edge too. This is a little more involved,
576 // because unlike the most recent register, less recent registers should
577 // still be considered, though only if no other registers are available.
578 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
579
Dan Gohman21d90032008-11-25 00:52:40 +0000580 // Attempt to break anti-dependence edges on the critical path. Walk the
581 // instructions from the bottom up, tracking information about liveness
582 // as we go to help determine which registers are available.
583 bool Changed = false;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000584 unsigned Count = InsertPosIndex - 1;
585 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000586 I != E; --Count) {
587 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000588
Dan Gohman490b1832008-12-05 05:30:02 +0000589 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
590 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
591 // is left behind appearing to clobber the super-register, while the
592 // subregister needs to remain live. So we just ignore them.
593 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
594 continue;
595
Dan Gohman00dc84a2008-12-16 19:27:52 +0000596 // Check if this instruction has a dependence on the critical path that
597 // is an anti-dependence that we may be able to break. If it is, set
598 // AntiDepReg to the non-zero register associated with the anti-dependence.
599 //
600 // We limit our attention to the critical path as a heuristic to avoid
601 // breaking anti-dependence edges that aren't going to significantly
602 // impact the overall schedule. There are a limited number of registers
603 // and we want to save them for the important edges.
604 //
605 // TODO: Instructions with multiple defs could have multiple
606 // anti-dependencies. The current code here only knows how to break one
607 // edge per instruction. Note that we'd have to be able to break all of
608 // the anti-dependencies in an instruction in order to be effective.
609 unsigned AntiDepReg = 0;
610 if (MI == CriticalPathMI) {
611 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
612 SUnit *NextSU = Edge->getSUnit();
613
614 // Only consider anti-dependence edges.
615 if (Edge->getKind() == SDep::Anti) {
616 AntiDepReg = Edge->getReg();
617 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
618 // Don't break anti-dependencies on non-allocatable registers.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000619 if (!AllocatableSet.test(AntiDepReg))
620 AntiDepReg = 0;
621 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000622 // If the SUnit has other dependencies on the SUnit that it
623 // anti-depends on, don't bother breaking the anti-dependency
624 // since those edges would prevent such units from being
625 // scheduled past each other regardless.
626 //
627 // Also, if there are dependencies on other SUnits with the
628 // same register as the anti-dependency, don't attempt to
629 // break it.
630 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
631 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
632 if (P->getSUnit() == NextSU ?
633 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
634 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
635 AntiDepReg = 0;
636 break;
637 }
638 }
639 }
640 CriticalPathSU = NextSU;
641 CriticalPathMI = CriticalPathSU->getInstr();
642 } else {
643 // We've reached the end of the critical path.
644 CriticalPathSU = 0;
645 CriticalPathMI = 0;
646 }
647 }
Dan Gohman21d90032008-11-25 00:52:40 +0000648
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000649 PrescanInstruction(MI);
650
651 // If this instruction has a use of AntiDepReg, breaking it
652 // is invalid.
Dan Gohman21d90032008-11-25 00:52:40 +0000653 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
654 MachineOperand &MO = MI->getOperand(i);
655 if (!MO.isReg()) continue;
656 unsigned Reg = MO.getReg();
657 if (Reg == 0) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000658 if (MO.isUse() && AntiDepReg == Reg) {
Dan Gohman21d90032008-11-25 00:52:40 +0000659 AntiDepReg = 0;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000660 break;
Dan Gohman21d90032008-11-25 00:52:40 +0000661 }
Dan Gohman21d90032008-11-25 00:52:40 +0000662 }
663
664 // Determine AntiDepReg's register class, if it is live and is
665 // consistently used within a single class.
666 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000667 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000668 "Register should be live if it's causing an anti-dependence!");
669 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
670 AntiDepReg = 0;
671
672 // Look for a suitable register to use to break the anti-depenence.
673 //
674 // TODO: Instead of picking the first free register, consider which might
675 // be the best.
676 if (AntiDepReg != 0) {
Dan Gohman79ce2762009-01-15 19:20:50 +0000677 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
678 RE = RC->allocation_order_end(MF); R != RE; ++R) {
Dan Gohman21d90032008-11-25 00:52:40 +0000679 unsigned NewReg = *R;
680 // Don't replace a register with itself.
681 if (NewReg == AntiDepReg) continue;
682 // Don't replace a register with one that was recently used to repair
683 // an anti-dependence with this AntiDepReg, because that would
684 // re-introduce that anti-dependence.
685 if (NewReg == LastNewReg[AntiDepReg]) continue;
686 // If NewReg is dead and NewReg's most recent def is not before
687 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000688 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000689 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000690 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000691 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000692 if (KillIndices[NewReg] == ~0u &&
Dan Gohmanfde221f2008-12-16 06:20:58 +0000693 Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000694 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000695 DEBUG(errs() << "Breaking anti-dependence edge on "
696 << TRI->getName(AntiDepReg)
697 << " with " << RegRefs.count(AntiDepReg) << " references"
698 << " using " << TRI->getName(NewReg) << "!\n");
Dan Gohman21d90032008-11-25 00:52:40 +0000699
700 // Update the references to the old register to refer to the new
701 // register.
702 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
703 std::multimap<unsigned, MachineOperand *>::iterator>
704 Range = RegRefs.equal_range(AntiDepReg);
705 for (std::multimap<unsigned, MachineOperand *>::iterator
706 Q = Range.first, QE = Range.second; Q != QE; ++Q)
707 Q->second->setReg(NewReg);
708
709 // We just went back in time and modified history; the
710 // liveness information for the anti-depenence reg is now
711 // inconsistent. Set the state as if it were dead.
712 Classes[NewReg] = Classes[AntiDepReg];
713 DefIndices[NewReg] = DefIndices[AntiDepReg];
714 KillIndices[NewReg] = KillIndices[AntiDepReg];
Dan Gohman47ac0f02009-02-11 04:27:20 +0000715 assert(((KillIndices[NewReg] == ~0u) !=
716 (DefIndices[NewReg] == ~0u)) &&
717 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000718
719 Classes[AntiDepReg] = 0;
720 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
Dan Gohman6c3643c2008-12-19 22:23:43 +0000721 KillIndices[AntiDepReg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000722 assert(((KillIndices[AntiDepReg] == ~0u) !=
723 (DefIndices[AntiDepReg] == ~0u)) &&
724 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000725
726 RegRefs.erase(AntiDepReg);
727 Changed = true;
728 LastNewReg[AntiDepReg] = NewReg;
729 break;
730 }
731 }
732 }
733
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000734 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000735 }
Dan Gohman21d90032008-11-25 00:52:40 +0000736
737 return Changed;
738}
739
Dan Gohman343f0c02008-11-19 23:18:57 +0000740//===----------------------------------------------------------------------===//
741// Top-Down Scheduling
742//===----------------------------------------------------------------------===//
743
744/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
745/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000746void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
747 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000748 --SuccSU->NumPredsLeft;
749
750#ifndef NDEBUG
751 if (SuccSU->NumPredsLeft < 0) {
752 cerr << "*** Scheduling failed! ***\n";
753 SuccSU->dump(this);
754 cerr << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000755 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +0000756 }
757#endif
758
759 // Compute how many cycles it will be before this actually becomes
760 // available. This is the max of the start time of all predecessors plus
761 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000762 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000763
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000764 // If all the node's predecessors are scheduled, this node is ready
765 // to be scheduled. Ignore the special ExitSU node.
766 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000767 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000768}
769
770/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
771void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
772 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
773 I != E; ++I)
774 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000775}
776
777/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
778/// count of its successors. If a successor pending count is zero, add it to
779/// the Available queue.
780void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000781 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman343f0c02008-11-19 23:18:57 +0000782 DEBUG(SU->dump(this));
783
784 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000785 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
786 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000787
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000788 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000789 SU->isScheduled = true;
790 AvailableQueue.ScheduledNode(SU);
791}
792
793/// ListScheduleTopDown - The main loop of list scheduling for top-down
794/// schedulers.
795void SchedulePostRATDList::ListScheduleTopDown() {
796 unsigned CurCycle = 0;
797
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000798 // Release any successors of the special Entry node.
799 ReleaseSuccessors(&EntrySU);
800
Dan Gohman343f0c02008-11-19 23:18:57 +0000801 // All leaves to Available queue.
802 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
803 // It is available if it has no predecessors.
804 if (SUnits[i].Preds.empty()) {
805 AvailableQueue.push(&SUnits[i]);
806 SUnits[i].isAvailable = true;
807 }
808 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000809
Dan Gohman343f0c02008-11-19 23:18:57 +0000810 // While Available queue is not empty, grab the node with the highest
811 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +0000812 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +0000813 Sequence.reserve(SUnits.size());
814 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
815 // Check to see if any of the pending instructions are ready to issue. If
816 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000817 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +0000818 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +0000819 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000820 AvailableQueue.push(PendingQueue[i]);
821 PendingQueue[i]->isAvailable = true;
822 PendingQueue[i] = PendingQueue.back();
823 PendingQueue.pop_back();
824 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +0000825 } else if (PendingQueue[i]->getDepth() < MinDepth)
826 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +0000827 }
David Goodwinc93d8372009-08-11 17:35:23 +0000828
829#ifndef NDEBUG
830 {
831 errs() << "\n*** Examining Available\n";
832 LatencyPriorityQueue q = AvailableQueue;
833 while (!q.empty()) {
834 SUnit *su = q.pop();
835 errs() << "Height " << su->getHeight() << ": ";
836 su->dump(this);
837 }
838 }
839#endif
840
Dan Gohman2836c282009-01-16 01:33:36 +0000841 SUnit *FoundSUnit = 0;
842
843 bool HasNoopHazards = false;
844 while (!AvailableQueue.empty()) {
845 SUnit *CurSUnit = AvailableQueue.pop();
846
847 ScheduleHazardRecognizer::HazardType HT =
848 HazardRec->getHazardType(CurSUnit);
849 if (HT == ScheduleHazardRecognizer::NoHazard) {
850 FoundSUnit = CurSUnit;
851 break;
852 }
853
854 // Remember if this is a noop hazard.
855 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
856
857 NotReady.push_back(CurSUnit);
858 }
859
860 // Add the nodes that aren't ready back onto the available list.
861 if (!NotReady.empty()) {
862 AvailableQueue.push_all(NotReady);
863 NotReady.clear();
864 }
865
Dan Gohman343f0c02008-11-19 23:18:57 +0000866 // If we found a node to schedule, do it now.
867 if (FoundSUnit) {
868 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +0000869 HazardRec->EmitInstruction(FoundSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000870
David Goodwind94a4e52009-08-10 15:55:25 +0000871 // If we are using the target-specific hazards, then don't
872 // advance the cycle time just because we schedule a node. If
873 // the target allows it we can schedule multiple nodes in the
874 // same cycle.
875 if (!EnablePostRAHazardAvoidance) {
876 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
877 ++CurCycle;
878 }
Dan Gohman2836c282009-01-16 01:33:36 +0000879 } else if (!HasNoopHazards) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000880 // Otherwise, we have a pipeline stall, but no other problem, just advance
881 // the current cycle and try again.
David Goodwin3a5f0d42009-08-11 01:44:26 +0000882 DEBUG(errs() << "*** Advancing cycle, no work to do\n");
Dan Gohman2836c282009-01-16 01:33:36 +0000883 HazardRec->AdvanceCycle();
Dan Gohman343f0c02008-11-19 23:18:57 +0000884 ++NumStalls;
885 ++CurCycle;
Dan Gohman2836c282009-01-16 01:33:36 +0000886 } else {
887 // Otherwise, we have no instructions to issue and we have instructions
888 // that will fault if we don't do this right. This is the case for
889 // processors without pipeline interlocks and other cases.
David Goodwin3a5f0d42009-08-11 01:44:26 +0000890 DEBUG(errs() << "*** Emitting noop\n");
Dan Gohman2836c282009-01-16 01:33:36 +0000891 HazardRec->EmitNoop();
892 Sequence.push_back(0); // NULL here means noop
893 ++NumNoops;
894 ++CurCycle;
Dan Gohman343f0c02008-11-19 23:18:57 +0000895 }
896 }
897
898#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000899 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000900#endif
901}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000902
903//===----------------------------------------------------------------------===//
904// Public Constructor Functions
905//===----------------------------------------------------------------------===//
906
907FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +0000908 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000909}