blob: a74d29db8c705da4c1625c67373c85366384e0c0 [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>
David Goodwin88a589c2009-08-25 17:03:05 +000043#include <set>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000044using namespace llvm;
45
Dan Gohman2836c282009-01-16 01:33:36 +000046STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000047STATISTIC(NumStalls, "Number of pipeline stalls");
48
Dan Gohman21d90032008-11-25 00:52:40 +000049static cl::opt<bool>
50EnableAntiDepBreaking("break-anti-dependencies",
Dan Gohman00dc84a2008-12-16 19:27:52 +000051 cl::desc("Break post-RA scheduling anti-dependencies"),
52 cl::init(true), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000053
Dan Gohman2836c282009-01-16 01:33:36 +000054static cl::opt<bool>
55EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwind94a4e52009-08-10 15:55:25 +000056 cl::desc("Enable exact hazard avoidance"),
57 cl::init(false), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000058
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000059namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000060 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000061 public:
62 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000063 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000064
Dan Gohman3f237442008-12-16 03:25:46 +000065 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000066 AU.setPreservesCFG();
Dan Gohman3f237442008-12-16 03:25:46 +000067 AU.addRequired<MachineDominatorTree>();
68 AU.addPreserved<MachineDominatorTree>();
69 AU.addRequired<MachineLoopInfo>();
70 AU.addPreserved<MachineLoopInfo>();
71 MachineFunctionPass::getAnalysisUsage(AU);
72 }
73
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000074 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000075 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000076 }
77
78 bool runOnMachineFunction(MachineFunction &Fn);
79 };
Dan Gohman343f0c02008-11-19 23:18:57 +000080 char PostRAScheduler::ID = 0;
81
82 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000083 /// AvailableQueue - The priority queue to use for the available SUnits.
84 ///
85 LatencyPriorityQueue AvailableQueue;
86
87 /// PendingQueue - This contains all of the instructions whose operands have
88 /// been issued, but their results are not ready yet (due to the latency of
89 /// the operation). Once the operands becomes available, the instruction is
90 /// added to the AvailableQueue.
91 std::vector<SUnit*> PendingQueue;
92
Dan Gohman21d90032008-11-25 00:52:40 +000093 /// Topo - A topological ordering for SUnits.
94 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +000095
Dan Gohman79ce2762009-01-15 19:20:50 +000096 /// AllocatableSet - The set of allocatable registers.
97 /// We'll be ignoring anti-dependencies on non-allocatable registers,
98 /// because they may not be safe to break.
99 const BitVector AllocatableSet;
100
Dan Gohman2836c282009-01-16 01:33:36 +0000101 /// HazardRec - The hazard recognizer to use.
102 ScheduleHazardRecognizer *HazardRec;
103
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000104 /// Classes - For live regs that are only used in one register class in a
105 /// live range, the register class. If the register is not live, the
106 /// corresponding value is null. If the register is live but used in
107 /// multiple register classes, the corresponding value is -1 casted to a
108 /// pointer.
109 const TargetRegisterClass *
110 Classes[TargetRegisterInfo::FirstVirtualRegister];
111
112 /// RegRegs - Map registers to all their references within a live range.
113 std::multimap<unsigned, MachineOperand *> RegRefs;
114
115 /// The index of the most recent kill (proceding bottom-up), or ~0u if
116 /// the register is not live.
117 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
118
119 /// The index of the most recent complete def (proceding bottom up), or ~0u
120 /// if the register is live.
121 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
122
Dan Gohman21d90032008-11-25 00:52:40 +0000123 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000124 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000125 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000126 const MachineDominatorTree &MDT,
127 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000128 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000129 AllocatableSet(TRI->getAllocatableSet(MF)),
130 HazardRec(HR) {}
131
132 ~SchedulePostRATDList() {
133 delete HazardRec;
134 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000135
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000136 /// StartBlock - Initialize register live-range state for scheduling in
137 /// this block.
138 ///
139 void StartBlock(MachineBasicBlock *BB);
140
141 /// Schedule - Schedule the instruction range using list scheduling.
142 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000143 void Schedule();
David Goodwin88a589c2009-08-25 17:03:05 +0000144
145 /// FixupKills - Fix register kill flags that have been made
146 /// invalid due to scheduling
147 ///
148 void FixupKills(MachineBasicBlock *MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000149
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000150 /// Observe - Update liveness information to account for the current
151 /// instruction, which will not be scheduled.
152 ///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000153 void Observe(MachineInstr *MI, unsigned Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000154
155 /// FinishBlock - Clean up register live-range state.
156 ///
157 void FinishBlock();
158
David Goodwin88a589c2009-08-25 17:03:05 +0000159 /// GenerateLivenessForKills - If true then generate Def/Kill
160 /// information for use in updating register kill. If false then
161 /// generate Def/Kill information for anti-dependence breaking.
162 bool GenerateLivenessForKills;
163
Dan Gohman343f0c02008-11-19 23:18:57 +0000164 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000165 void PrescanInstruction(MachineInstr *MI);
166 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000167 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000168 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000169 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
170 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000171 bool BreakAntiDependencies();
Dan Gohman26255ad2009-08-12 01:33:27 +0000172 unsigned findSuitableFreeRegister(unsigned AntiDepReg,
173 unsigned LastNewReg,
174 const TargetRegisterClass *);
Dan Gohman343f0c02008-11-19 23:18:57 +0000175 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000176}
177
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000178/// isSchedulingBoundary - Test if the given instruction should be
179/// considered a scheduling boundary. This primarily includes labels
180/// and terminators.
181///
182static bool isSchedulingBoundary(const MachineInstr *MI,
183 const MachineFunction &MF) {
184 // Terminators and labels can't be scheduled around.
185 if (MI->getDesc().isTerminator() || MI->isLabel())
186 return true;
187
Dan Gohmanbed353d2009-02-10 23:29:38 +0000188 // Don't attempt to schedule around any instruction that modifies
189 // a stack-oriented pointer, as it's unlikely to be profitable. This
190 // saves compile time, because it doesn't require every single
191 // stack slot reference to depend on the instruction that does the
192 // modification.
193 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
194 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
195 return true;
196
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000197 return false;
198}
199
Dan Gohman343f0c02008-11-19 23:18:57 +0000200bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000201 DEBUG(errs() << "PostRAScheduler\n");
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000202
Dan Gohman3f237442008-12-16 03:25:46 +0000203 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
204 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000205 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000206 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000207 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
208 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000209
Dan Gohman2836c282009-01-16 01:33:36 +0000210 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000211
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000212 // Loop over all of the basic blocks
213 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000214 MBB != MBBe; ++MBB) {
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000215 // Initialize register live-range state for scheduling in this block.
David Goodwin88a589c2009-08-25 17:03:05 +0000216 Scheduler.GenerateLivenessForKills = false;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000217 Scheduler.StartBlock(MBB);
218
Dan Gohmanf7119392009-01-16 22:10:20 +0000219 // Schedule each sequence of instructions not interrupted by a label
220 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000221 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000222 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000223 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
224 MachineInstr *MI = prior(I);
225 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000226 Scheduler.Run(MBB, I, Current, CurrentCount);
227 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000228 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000229 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000230 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000231 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000232 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000233 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000234 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000235 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000236 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000237 "Instruction count mismatch!");
238 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Dan Gohman343f0c02008-11-19 23:18:57 +0000239 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000240
241 // Clean up register live-range state.
242 Scheduler.FinishBlock();
David Goodwin88a589c2009-08-25 17:03:05 +0000243
244 // Initialize register live-range state again and update register kills
245 Scheduler.GenerateLivenessForKills = true;
246 Scheduler.StartBlock(MBB);
247 Scheduler.FixupKills(MBB);
248 Scheduler.FinishBlock();
Dan Gohman343f0c02008-11-19 23:18:57 +0000249 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000250
251 return true;
252}
253
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000254/// StartBlock - Initialize register live-range state for scheduling in
255/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000256///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000257void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
258 // Call the superclass.
259 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000260
David Goodwind94a4e52009-08-10 15:55:25 +0000261 // Reset the hazard recognizer.
262 HazardRec->Reset();
263
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000264 // Clear out the register class data.
265 std::fill(Classes, array_endof(Classes),
266 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000267
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000268 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000269 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000270 std::fill(DefIndices, array_endof(DefIndices), BB->size());
271
272 // Determine the live-out physregs for this block.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000273 if (!BB->empty() && BB->back().getDesc().isReturn())
Dan Gohman21d90032008-11-25 00:52:40 +0000274 // In a return block, examine the function live-out regs.
275 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
276 E = MRI.liveout_end(); I != E; ++I) {
277 unsigned Reg = *I;
278 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
279 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000280 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000281 // Repeat, for all aliases.
282 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
283 unsigned AliasReg = *Alias;
284 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
285 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000286 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000287 }
288 }
289 else
290 // In a non-return block, examine the live-in regs of all successors.
291 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
Dan Gohman47ac0f02009-02-11 04:27:20 +0000292 SE = BB->succ_end(); SI != SE; ++SI)
Dan Gohman21d90032008-11-25 00:52:40 +0000293 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
294 E = (*SI)->livein_end(); I != E; ++I) {
295 unsigned Reg = *I;
296 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
297 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000298 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000299 // Repeat, for all aliases.
300 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
301 unsigned AliasReg = *Alias;
302 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
303 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000304 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000305 }
306 }
307
David Goodwin88a589c2009-08-25 17:03:05 +0000308 if (!GenerateLivenessForKills) {
309 // Consider callee-saved registers as live-out, since we're running after
310 // prologue/epilogue insertion so there's no way to add additional
311 // saved registers.
312 //
313 // TODO: If the callee saves and restores these, then we can potentially
314 // use them between the save and the restore. To do that, we could scan
315 // the exit blocks to see which of these registers are defined.
316 // Alternatively, callee-saved registers that aren't saved and restored
317 // could be marked live-in in every block.
318 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
319 unsigned Reg = *I;
320 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
321 KillIndices[Reg] = BB->size();
322 DefIndices[Reg] = ~0u;
323 // Repeat, for all aliases.
324 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
325 unsigned AliasReg = *Alias;
326 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
327 KillIndices[AliasReg] = BB->size();
328 DefIndices[AliasReg] = ~0u;
329 }
Dan Gohman21d90032008-11-25 00:52:40 +0000330 }
331 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000332}
333
334/// Schedule - Schedule the instruction range using list scheduling.
335///
336void SchedulePostRATDList::Schedule() {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000337 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000338
339 // Build the scheduling graph.
340 BuildSchedGraph();
341
342 if (EnableAntiDepBreaking) {
343 if (BreakAntiDependencies()) {
344 // We made changes. Update the dependency graph.
345 // Theoretically we could update the graph in place:
346 // When a live range is changed to use a different register, remove
347 // the def's anti-dependence *and* output-dependence edges due to
348 // that register, and add new anti-dependence and output-dependence
349 // edges based on the next live range of the register.
350 SUnits.clear();
351 EntrySU = SUnit();
352 ExitSU = SUnit();
353 BuildSchedGraph();
354 }
355 }
356
David Goodwind94a4e52009-08-10 15:55:25 +0000357 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
358 SUnits[su].dumpAll(this));
359
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000360 AvailableQueue.initNodes(SUnits);
361
362 ListScheduleTopDown();
363
364 AvailableQueue.releaseState();
365}
366
367/// Observe - Update liveness information to account for the current
368/// instruction, which will not be scheduled.
369///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000370void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000371 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
372
373 // Any register which was defined within the previous scheduling region
374 // may have been rescheduled and its lifetime may overlap with registers
375 // in ways not reflected in our current liveness state. For each such
376 // register, adjust the liveness state to be conservatively correct.
377 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
378 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
379 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
380 // Mark this register to be non-renamable.
381 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
382 // Move the def index to the end of the previous region, to reflect
383 // that the def could theoretically have been scheduled at the end.
384 DefIndices[Reg] = InsertPosIndex;
385 }
386
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000387 PrescanInstruction(MI);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000388 ScanInstruction(MI, Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000389}
390
391/// FinishBlock - Clean up register live-range state.
392///
393void SchedulePostRATDList::FinishBlock() {
394 RegRefs.clear();
395
396 // Call the superclass.
397 ScheduleDAGInstrs::FinishBlock();
398}
399
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000400/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
401/// critical path.
402static SDep *CriticalPathStep(SUnit *SU) {
403 SDep *Next = 0;
404 unsigned NextDepth = 0;
405 // Find the predecessor edge with the greatest depth.
406 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
407 P != PE; ++P) {
408 SUnit *PredSU = P->getSUnit();
409 unsigned PredLatency = P->getLatency();
410 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
411 // In the case of a latency tie, prefer an anti-dependency edge over
412 // other types of edges.
413 if (NextDepth < PredTotalLatency ||
414 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
415 NextDepth = PredTotalLatency;
416 Next = &*P;
417 }
418 }
419 return Next;
420}
421
422void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
423 // Scan the register operands for this instruction and update
424 // Classes and RegRefs.
425 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
426 MachineOperand &MO = MI->getOperand(i);
427 if (!MO.isReg()) continue;
428 unsigned Reg = MO.getReg();
429 if (Reg == 0) continue;
Chris Lattner2a386882009-07-29 21:36:49 +0000430 const TargetRegisterClass *NewRC = 0;
431
432 if (i < MI->getDesc().getNumOperands())
433 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000434
435 // For now, only allow the register to be changed if its register
436 // class is consistent across all uses.
437 if (!Classes[Reg] && NewRC)
438 Classes[Reg] = NewRC;
439 else if (!NewRC || Classes[Reg] != NewRC)
440 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
441
442 // Now check for aliases.
443 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
444 // If an alias of the reg is used during the live range, give up.
445 // Note that this allows us to skip checking if AntiDepReg
446 // overlaps with any of the aliases, among other things.
447 unsigned AliasReg = *Alias;
448 if (Classes[AliasReg]) {
449 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
450 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
451 }
452 }
453
454 // If we're still willing to consider this register, note the reference.
455 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
456 RegRefs.insert(std::make_pair(Reg, &MO));
457 }
458}
459
460void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
461 unsigned Count) {
462 // Update liveness.
463 // Proceding upwards, registers that are defed but not used in this
464 // instruction are now dead.
465 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
466 MachineOperand &MO = MI->getOperand(i);
467 if (!MO.isReg()) continue;
468 unsigned Reg = MO.getReg();
469 if (Reg == 0) continue;
470 if (!MO.isDef()) continue;
471 // Ignore two-addr defs.
Bob Wilsond9df5012009-04-09 17:16:43 +0000472 if (MI->isRegTiedToUseOperand(i)) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000473
474 DefIndices[Reg] = Count;
475 KillIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000476 assert(((KillIndices[Reg] == ~0u) !=
477 (DefIndices[Reg] == ~0u)) &&
478 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000479 Classes[Reg] = 0;
480 RegRefs.erase(Reg);
481 // Repeat, for all subregs.
482 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
483 *Subreg; ++Subreg) {
484 unsigned SubregReg = *Subreg;
485 DefIndices[SubregReg] = Count;
486 KillIndices[SubregReg] = ~0u;
487 Classes[SubregReg] = 0;
488 RegRefs.erase(SubregReg);
489 }
David Goodwin88a589c2009-08-25 17:03:05 +0000490 // Conservatively mark super-registers as unusable. If
491 // initializing for kill updating, then mark all supers as defined
492 // as well.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000493 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
494 *Super; ++Super) {
495 unsigned SuperReg = *Super;
496 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
David Goodwin88a589c2009-08-25 17:03:05 +0000497 if (GenerateLivenessForKills) {
498 DefIndices[SuperReg] = Count;
499 KillIndices[SuperReg] = ~0u;
500 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000501 }
502 }
503 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
504 MachineOperand &MO = MI->getOperand(i);
505 if (!MO.isReg()) continue;
506 unsigned Reg = MO.getReg();
507 if (Reg == 0) continue;
508 if (!MO.isUse()) continue;
509
Chris Lattner2a386882009-07-29 21:36:49 +0000510 const TargetRegisterClass *NewRC = 0;
511 if (i < MI->getDesc().getNumOperands())
512 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000513
514 // For now, only allow the register to be changed if its register
515 // class is consistent across all uses.
516 if (!Classes[Reg] && NewRC)
517 Classes[Reg] = NewRC;
518 else if (!NewRC || Classes[Reg] != NewRC)
519 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
520
521 RegRefs.insert(std::make_pair(Reg, &MO));
522
523 // It wasn't previously live but now it is, this is a kill.
524 if (KillIndices[Reg] == ~0u) {
525 KillIndices[Reg] = Count;
526 DefIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000527 assert(((KillIndices[Reg] == ~0u) !=
528 (DefIndices[Reg] == ~0u)) &&
529 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000530 }
531 // Repeat, for all aliases.
532 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
533 unsigned AliasReg = *Alias;
534 if (KillIndices[AliasReg] == ~0u) {
535 KillIndices[AliasReg] = Count;
536 DefIndices[AliasReg] = ~0u;
537 }
538 }
539 }
540}
541
Dan Gohman26255ad2009-08-12 01:33:27 +0000542unsigned
543SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
544 unsigned LastNewReg,
545 const TargetRegisterClass *RC) {
546 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
547 RE = RC->allocation_order_end(MF); R != RE; ++R) {
548 unsigned NewReg = *R;
549 // Don't replace a register with itself.
550 if (NewReg == AntiDepReg) continue;
551 // Don't replace a register with one that was recently used to repair
552 // an anti-dependence with this AntiDepReg, because that would
553 // re-introduce that anti-dependence.
554 if (NewReg == LastNewReg) continue;
555 // If NewReg is dead and NewReg's most recent def is not before
556 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
557 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
558 "Kill and Def maps aren't consistent for AntiDepReg!");
559 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
560 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohmanda277572009-08-12 01:44:20 +0000561 if (KillIndices[NewReg] != ~0u ||
562 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
563 KillIndices[AntiDepReg] > DefIndices[NewReg])
Dan Gohman26255ad2009-08-12 01:33:27 +0000564 continue;
565 return NewReg;
566 }
567
568 // No registers are free and available!
569 return 0;
570}
571
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000572/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
573/// of the ScheduleDAG and break them by renaming registers.
574///
575bool SchedulePostRATDList::BreakAntiDependencies() {
576 // The code below assumes that there is at least one instruction,
577 // so just duck out immediately if the block is empty.
578 if (SUnits.empty()) return false;
579
580 // Find the node at the bottom of the critical path.
581 SUnit *Max = 0;
582 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
583 SUnit *SU = &SUnits[i];
584 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
585 Max = SU;
586 }
587
David Goodwin3a5f0d42009-08-11 01:44:26 +0000588 DEBUG(errs() << "Critical path has total latency "
589 << (Max->getDepth() + Max->Latency) << "\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000590
591 // Track progress along the critical path through the SUnit graph as we walk
592 // the instructions.
593 SUnit *CriticalPathSU = Max;
594 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000595
596 // Consider this pattern:
597 // A = ...
598 // ... = A
599 // A = ...
600 // ... = A
601 // A = ...
602 // ... = A
603 // A = ...
604 // ... = A
605 // There are three anti-dependencies here, and without special care,
606 // we'd break all of them using the same register:
607 // A = ...
608 // ... = A
609 // B = ...
610 // ... = B
611 // B = ...
612 // ... = B
613 // B = ...
614 // ... = B
615 // because at each anti-dependence, B is the first register that
616 // isn't A which is free. This re-introduces anti-dependencies
617 // at all but one of the original anti-dependencies that we were
618 // trying to break. To avoid this, keep track of the most recent
David Goodwinc93d8372009-08-11 17:35:23 +0000619 // register that each register was replaced with, avoid
Dan Gohman21d90032008-11-25 00:52:40 +0000620 // using it to repair an anti-dependence on the same register.
621 // This lets us produce this:
622 // A = ...
623 // ... = A
624 // B = ...
625 // ... = B
626 // C = ...
627 // ... = C
628 // B = ...
629 // ... = B
630 // This still has an anti-dependence on B, but at least it isn't on the
631 // original critical path.
632 //
633 // TODO: If we tracked more than one register here, we could potentially
634 // fix that remaining critical edge too. This is a little more involved,
635 // because unlike the most recent register, less recent registers should
636 // still be considered, though only if no other registers are available.
637 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
638
Dan Gohman21d90032008-11-25 00:52:40 +0000639 // Attempt to break anti-dependence edges on the critical path. Walk the
640 // instructions from the bottom up, tracking information about liveness
641 // as we go to help determine which registers are available.
642 bool Changed = false;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000643 unsigned Count = InsertPosIndex - 1;
644 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000645 I != E; --Count) {
646 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000647
Dan Gohman490b1832008-12-05 05:30:02 +0000648 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
649 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
650 // is left behind appearing to clobber the super-register, while the
651 // subregister needs to remain live. So we just ignore them.
652 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
653 continue;
654
Dan Gohman00dc84a2008-12-16 19:27:52 +0000655 // Check if this instruction has a dependence on the critical path that
656 // is an anti-dependence that we may be able to break. If it is, set
657 // AntiDepReg to the non-zero register associated with the anti-dependence.
658 //
659 // We limit our attention to the critical path as a heuristic to avoid
660 // breaking anti-dependence edges that aren't going to significantly
661 // impact the overall schedule. There are a limited number of registers
662 // and we want to save them for the important edges.
663 //
664 // TODO: Instructions with multiple defs could have multiple
665 // anti-dependencies. The current code here only knows how to break one
666 // edge per instruction. Note that we'd have to be able to break all of
667 // the anti-dependencies in an instruction in order to be effective.
668 unsigned AntiDepReg = 0;
669 if (MI == CriticalPathMI) {
670 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
671 SUnit *NextSU = Edge->getSUnit();
672
673 // Only consider anti-dependence edges.
674 if (Edge->getKind() == SDep::Anti) {
675 AntiDepReg = Edge->getReg();
676 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
677 // Don't break anti-dependencies on non-allocatable registers.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000678 if (!AllocatableSet.test(AntiDepReg))
679 AntiDepReg = 0;
680 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000681 // If the SUnit has other dependencies on the SUnit that it
682 // anti-depends on, don't bother breaking the anti-dependency
683 // since those edges would prevent such units from being
684 // scheduled past each other regardless.
685 //
686 // Also, if there are dependencies on other SUnits with the
687 // same register as the anti-dependency, don't attempt to
688 // break it.
689 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
690 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
691 if (P->getSUnit() == NextSU ?
692 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
693 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
694 AntiDepReg = 0;
695 break;
696 }
697 }
698 }
699 CriticalPathSU = NextSU;
700 CriticalPathMI = CriticalPathSU->getInstr();
701 } else {
702 // We've reached the end of the critical path.
703 CriticalPathSU = 0;
704 CriticalPathMI = 0;
705 }
706 }
Dan Gohman21d90032008-11-25 00:52:40 +0000707
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000708 PrescanInstruction(MI);
709
710 // If this instruction has a use of AntiDepReg, breaking it
711 // is invalid.
Dan Gohman21d90032008-11-25 00:52:40 +0000712 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
713 MachineOperand &MO = MI->getOperand(i);
714 if (!MO.isReg()) continue;
715 unsigned Reg = MO.getReg();
716 if (Reg == 0) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000717 if (MO.isUse() && AntiDepReg == Reg) {
Dan Gohman21d90032008-11-25 00:52:40 +0000718 AntiDepReg = 0;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000719 break;
Dan Gohman21d90032008-11-25 00:52:40 +0000720 }
Dan Gohman21d90032008-11-25 00:52:40 +0000721 }
722
723 // Determine AntiDepReg's register class, if it is live and is
724 // consistently used within a single class.
725 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000726 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000727 "Register should be live if it's causing an anti-dependence!");
728 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
729 AntiDepReg = 0;
730
731 // Look for a suitable register to use to break the anti-depenence.
732 //
733 // TODO: Instead of picking the first free register, consider which might
734 // be the best.
735 if (AntiDepReg != 0) {
Dan Gohman26255ad2009-08-12 01:33:27 +0000736 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
737 LastNewReg[AntiDepReg],
738 RC)) {
739 DEBUG(errs() << "Breaking anti-dependence edge on "
740 << TRI->getName(AntiDepReg)
741 << " with " << RegRefs.count(AntiDepReg) << " references"
742 << " using " << TRI->getName(NewReg) << "!\n");
Dan Gohman21d90032008-11-25 00:52:40 +0000743
Dan Gohman26255ad2009-08-12 01:33:27 +0000744 // Update the references to the old register to refer to the new
745 // register.
746 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
747 std::multimap<unsigned, MachineOperand *>::iterator>
748 Range = RegRefs.equal_range(AntiDepReg);
749 for (std::multimap<unsigned, MachineOperand *>::iterator
750 Q = Range.first, QE = Range.second; Q != QE; ++Q)
751 Q->second->setReg(NewReg);
Dan Gohman21d90032008-11-25 00:52:40 +0000752
Dan Gohman26255ad2009-08-12 01:33:27 +0000753 // We just went back in time and modified history; the
754 // liveness information for the anti-depenence reg is now
755 // inconsistent. Set the state as if it were dead.
756 Classes[NewReg] = Classes[AntiDepReg];
757 DefIndices[NewReg] = DefIndices[AntiDepReg];
758 KillIndices[NewReg] = KillIndices[AntiDepReg];
759 assert(((KillIndices[NewReg] == ~0u) !=
760 (DefIndices[NewReg] == ~0u)) &&
761 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000762
Dan Gohman26255ad2009-08-12 01:33:27 +0000763 Classes[AntiDepReg] = 0;
764 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
765 KillIndices[AntiDepReg] = ~0u;
766 assert(((KillIndices[AntiDepReg] == ~0u) !=
767 (DefIndices[AntiDepReg] == ~0u)) &&
768 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000769
Dan Gohman26255ad2009-08-12 01:33:27 +0000770 RegRefs.erase(AntiDepReg);
771 Changed = true;
772 LastNewReg[AntiDepReg] = NewReg;
Dan Gohman21d90032008-11-25 00:52:40 +0000773 }
774 }
775
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000776 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000777 }
Dan Gohman21d90032008-11-25 00:52:40 +0000778
779 return Changed;
780}
781
David Goodwin88a589c2009-08-25 17:03:05 +0000782/// FixupKills - Fix the register kill flags, they may have been made
783/// incorrect by instruction reordering.
784///
785void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
786 DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
787
788 std::set<unsigned> killedRegs;
789 BitVector ReservedRegs = TRI->getReservedRegs(MF);
790
791 unsigned Count = MBB->size();
792 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
793 I != E; --Count) {
794 MachineInstr *MI = --I;
795
796 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
797 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
798 // is left behind appearing to clobber the super-register, while the
799 // subregister needs to remain live. So we just ignore them.
800 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
801 continue;
802
803 PrescanInstruction(MI);
804 ScanInstruction(MI, Count);
805
806 // Examine all used registers and set kill flag. When a register
807 // is used multiple times we only set the kill flag on the first
808 // use.
809 killedRegs.clear();
810 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
811 MachineOperand &MO = MI->getOperand(i);
812 if (!MO.isReg() || !MO.isUse()) continue;
813 unsigned Reg = MO.getReg();
814 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
815
816 bool kill = ((KillIndices[Reg] == Count) &&
817 (killedRegs.find(Reg) == killedRegs.end()));
818 if (MO.isKill() != kill) {
819 MO.setIsKill(kill);
820 DEBUG(errs() << "Fixed " << MO << " in ");
821 DEBUG(MI->dump());
822 }
823
824 killedRegs.insert(Reg);
825 }
826 }
827}
828
Dan Gohman343f0c02008-11-19 23:18:57 +0000829//===----------------------------------------------------------------------===//
830// Top-Down Scheduling
831//===----------------------------------------------------------------------===//
832
833/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
834/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000835void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
836 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000837 --SuccSU->NumPredsLeft;
838
839#ifndef NDEBUG
840 if (SuccSU->NumPredsLeft < 0) {
Chris Lattner103289e2009-08-23 07:19:13 +0000841 errs() << "*** Scheduling failed! ***\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000842 SuccSU->dump(this);
Chris Lattner103289e2009-08-23 07:19:13 +0000843 errs() << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000844 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +0000845 }
846#endif
847
848 // Compute how many cycles it will be before this actually becomes
849 // available. This is the max of the start time of all predecessors plus
850 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000851 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000852
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000853 // If all the node's predecessors are scheduled, this node is ready
854 // to be scheduled. Ignore the special ExitSU node.
855 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000856 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000857}
858
859/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
860void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
861 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
862 I != E; ++I)
863 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000864}
865
866/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
867/// count of its successors. If a successor pending count is zero, add it to
868/// the Available queue.
869void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000870 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman343f0c02008-11-19 23:18:57 +0000871 DEBUG(SU->dump(this));
872
873 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000874 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
875 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000876
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000877 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000878 SU->isScheduled = true;
879 AvailableQueue.ScheduledNode(SU);
880}
881
882/// ListScheduleTopDown - The main loop of list scheduling for top-down
883/// schedulers.
884void SchedulePostRATDList::ListScheduleTopDown() {
885 unsigned CurCycle = 0;
886
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000887 // Release any successors of the special Entry node.
888 ReleaseSuccessors(&EntrySU);
889
Dan Gohman343f0c02008-11-19 23:18:57 +0000890 // All leaves to Available queue.
891 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
892 // It is available if it has no predecessors.
893 if (SUnits[i].Preds.empty()) {
894 AvailableQueue.push(&SUnits[i]);
895 SUnits[i].isAvailable = true;
896 }
897 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000898
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000899 // In any cycle where we can't schedule any instructions, we must
900 // stall or emit a noop, depending on the target.
901 bool CycleInstCnt = 0;
902
Dan Gohman343f0c02008-11-19 23:18:57 +0000903 // While Available queue is not empty, grab the node with the highest
904 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +0000905 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +0000906 Sequence.reserve(SUnits.size());
907 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
908 // Check to see if any of the pending instructions are ready to issue. If
909 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000910 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +0000911 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +0000912 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000913 AvailableQueue.push(PendingQueue[i]);
914 PendingQueue[i]->isAvailable = true;
915 PendingQueue[i] = PendingQueue.back();
916 PendingQueue.pop_back();
917 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +0000918 } else if (PendingQueue[i]->getDepth() < MinDepth)
919 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +0000920 }
David Goodwinc93d8372009-08-11 17:35:23 +0000921
David Goodwin7cd01182009-08-11 17:56:42 +0000922 DEBUG(errs() << "\n*** Examining Available\n";
923 LatencyPriorityQueue q = AvailableQueue;
924 while (!q.empty()) {
925 SUnit *su = q.pop();
926 errs() << "Height " << su->getHeight() << ": ";
927 su->dump(this);
928 });
David Goodwinc93d8372009-08-11 17:35:23 +0000929
Dan Gohman2836c282009-01-16 01:33:36 +0000930 SUnit *FoundSUnit = 0;
931
932 bool HasNoopHazards = false;
933 while (!AvailableQueue.empty()) {
934 SUnit *CurSUnit = AvailableQueue.pop();
935
936 ScheduleHazardRecognizer::HazardType HT =
937 HazardRec->getHazardType(CurSUnit);
938 if (HT == ScheduleHazardRecognizer::NoHazard) {
939 FoundSUnit = CurSUnit;
940 break;
941 }
942
943 // Remember if this is a noop hazard.
944 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
945
946 NotReady.push_back(CurSUnit);
947 }
948
949 // Add the nodes that aren't ready back onto the available list.
950 if (!NotReady.empty()) {
951 AvailableQueue.push_all(NotReady);
952 NotReady.clear();
953 }
954
Dan Gohman343f0c02008-11-19 23:18:57 +0000955 // If we found a node to schedule, do it now.
956 if (FoundSUnit) {
957 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +0000958 HazardRec->EmitInstruction(FoundSUnit);
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000959 CycleInstCnt++;
Dan Gohman343f0c02008-11-19 23:18:57 +0000960
David Goodwind94a4e52009-08-10 15:55:25 +0000961 // If we are using the target-specific hazards, then don't
962 // advance the cycle time just because we schedule a node. If
963 // the target allows it we can schedule multiple nodes in the
964 // same cycle.
965 if (!EnablePostRAHazardAvoidance) {
966 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
967 ++CurCycle;
968 }
Dan Gohman2836c282009-01-16 01:33:36 +0000969 } else {
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000970 if (CycleInstCnt > 0) {
971 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
972 HazardRec->AdvanceCycle();
973 } else if (!HasNoopHazards) {
974 // Otherwise, we have a pipeline stall, but no other problem,
975 // just advance the current cycle and try again.
976 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
977 HazardRec->AdvanceCycle();
978 ++NumStalls;
979 } else {
980 // Otherwise, we have no instructions to issue and we have instructions
981 // that will fault if we don't do this right. This is the case for
982 // processors without pipeline interlocks and other cases.
983 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
984 HazardRec->EmitNoop();
985 Sequence.push_back(0); // NULL here means noop
986 ++NumNoops;
987 }
988
Dan Gohman2836c282009-01-16 01:33:36 +0000989 ++CurCycle;
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000990 CycleInstCnt = 0;
Dan Gohman343f0c02008-11-19 23:18:57 +0000991 }
992 }
993
994#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000995 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000996#endif
997}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000998
999//===----------------------------------------------------------------------===//
1000// Public Constructor Functions
1001//===----------------------------------------------------------------------===//
1002
1003FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +00001004 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00001005}