blob: 3cd884763a7ebcbe12824d67a0f75547e75f7c3c [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"
Dan Gohman6dc75fe2009-02-06 17:12:10 +000022#include "ScheduleDAGInstrs.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000023#include "llvm/CodeGen/Passes.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000024#include "llvm/CodeGen/LatencyPriorityQueue.h"
25#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman3f237442008-12-16 03:25:46 +000026#include "llvm/CodeGen/MachineDominators.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000027#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman3f237442008-12-16 03:25:46 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman21d90032008-11-25 00:52:40 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman2836c282009-01-16 01:33:36 +000030#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohmanbed353d2009-02-10 23:29:38 +000031#include "llvm/Target/TargetLowering.h"
Dan Gohman79ce2762009-01-15 19:20:50 +000032#include "llvm/Target/TargetMachine.h"
Dan Gohman21d90032008-11-25 00:52:40 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner459525d2008-01-14 19:00:06 +000035#include "llvm/Support/Compiler.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000036#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000037#include "llvm/Support/ErrorHandling.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000038#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000039#include <map>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000040using namespace llvm;
41
Dan Gohman2836c282009-01-16 01:33:36 +000042STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000043STATISTIC(NumStalls, "Number of pipeline stalls");
44
Dan Gohman21d90032008-11-25 00:52:40 +000045static cl::opt<bool>
46EnableAntiDepBreaking("break-anti-dependencies",
Dan Gohman00dc84a2008-12-16 19:27:52 +000047 cl::desc("Break post-RA scheduling anti-dependencies"),
48 cl::init(true), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000049
Dan Gohman2836c282009-01-16 01:33:36 +000050static cl::opt<bool>
51EnablePostRAHazardAvoidance("avoid-hazards",
52 cl::desc("Enable simple hazard-avoidance"),
53 cl::init(true), cl::Hidden);
54
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000055namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000056 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000057 public:
58 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000059 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000060
Dan Gohman3f237442008-12-16 03:25:46 +000061 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000062 AU.setPreservesCFG();
Dan Gohman3f237442008-12-16 03:25:46 +000063 AU.addRequired<MachineDominatorTree>();
64 AU.addPreserved<MachineDominatorTree>();
65 AU.addRequired<MachineLoopInfo>();
66 AU.addPreserved<MachineLoopInfo>();
67 MachineFunctionPass::getAnalysisUsage(AU);
68 }
69
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000070 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000071 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000072 }
73
74 bool runOnMachineFunction(MachineFunction &Fn);
75 };
Dan Gohman343f0c02008-11-19 23:18:57 +000076 char PostRAScheduler::ID = 0;
77
78 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000079 /// AvailableQueue - The priority queue to use for the available SUnits.
80 ///
81 LatencyPriorityQueue AvailableQueue;
82
83 /// PendingQueue - This contains all of the instructions whose operands have
84 /// been issued, but their results are not ready yet (due to the latency of
85 /// the operation). Once the operands becomes available, the instruction is
86 /// added to the AvailableQueue.
87 std::vector<SUnit*> PendingQueue;
88
Dan Gohman21d90032008-11-25 00:52:40 +000089 /// Topo - A topological ordering for SUnits.
90 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +000091
Dan Gohman79ce2762009-01-15 19:20:50 +000092 /// AllocatableSet - The set of allocatable registers.
93 /// We'll be ignoring anti-dependencies on non-allocatable registers,
94 /// because they may not be safe to break.
95 const BitVector AllocatableSet;
96
Dan Gohman2836c282009-01-16 01:33:36 +000097 /// HazardRec - The hazard recognizer to use.
98 ScheduleHazardRecognizer *HazardRec;
99
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000100 /// Classes - For live regs that are only used in one register class in a
101 /// live range, the register class. If the register is not live, the
102 /// corresponding value is null. If the register is live but used in
103 /// multiple register classes, the corresponding value is -1 casted to a
104 /// pointer.
105 const TargetRegisterClass *
106 Classes[TargetRegisterInfo::FirstVirtualRegister];
107
108 /// RegRegs - Map registers to all their references within a live range.
109 std::multimap<unsigned, MachineOperand *> RegRefs;
110
111 /// The index of the most recent kill (proceding bottom-up), or ~0u if
112 /// the register is not live.
113 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
114
115 /// The index of the most recent complete def (proceding bottom up), or ~0u
116 /// if the register is live.
117 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
118
Dan Gohman21d90032008-11-25 00:52:40 +0000119 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000120 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000121 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000122 const MachineDominatorTree &MDT,
123 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000124 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000125 AllocatableSet(TRI->getAllocatableSet(MF)),
126 HazardRec(HR) {}
127
128 ~SchedulePostRATDList() {
129 delete HazardRec;
130 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000131
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000132 /// StartBlock - Initialize register live-range state for scheduling in
133 /// this block.
134 ///
135 void StartBlock(MachineBasicBlock *BB);
136
137 /// Schedule - Schedule the instruction range using list scheduling.
138 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000139 void Schedule();
140
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000141 /// Observe - Update liveness information to account for the current
142 /// instruction, which will not be scheduled.
143 ///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000144 void Observe(MachineInstr *MI, unsigned Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000145
146 /// FinishBlock - Clean up register live-range state.
147 ///
148 void FinishBlock();
149
Dan Gohman343f0c02008-11-19 23:18:57 +0000150 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000151 void PrescanInstruction(MachineInstr *MI);
152 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000153 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000154 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000155 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
156 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000157 bool BreakAntiDependencies();
Dan Gohman343f0c02008-11-19 23:18:57 +0000158 };
Dan Gohman2836c282009-01-16 01:33:36 +0000159
160 /// SimpleHazardRecognizer - A *very* simple hazard recognizer. It uses
161 /// a coarse classification and attempts to avoid that instructions of
162 /// a given class aren't grouped too densely together.
163 class SimpleHazardRecognizer : public ScheduleHazardRecognizer {
164 /// Class - A simple classification for SUnits.
165 enum Class {
166 Other, Load, Store
167 };
168
169 /// Window - The Class values of the most recently issued
170 /// instructions.
171 Class Window[8];
172
173 /// getClass - Classify the given SUnit.
174 Class getClass(const SUnit *SU) {
175 const MachineInstr *MI = SU->getInstr();
176 const TargetInstrDesc &TID = MI->getDesc();
177 if (TID.mayLoad())
178 return Load;
179 if (TID.mayStore())
180 return Store;
181 return Other;
182 }
183
184 /// Step - Rotate the existing entries in Window and insert the
185 /// given class value in position as the most recent.
186 void Step(Class C) {
187 std::copy(Window+1, array_endof(Window), Window);
188 Window[array_lengthof(Window)-1] = C;
189 }
190
191 public:
192 SimpleHazardRecognizer() : Window() {}
193
194 virtual HazardType getHazardType(SUnit *SU) {
195 Class C = getClass(SU);
196 if (C == Other)
197 return NoHazard;
198 unsigned Score = 0;
Dan Gohman79ce4ce2009-01-16 17:55:08 +0000199 for (unsigned i = 0; i != array_lengthof(Window); ++i)
Dan Gohman2836c282009-01-16 01:33:36 +0000200 if (Window[i] == C)
201 Score += i + 1;
202 if (Score > array_lengthof(Window) * 2)
203 return Hazard;
204 return NoHazard;
205 }
206
207 virtual void EmitInstruction(SUnit *SU) {
208 Step(getClass(SU));
209 }
210
211 virtual void AdvanceCycle() {
212 Step(Other);
213 }
214 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000215}
216
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000217/// isSchedulingBoundary - Test if the given instruction should be
218/// considered a scheduling boundary. This primarily includes labels
219/// and terminators.
220///
221static bool isSchedulingBoundary(const MachineInstr *MI,
222 const MachineFunction &MF) {
223 // Terminators and labels can't be scheduled around.
224 if (MI->getDesc().isTerminator() || MI->isLabel())
225 return true;
226
Dan Gohmanbed353d2009-02-10 23:29:38 +0000227 // Don't attempt to schedule around any instruction that modifies
228 // a stack-oriented pointer, as it's unlikely to be profitable. This
229 // saves compile time, because it doesn't require every single
230 // stack slot reference to depend on the instruction that does the
231 // modification.
232 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
233 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
234 return true;
235
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000236 return false;
237}
238
Dan Gohman343f0c02008-11-19 23:18:57 +0000239bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
240 DOUT << "PostRAScheduler\n";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000241
Dan Gohman3f237442008-12-16 03:25:46 +0000242 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
243 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
Dan Gohman2836c282009-01-16 01:33:36 +0000244 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
245 new SimpleHazardRecognizer :
246 new ScheduleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000247
Dan Gohman2836c282009-01-16 01:33:36 +0000248 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000249
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000250 // Loop over all of the basic blocks
251 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000252 MBB != MBBe; ++MBB) {
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000253 // Initialize register live-range state for scheduling in this block.
254 Scheduler.StartBlock(MBB);
255
Dan Gohmanf7119392009-01-16 22:10:20 +0000256 // Schedule each sequence of instructions not interrupted by a label
257 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000258 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000259 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000260 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
261 MachineInstr *MI = prior(I);
262 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000263 Scheduler.Run(MBB, I, Current, CurrentCount);
264 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000265 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000266 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000267 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000268 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000269 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000270 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000271 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000272 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000273 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000274 "Instruction count mismatch!");
275 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Dan Gohman343f0c02008-11-19 23:18:57 +0000276 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000277
278 // Clean up register live-range state.
279 Scheduler.FinishBlock();
Dan Gohman343f0c02008-11-19 23:18:57 +0000280 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000281
282 return true;
283}
284
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000285/// StartBlock - Initialize register live-range state for scheduling in
286/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000287///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000288void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
289 // Call the superclass.
290 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000291
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000292 // Clear out the register class data.
293 std::fill(Classes, array_endof(Classes),
294 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000295
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000296 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000297 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000298 std::fill(DefIndices, array_endof(DefIndices), BB->size());
299
300 // Determine the live-out physregs for this block.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000301 if (!BB->empty() && BB->back().getDesc().isReturn())
Dan Gohman21d90032008-11-25 00:52:40 +0000302 // In a return block, examine the function live-out regs.
303 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
304 E = MRI.liveout_end(); I != E; ++I) {
305 unsigned Reg = *I;
306 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
307 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000308 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000309 // Repeat, for all aliases.
310 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
311 unsigned AliasReg = *Alias;
312 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
313 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000314 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000315 }
316 }
317 else
318 // In a non-return block, examine the live-in regs of all successors.
319 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
Dan Gohman47ac0f02009-02-11 04:27:20 +0000320 SE = BB->succ_end(); SI != SE; ++SI)
Dan Gohman21d90032008-11-25 00:52:40 +0000321 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
322 E = (*SI)->livein_end(); I != E; ++I) {
323 unsigned Reg = *I;
324 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
325 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000326 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000327 // Repeat, for all aliases.
328 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
329 unsigned AliasReg = *Alias;
330 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
331 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000332 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000333 }
334 }
335
336 // Consider callee-saved registers as live-out, since we're running after
337 // prologue/epilogue insertion so there's no way to add additional
338 // saved registers.
339 //
340 // TODO: If the callee saves and restores these, then we can potentially
341 // use them between the save and the restore. To do that, we could scan
342 // the exit blocks to see which of these registers are defined.
Dan Gohman00dc84a2008-12-16 19:27:52 +0000343 // Alternatively, callee-saved registers that aren't saved and restored
Dan Gohmanebb0a312008-12-03 19:30:13 +0000344 // could be marked live-in in every block.
Dan Gohman21d90032008-11-25 00:52:40 +0000345 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
346 unsigned Reg = *I;
347 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
348 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000349 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000350 // Repeat, for all aliases.
351 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
352 unsigned AliasReg = *Alias;
353 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
354 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000355 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000356 }
357 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000358}
359
360/// Schedule - Schedule the instruction range using list scheduling.
361///
362void SchedulePostRATDList::Schedule() {
363 DOUT << "********** List Scheduling **********\n";
364
365 // Build the scheduling graph.
366 BuildSchedGraph();
367
368 if (EnableAntiDepBreaking) {
369 if (BreakAntiDependencies()) {
370 // We made changes. Update the dependency graph.
371 // Theoretically we could update the graph in place:
372 // When a live range is changed to use a different register, remove
373 // the def's anti-dependence *and* output-dependence edges due to
374 // that register, and add new anti-dependence and output-dependence
375 // edges based on the next live range of the register.
376 SUnits.clear();
377 EntrySU = SUnit();
378 ExitSU = SUnit();
379 BuildSchedGraph();
380 }
381 }
382
383 AvailableQueue.initNodes(SUnits);
384
385 ListScheduleTopDown();
386
387 AvailableQueue.releaseState();
388}
389
390/// Observe - Update liveness information to account for the current
391/// instruction, which will not be scheduled.
392///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000393void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000394 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
395
396 // Any register which was defined within the previous scheduling region
397 // may have been rescheduled and its lifetime may overlap with registers
398 // in ways not reflected in our current liveness state. For each such
399 // register, adjust the liveness state to be conservatively correct.
400 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
401 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
402 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
403 // Mark this register to be non-renamable.
404 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
405 // Move the def index to the end of the previous region, to reflect
406 // that the def could theoretically have been scheduled at the end.
407 DefIndices[Reg] = InsertPosIndex;
408 }
409
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000410 PrescanInstruction(MI);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000411 ScanInstruction(MI, Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000412}
413
414/// FinishBlock - Clean up register live-range state.
415///
416void SchedulePostRATDList::FinishBlock() {
417 RegRefs.clear();
418
419 // Call the superclass.
420 ScheduleDAGInstrs::FinishBlock();
421}
422
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000423/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
424/// critical path.
425static SDep *CriticalPathStep(SUnit *SU) {
426 SDep *Next = 0;
427 unsigned NextDepth = 0;
428 // Find the predecessor edge with the greatest depth.
429 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
430 P != PE; ++P) {
431 SUnit *PredSU = P->getSUnit();
432 unsigned PredLatency = P->getLatency();
433 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
434 // In the case of a latency tie, prefer an anti-dependency edge over
435 // other types of edges.
436 if (NextDepth < PredTotalLatency ||
437 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
438 NextDepth = PredTotalLatency;
439 Next = &*P;
440 }
441 }
442 return Next;
443}
444
445void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
446 // Scan the register operands for this instruction and update
447 // Classes and RegRefs.
448 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
449 MachineOperand &MO = MI->getOperand(i);
450 if (!MO.isReg()) continue;
451 unsigned Reg = MO.getReg();
452 if (Reg == 0) continue;
Chris Lattner2a386882009-07-29 21:36:49 +0000453 const TargetRegisterClass *NewRC = 0;
454
455 if (i < MI->getDesc().getNumOperands())
456 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000457
458 // For now, only allow the register to be changed if its register
459 // class is consistent across all uses.
460 if (!Classes[Reg] && NewRC)
461 Classes[Reg] = NewRC;
462 else if (!NewRC || Classes[Reg] != NewRC)
463 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
464
465 // Now check for aliases.
466 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
467 // If an alias of the reg is used during the live range, give up.
468 // Note that this allows us to skip checking if AntiDepReg
469 // overlaps with any of the aliases, among other things.
470 unsigned AliasReg = *Alias;
471 if (Classes[AliasReg]) {
472 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
473 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
474 }
475 }
476
477 // If we're still willing to consider this register, note the reference.
478 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
479 RegRefs.insert(std::make_pair(Reg, &MO));
480 }
481}
482
483void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
484 unsigned Count) {
485 // Update liveness.
486 // Proceding upwards, registers that are defed but not used in this
487 // instruction are now dead.
488 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
489 MachineOperand &MO = MI->getOperand(i);
490 if (!MO.isReg()) continue;
491 unsigned Reg = MO.getReg();
492 if (Reg == 0) continue;
493 if (!MO.isDef()) continue;
494 // Ignore two-addr defs.
Bob Wilsond9df5012009-04-09 17:16:43 +0000495 if (MI->isRegTiedToUseOperand(i)) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000496
497 DefIndices[Reg] = Count;
498 KillIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000499 assert(((KillIndices[Reg] == ~0u) !=
500 (DefIndices[Reg] == ~0u)) &&
501 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000502 Classes[Reg] = 0;
503 RegRefs.erase(Reg);
504 // Repeat, for all subregs.
505 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
506 *Subreg; ++Subreg) {
507 unsigned SubregReg = *Subreg;
508 DefIndices[SubregReg] = Count;
509 KillIndices[SubregReg] = ~0u;
510 Classes[SubregReg] = 0;
511 RegRefs.erase(SubregReg);
512 }
513 // Conservatively mark super-registers as unusable.
514 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
515 *Super; ++Super) {
516 unsigned SuperReg = *Super;
517 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
518 }
519 }
520 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
521 MachineOperand &MO = MI->getOperand(i);
522 if (!MO.isReg()) continue;
523 unsigned Reg = MO.getReg();
524 if (Reg == 0) continue;
525 if (!MO.isUse()) continue;
526
Chris Lattner2a386882009-07-29 21:36:49 +0000527 const TargetRegisterClass *NewRC = 0;
528 if (i < MI->getDesc().getNumOperands())
529 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000530
531 // For now, only allow the register to be changed if its register
532 // class is consistent across all uses.
533 if (!Classes[Reg] && NewRC)
534 Classes[Reg] = NewRC;
535 else if (!NewRC || Classes[Reg] != NewRC)
536 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
537
538 RegRefs.insert(std::make_pair(Reg, &MO));
539
540 // It wasn't previously live but now it is, this is a kill.
541 if (KillIndices[Reg] == ~0u) {
542 KillIndices[Reg] = Count;
543 DefIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000544 assert(((KillIndices[Reg] == ~0u) !=
545 (DefIndices[Reg] == ~0u)) &&
546 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000547 }
548 // Repeat, for all aliases.
549 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
550 unsigned AliasReg = *Alias;
551 if (KillIndices[AliasReg] == ~0u) {
552 KillIndices[AliasReg] = Count;
553 DefIndices[AliasReg] = ~0u;
554 }
555 }
556 }
557}
558
559/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
560/// of the ScheduleDAG and break them by renaming registers.
561///
562bool SchedulePostRATDList::BreakAntiDependencies() {
563 // The code below assumes that there is at least one instruction,
564 // so just duck out immediately if the block is empty.
565 if (SUnits.empty()) return false;
566
567 // Find the node at the bottom of the critical path.
568 SUnit *Max = 0;
569 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
570 SUnit *SU = &SUnits[i];
571 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
572 Max = SU;
573 }
574
575 DOUT << "Critical path has total latency "
576 << (Max->getDepth() + Max->Latency) << "\n";
577
578 // Track progress along the critical path through the SUnit graph as we walk
579 // the instructions.
580 SUnit *CriticalPathSU = Max;
581 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000582
583 // Consider this pattern:
584 // A = ...
585 // ... = A
586 // A = ...
587 // ... = A
588 // A = ...
589 // ... = A
590 // A = ...
591 // ... = A
592 // There are three anti-dependencies here, and without special care,
593 // we'd break all of them using the same register:
594 // A = ...
595 // ... = A
596 // B = ...
597 // ... = B
598 // B = ...
599 // ... = B
600 // B = ...
601 // ... = B
602 // because at each anti-dependence, B is the first register that
603 // isn't A which is free. This re-introduces anti-dependencies
604 // at all but one of the original anti-dependencies that we were
605 // trying to break. To avoid this, keep track of the most recent
606 // register that each register was replaced with, avoid avoid
607 // using it to repair an anti-dependence on the same register.
608 // This lets us produce this:
609 // A = ...
610 // ... = A
611 // B = ...
612 // ... = B
613 // C = ...
614 // ... = C
615 // B = ...
616 // ... = B
617 // This still has an anti-dependence on B, but at least it isn't on the
618 // original critical path.
619 //
620 // TODO: If we tracked more than one register here, we could potentially
621 // fix that remaining critical edge too. This is a little more involved,
622 // because unlike the most recent register, less recent registers should
623 // still be considered, though only if no other registers are available.
624 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
625
Dan Gohman21d90032008-11-25 00:52:40 +0000626 // Attempt to break anti-dependence edges on the critical path. Walk the
627 // instructions from the bottom up, tracking information about liveness
628 // as we go to help determine which registers are available.
629 bool Changed = false;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000630 unsigned Count = InsertPosIndex - 1;
631 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000632 I != E; --Count) {
633 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000634
Dan Gohman490b1832008-12-05 05:30:02 +0000635 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
636 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
637 // is left behind appearing to clobber the super-register, while the
638 // subregister needs to remain live. So we just ignore them.
639 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
640 continue;
641
Dan Gohman00dc84a2008-12-16 19:27:52 +0000642 // Check if this instruction has a dependence on the critical path that
643 // is an anti-dependence that we may be able to break. If it is, set
644 // AntiDepReg to the non-zero register associated with the anti-dependence.
645 //
646 // We limit our attention to the critical path as a heuristic to avoid
647 // breaking anti-dependence edges that aren't going to significantly
648 // impact the overall schedule. There are a limited number of registers
649 // and we want to save them for the important edges.
650 //
651 // TODO: Instructions with multiple defs could have multiple
652 // anti-dependencies. The current code here only knows how to break one
653 // edge per instruction. Note that we'd have to be able to break all of
654 // the anti-dependencies in an instruction in order to be effective.
655 unsigned AntiDepReg = 0;
656 if (MI == CriticalPathMI) {
657 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
658 SUnit *NextSU = Edge->getSUnit();
659
660 // Only consider anti-dependence edges.
661 if (Edge->getKind() == SDep::Anti) {
662 AntiDepReg = Edge->getReg();
663 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
664 // Don't break anti-dependencies on non-allocatable registers.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000665 if (!AllocatableSet.test(AntiDepReg))
666 AntiDepReg = 0;
667 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000668 // If the SUnit has other dependencies on the SUnit that it
669 // anti-depends on, don't bother breaking the anti-dependency
670 // since those edges would prevent such units from being
671 // scheduled past each other regardless.
672 //
673 // Also, if there are dependencies on other SUnits with the
674 // same register as the anti-dependency, don't attempt to
675 // break it.
676 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
677 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
678 if (P->getSUnit() == NextSU ?
679 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
680 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
681 AntiDepReg = 0;
682 break;
683 }
684 }
685 }
686 CriticalPathSU = NextSU;
687 CriticalPathMI = CriticalPathSU->getInstr();
688 } else {
689 // We've reached the end of the critical path.
690 CriticalPathSU = 0;
691 CriticalPathMI = 0;
692 }
693 }
Dan Gohman21d90032008-11-25 00:52:40 +0000694
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000695 PrescanInstruction(MI);
696
697 // If this instruction has a use of AntiDepReg, breaking it
698 // is invalid.
Dan Gohman21d90032008-11-25 00:52:40 +0000699 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
700 MachineOperand &MO = MI->getOperand(i);
701 if (!MO.isReg()) continue;
702 unsigned Reg = MO.getReg();
703 if (Reg == 0) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000704 if (MO.isUse() && AntiDepReg == Reg) {
Dan Gohman21d90032008-11-25 00:52:40 +0000705 AntiDepReg = 0;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000706 break;
Dan Gohman21d90032008-11-25 00:52:40 +0000707 }
Dan Gohman21d90032008-11-25 00:52:40 +0000708 }
709
710 // Determine AntiDepReg's register class, if it is live and is
711 // consistently used within a single class.
712 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000713 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000714 "Register should be live if it's causing an anti-dependence!");
715 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
716 AntiDepReg = 0;
717
718 // Look for a suitable register to use to break the anti-depenence.
719 //
720 // TODO: Instead of picking the first free register, consider which might
721 // be the best.
722 if (AntiDepReg != 0) {
Dan Gohman79ce2762009-01-15 19:20:50 +0000723 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
724 RE = RC->allocation_order_end(MF); R != RE; ++R) {
Dan Gohman21d90032008-11-25 00:52:40 +0000725 unsigned NewReg = *R;
726 // Don't replace a register with itself.
727 if (NewReg == AntiDepReg) continue;
728 // Don't replace a register with one that was recently used to repair
729 // an anti-dependence with this AntiDepReg, because that would
730 // re-introduce that anti-dependence.
731 if (NewReg == LastNewReg[AntiDepReg]) continue;
732 // If NewReg is dead and NewReg's most recent def is not before
733 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000734 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000735 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000736 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000737 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000738 if (KillIndices[NewReg] == ~0u &&
Dan Gohmanfde221f2008-12-16 06:20:58 +0000739 Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000740 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
Dan Gohman80e201b2008-12-04 02:15:26 +0000741 DOUT << "Breaking anti-dependence edge on "
742 << TRI->getName(AntiDepReg)
Dan Gohmancef874a2008-12-03 23:07:27 +0000743 << " with " << RegRefs.count(AntiDepReg) << " references"
Dan Gohman80e201b2008-12-04 02:15:26 +0000744 << " using " << TRI->getName(NewReg) << "!\n";
Dan Gohman21d90032008-11-25 00:52:40 +0000745
746 // Update the references to the old register to refer to the new
747 // register.
748 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
749 std::multimap<unsigned, MachineOperand *>::iterator>
750 Range = RegRefs.equal_range(AntiDepReg);
751 for (std::multimap<unsigned, MachineOperand *>::iterator
752 Q = Range.first, QE = Range.second; Q != QE; ++Q)
753 Q->second->setReg(NewReg);
754
755 // We just went back in time and modified history; the
756 // liveness information for the anti-depenence reg is now
757 // inconsistent. Set the state as if it were dead.
758 Classes[NewReg] = Classes[AntiDepReg];
759 DefIndices[NewReg] = DefIndices[AntiDepReg];
760 KillIndices[NewReg] = KillIndices[AntiDepReg];
Dan Gohman47ac0f02009-02-11 04:27:20 +0000761 assert(((KillIndices[NewReg] == ~0u) !=
762 (DefIndices[NewReg] == ~0u)) &&
763 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000764
765 Classes[AntiDepReg] = 0;
766 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
Dan Gohman6c3643c2008-12-19 22:23:43 +0000767 KillIndices[AntiDepReg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000768 assert(((KillIndices[AntiDepReg] == ~0u) !=
769 (DefIndices[AntiDepReg] == ~0u)) &&
770 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000771
772 RegRefs.erase(AntiDepReg);
773 Changed = true;
774 LastNewReg[AntiDepReg] = NewReg;
775 break;
776 }
777 }
778 }
779
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000780 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000781 }
Dan Gohman21d90032008-11-25 00:52:40 +0000782
783 return Changed;
784}
785
Dan Gohman343f0c02008-11-19 23:18:57 +0000786//===----------------------------------------------------------------------===//
787// Top-Down Scheduling
788//===----------------------------------------------------------------------===//
789
790/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
791/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000792void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
793 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000794 --SuccSU->NumPredsLeft;
795
796#ifndef NDEBUG
797 if (SuccSU->NumPredsLeft < 0) {
798 cerr << "*** Scheduling failed! ***\n";
799 SuccSU->dump(this);
800 cerr << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000801 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +0000802 }
803#endif
804
805 // Compute how many cycles it will be before this actually becomes
806 // available. This is the max of the start time of all predecessors plus
807 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000808 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000809
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000810 // If all the node's predecessors are scheduled, this node is ready
811 // to be scheduled. Ignore the special ExitSU node.
812 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000813 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000814}
815
816/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
817void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
818 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
819 I != E; ++I)
820 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000821}
822
823/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
824/// count of its successors. If a successor pending count is zero, add it to
825/// the Available queue.
826void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
827 DOUT << "*** Scheduling [" << CurCycle << "]: ";
828 DEBUG(SU->dump(this));
829
830 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000831 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
832 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000833
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000834 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000835 SU->isScheduled = true;
836 AvailableQueue.ScheduledNode(SU);
837}
838
839/// ListScheduleTopDown - The main loop of list scheduling for top-down
840/// schedulers.
841void SchedulePostRATDList::ListScheduleTopDown() {
842 unsigned CurCycle = 0;
843
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000844 // Release any successors of the special Entry node.
845 ReleaseSuccessors(&EntrySU);
846
Dan Gohman343f0c02008-11-19 23:18:57 +0000847 // All leaves to Available queue.
848 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
849 // It is available if it has no predecessors.
850 if (SUnits[i].Preds.empty()) {
851 AvailableQueue.push(&SUnits[i]);
852 SUnits[i].isAvailable = true;
853 }
854 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000855
Dan Gohman343f0c02008-11-19 23:18:57 +0000856 // While Available queue is not empty, grab the node with the highest
857 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +0000858 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +0000859 Sequence.reserve(SUnits.size());
860 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
861 // Check to see if any of the pending instructions are ready to issue. If
862 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000863 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +0000864 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +0000865 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000866 AvailableQueue.push(PendingQueue[i]);
867 PendingQueue[i]->isAvailable = true;
868 PendingQueue[i] = PendingQueue.back();
869 PendingQueue.pop_back();
870 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +0000871 } else if (PendingQueue[i]->getDepth() < MinDepth)
872 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +0000873 }
874
Dan Gohman2836c282009-01-16 01:33:36 +0000875 // If there are no instructions available, don't try to issue anything, and
876 // don't advance the hazard recognizer.
Dan Gohman343f0c02008-11-19 23:18:57 +0000877 if (AvailableQueue.empty()) {
Dan Gohman3f237442008-12-16 03:25:46 +0000878 CurCycle = MinDepth != ~0u ? MinDepth : CurCycle + 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000879 continue;
880 }
881
Dan Gohman2836c282009-01-16 01:33:36 +0000882 SUnit *FoundSUnit = 0;
883
884 bool HasNoopHazards = false;
885 while (!AvailableQueue.empty()) {
886 SUnit *CurSUnit = AvailableQueue.pop();
887
888 ScheduleHazardRecognizer::HazardType HT =
889 HazardRec->getHazardType(CurSUnit);
890 if (HT == ScheduleHazardRecognizer::NoHazard) {
891 FoundSUnit = CurSUnit;
892 break;
893 }
894
895 // Remember if this is a noop hazard.
896 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
897
898 NotReady.push_back(CurSUnit);
899 }
900
901 // Add the nodes that aren't ready back onto the available list.
902 if (!NotReady.empty()) {
903 AvailableQueue.push_all(NotReady);
904 NotReady.clear();
905 }
906
Dan Gohman343f0c02008-11-19 23:18:57 +0000907 // If we found a node to schedule, do it now.
908 if (FoundSUnit) {
909 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +0000910 HazardRec->EmitInstruction(FoundSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000911
912 // If this is a pseudo-op node, we don't want to increment the current
913 // cycle.
914 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
Dan Gohman2836c282009-01-16 01:33:36 +0000915 ++CurCycle;
916 } else if (!HasNoopHazards) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000917 // Otherwise, we have a pipeline stall, but no other problem, just advance
918 // the current cycle and try again.
919 DOUT << "*** Advancing cycle, no work to do\n";
Dan Gohman2836c282009-01-16 01:33:36 +0000920 HazardRec->AdvanceCycle();
Dan Gohman343f0c02008-11-19 23:18:57 +0000921 ++NumStalls;
922 ++CurCycle;
Dan Gohman2836c282009-01-16 01:33:36 +0000923 } else {
924 // Otherwise, we have no instructions to issue and we have instructions
925 // that will fault if we don't do this right. This is the case for
926 // processors without pipeline interlocks and other cases.
927 DOUT << "*** Emitting noop\n";
928 HazardRec->EmitNoop();
929 Sequence.push_back(0); // NULL here means noop
930 ++NumNoops;
931 ++CurCycle;
Dan Gohman343f0c02008-11-19 23:18:57 +0000932 }
933 }
934
935#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000936 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000937#endif
938}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000939
940//===----------------------------------------------------------------------===//
941// Public Constructor Functions
942//===----------------------------------------------------------------------===//
943
944FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +0000945 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000946}