blob: e1491256fe1a39745ddb66e40b11ced972d508a1 [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"),
David Goodwin5e411782009-09-03 22:15:25 +000057 cl::init(true), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000058
David Goodwin1f152282009-09-01 18:34:03 +000059// If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
60static cl::opt<int>
61DebugDiv("postra-sched-debugdiv",
62 cl::desc("Debug control MBBs that are scheduled"),
63 cl::init(0), cl::Hidden);
64static cl::opt<int>
65DebugMod("postra-sched-debugmod",
66 cl::desc("Debug control MBBs that are scheduled"),
67 cl::init(0), cl::Hidden);
68
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000069namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000070 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000071 public:
72 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000073 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000074
Dan Gohman3f237442008-12-16 03:25:46 +000075 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000076 AU.setPreservesCFG();
Dan Gohman3f237442008-12-16 03:25:46 +000077 AU.addRequired<MachineDominatorTree>();
78 AU.addPreserved<MachineDominatorTree>();
79 AU.addRequired<MachineLoopInfo>();
80 AU.addPreserved<MachineLoopInfo>();
81 MachineFunctionPass::getAnalysisUsage(AU);
82 }
83
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000084 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000085 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000086 }
87
88 bool runOnMachineFunction(MachineFunction &Fn);
89 };
Dan Gohman343f0c02008-11-19 23:18:57 +000090 char PostRAScheduler::ID = 0;
91
92 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000093 /// AvailableQueue - The priority queue to use for the available SUnits.
94 ///
95 LatencyPriorityQueue AvailableQueue;
96
97 /// PendingQueue - This contains all of the instructions whose operands have
98 /// been issued, but their results are not ready yet (due to the latency of
99 /// the operation). Once the operands becomes available, the instruction is
100 /// added to the AvailableQueue.
101 std::vector<SUnit*> PendingQueue;
102
Dan Gohman21d90032008-11-25 00:52:40 +0000103 /// Topo - A topological ordering for SUnits.
104 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +0000105
Dan Gohman79ce2762009-01-15 19:20:50 +0000106 /// AllocatableSet - The set of allocatable registers.
107 /// We'll be ignoring anti-dependencies on non-allocatable registers,
108 /// because they may not be safe to break.
109 const BitVector AllocatableSet;
110
Dan Gohman2836c282009-01-16 01:33:36 +0000111 /// HazardRec - The hazard recognizer to use.
112 ScheduleHazardRecognizer *HazardRec;
113
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000114 /// Classes - For live regs that are only used in one register class in a
115 /// live range, the register class. If the register is not live, the
116 /// corresponding value is null. If the register is live but used in
117 /// multiple register classes, the corresponding value is -1 casted to a
118 /// pointer.
119 const TargetRegisterClass *
120 Classes[TargetRegisterInfo::FirstVirtualRegister];
121
122 /// RegRegs - Map registers to all their references within a live range.
123 std::multimap<unsigned, MachineOperand *> RegRefs;
124
125 /// The index of the most recent kill (proceding bottom-up), or ~0u if
126 /// the register is not live.
127 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
128
129 /// The index of the most recent complete def (proceding bottom up), or ~0u
130 /// if the register is live.
131 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
132
Dan Gohman21d90032008-11-25 00:52:40 +0000133 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000134 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000135 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000136 const MachineDominatorTree &MDT,
137 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000138 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000139 AllocatableSet(TRI->getAllocatableSet(MF)),
140 HazardRec(HR) {}
141
142 ~SchedulePostRATDList() {
143 delete HazardRec;
144 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000145
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000146 /// StartBlock - Initialize register live-range state for scheduling in
147 /// this block.
148 ///
149 void StartBlock(MachineBasicBlock *BB);
150
151 /// Schedule - Schedule the instruction range using list scheduling.
152 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000153 void Schedule();
David Goodwin88a589c2009-08-25 17:03:05 +0000154
155 /// FixupKills - Fix register kill flags that have been made
156 /// invalid due to scheduling
157 ///
158 void FixupKills(MachineBasicBlock *MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000159
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000160 /// Observe - Update liveness information to account for the current
161 /// instruction, which will not be scheduled.
162 ///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000163 void Observe(MachineInstr *MI, unsigned Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000164
165 /// FinishBlock - Clean up register live-range state.
166 ///
167 void FinishBlock();
168
Dan Gohman343f0c02008-11-19 23:18:57 +0000169 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000170 void PrescanInstruction(MachineInstr *MI);
171 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000172 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000173 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000174 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
175 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000176 bool BreakAntiDependencies();
Dan Gohman26255ad2009-08-12 01:33:27 +0000177 unsigned findSuitableFreeRegister(unsigned AntiDepReg,
178 unsigned LastNewReg,
179 const TargetRegisterClass *);
David Goodwin5e411782009-09-03 22:15:25 +0000180 void StartBlockForKills(MachineBasicBlock *BB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000181 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000182}
183
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000184/// isSchedulingBoundary - Test if the given instruction should be
185/// considered a scheduling boundary. This primarily includes labels
186/// and terminators.
187///
188static bool isSchedulingBoundary(const MachineInstr *MI,
189 const MachineFunction &MF) {
190 // Terminators and labels can't be scheduled around.
191 if (MI->getDesc().isTerminator() || MI->isLabel())
192 return true;
193
Dan Gohmanbed353d2009-02-10 23:29:38 +0000194 // Don't attempt to schedule around any instruction that modifies
195 // a stack-oriented pointer, as it's unlikely to be profitable. This
196 // saves compile time, because it doesn't require every single
197 // stack slot reference to depend on the instruction that does the
198 // modification.
199 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
200 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
201 return true;
202
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000203 return false;
204}
205
Dan Gohman343f0c02008-11-19 23:18:57 +0000206bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000207 DEBUG(errs() << "PostRAScheduler\n");
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000208
Dan Gohman3f237442008-12-16 03:25:46 +0000209 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
210 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000211 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000212 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000213 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
214 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000215
Dan Gohman2836c282009-01-16 01:33:36 +0000216 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000217
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000218 // Loop over all of the basic blocks
219 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000220 MBB != MBBe; ++MBB) {
David Goodwin1f152282009-09-01 18:34:03 +0000221#ifndef NDEBUG
222 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
223 if (DebugDiv > 0) {
224 static int bbcnt = 0;
225 if (bbcnt++ % DebugDiv != DebugMod)
226 continue;
227 errs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
228 ":MBB ID#" << MBB->getNumber() << " ***\n";
229 }
230#endif
231
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000232 // Initialize register live-range state for scheduling in this block.
233 Scheduler.StartBlock(MBB);
234
Dan Gohmanf7119392009-01-16 22:10:20 +0000235 // Schedule each sequence of instructions not interrupted by a label
236 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000237 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000238 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000239 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
240 MachineInstr *MI = prior(I);
241 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000242 Scheduler.Run(MBB, I, Current, CurrentCount);
243 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000244 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000245 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000246 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000247 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000248 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000249 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000250 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000251 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000252 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000253 "Instruction count mismatch!");
254 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Dan Gohman343f0c02008-11-19 23:18:57 +0000255 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000256
257 // Clean up register live-range state.
258 Scheduler.FinishBlock();
David Goodwin88a589c2009-08-25 17:03:05 +0000259
David Goodwin5e411782009-09-03 22:15:25 +0000260 // Update register kills
David Goodwin88a589c2009-08-25 17:03:05 +0000261 Scheduler.FixupKills(MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000262 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000263
264 return true;
265}
266
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000267/// StartBlock - Initialize register live-range state for scheduling in
268/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000269///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000270void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
271 // Call the superclass.
272 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000273
David Goodwind94a4e52009-08-10 15:55:25 +0000274 // Reset the hazard recognizer.
275 HazardRec->Reset();
276
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000277 // Clear out the register class data.
278 std::fill(Classes, array_endof(Classes),
279 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000280
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000281 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000282 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000283 std::fill(DefIndices, array_endof(DefIndices), BB->size());
284
285 // Determine the live-out physregs for this block.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000286 if (!BB->empty() && BB->back().getDesc().isReturn())
Dan Gohman21d90032008-11-25 00:52:40 +0000287 // In a return block, examine the function live-out regs.
288 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
289 E = MRI.liveout_end(); I != E; ++I) {
290 unsigned Reg = *I;
291 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
292 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000293 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000294 // Repeat, for all aliases.
295 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
296 unsigned AliasReg = *Alias;
297 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
298 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000299 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000300 }
301 }
302 else
303 // In a non-return block, examine the live-in regs of all successors.
304 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
Dan Gohman47ac0f02009-02-11 04:27:20 +0000305 SE = BB->succ_end(); SI != SE; ++SI)
Dan Gohman21d90032008-11-25 00:52:40 +0000306 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
307 E = (*SI)->livein_end(); I != E; ++I) {
308 unsigned Reg = *I;
309 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
310 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000311 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000312 // Repeat, for all aliases.
313 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
314 unsigned AliasReg = *Alias;
315 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
316 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000317 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000318 }
319 }
320
David Goodwin5e411782009-09-03 22:15:25 +0000321 // Consider callee-saved registers as live-out, since we're running after
322 // prologue/epilogue insertion so there's no way to add additional
323 // saved registers.
324 //
325 // TODO: there is a new method
326 // MachineFrameInfo::getPristineRegs(MBB). It gives you a list of
327 // CSRs that have not been saved when entering the MBB. The
328 // remaining CSRs have been saved and can be treated like call
329 // clobbered registers.
330 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
331 unsigned Reg = *I;
332 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
333 KillIndices[Reg] = BB->size();
334 DefIndices[Reg] = ~0u;
335 // Repeat, for all aliases.
336 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
337 unsigned AliasReg = *Alias;
338 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
339 KillIndices[AliasReg] = BB->size();
340 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000341 }
342 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000343}
344
345/// Schedule - Schedule the instruction range using list scheduling.
346///
347void SchedulePostRATDList::Schedule() {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000348 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000349
350 // Build the scheduling graph.
351 BuildSchedGraph();
352
353 if (EnableAntiDepBreaking) {
354 if (BreakAntiDependencies()) {
355 // We made changes. Update the dependency graph.
356 // Theoretically we could update the graph in place:
357 // When a live range is changed to use a different register, remove
358 // the def's anti-dependence *and* output-dependence edges due to
359 // that register, and add new anti-dependence and output-dependence
360 // edges based on the next live range of the register.
361 SUnits.clear();
362 EntrySU = SUnit();
363 ExitSU = SUnit();
364 BuildSchedGraph();
365 }
366 }
367
David Goodwind94a4e52009-08-10 15:55:25 +0000368 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
369 SUnits[su].dumpAll(this));
370
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000371 AvailableQueue.initNodes(SUnits);
372
373 ListScheduleTopDown();
374
375 AvailableQueue.releaseState();
376}
377
378/// Observe - Update liveness information to account for the current
379/// instruction, which will not be scheduled.
380///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000381void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000382 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
383
384 // Any register which was defined within the previous scheduling region
385 // may have been rescheduled and its lifetime may overlap with registers
386 // in ways not reflected in our current liveness state. For each such
387 // register, adjust the liveness state to be conservatively correct.
388 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
389 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
390 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
391 // Mark this register to be non-renamable.
392 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
393 // Move the def index to the end of the previous region, to reflect
394 // that the def could theoretically have been scheduled at the end.
395 DefIndices[Reg] = InsertPosIndex;
396 }
397
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000398 PrescanInstruction(MI);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000399 ScanInstruction(MI, Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000400}
401
402/// FinishBlock - Clean up register live-range state.
403///
404void SchedulePostRATDList::FinishBlock() {
405 RegRefs.clear();
406
407 // Call the superclass.
408 ScheduleDAGInstrs::FinishBlock();
409}
410
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000411/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
412/// critical path.
413static SDep *CriticalPathStep(SUnit *SU) {
414 SDep *Next = 0;
415 unsigned NextDepth = 0;
416 // Find the predecessor edge with the greatest depth.
417 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
418 P != PE; ++P) {
419 SUnit *PredSU = P->getSUnit();
420 unsigned PredLatency = P->getLatency();
421 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
422 // In the case of a latency tie, prefer an anti-dependency edge over
423 // other types of edges.
424 if (NextDepth < PredTotalLatency ||
425 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
426 NextDepth = PredTotalLatency;
427 Next = &*P;
428 }
429 }
430 return Next;
431}
432
433void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
434 // Scan the register operands for this instruction and update
435 // Classes and RegRefs.
436 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
437 MachineOperand &MO = MI->getOperand(i);
438 if (!MO.isReg()) continue;
439 unsigned Reg = MO.getReg();
440 if (Reg == 0) continue;
Chris Lattner2a386882009-07-29 21:36:49 +0000441 const TargetRegisterClass *NewRC = 0;
442
443 if (i < MI->getDesc().getNumOperands())
444 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000445
446 // For now, only allow the register to be changed if its register
447 // class is consistent across all uses.
448 if (!Classes[Reg] && NewRC)
449 Classes[Reg] = NewRC;
450 else if (!NewRC || Classes[Reg] != NewRC)
451 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
452
453 // Now check for aliases.
454 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
455 // If an alias of the reg is used during the live range, give up.
456 // Note that this allows us to skip checking if AntiDepReg
457 // overlaps with any of the aliases, among other things.
458 unsigned AliasReg = *Alias;
459 if (Classes[AliasReg]) {
460 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
461 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
462 }
463 }
464
465 // If we're still willing to consider this register, note the reference.
466 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
467 RegRefs.insert(std::make_pair(Reg, &MO));
468 }
469}
470
471void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
472 unsigned Count) {
473 // Update liveness.
474 // Proceding upwards, registers that are defed but not used in this
475 // instruction are now dead.
476 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
477 MachineOperand &MO = MI->getOperand(i);
478 if (!MO.isReg()) continue;
479 unsigned Reg = MO.getReg();
480 if (Reg == 0) continue;
481 if (!MO.isDef()) continue;
482 // Ignore two-addr defs.
Bob Wilsond9df5012009-04-09 17:16:43 +0000483 if (MI->isRegTiedToUseOperand(i)) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000484
485 DefIndices[Reg] = Count;
486 KillIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000487 assert(((KillIndices[Reg] == ~0u) !=
488 (DefIndices[Reg] == ~0u)) &&
489 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000490 Classes[Reg] = 0;
491 RegRefs.erase(Reg);
492 // Repeat, for all subregs.
493 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
494 *Subreg; ++Subreg) {
495 unsigned SubregReg = *Subreg;
496 DefIndices[SubregReg] = Count;
497 KillIndices[SubregReg] = ~0u;
498 Classes[SubregReg] = 0;
499 RegRefs.erase(SubregReg);
500 }
David Goodwin7886cd82009-08-29 00:11:13 +0000501 // Conservatively mark super-registers as unusable.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000502 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
503 *Super; ++Super) {
504 unsigned SuperReg = *Super;
505 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
506 }
507 }
508 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
509 MachineOperand &MO = MI->getOperand(i);
510 if (!MO.isReg()) continue;
511 unsigned Reg = MO.getReg();
512 if (Reg == 0) continue;
513 if (!MO.isUse()) continue;
514
Chris Lattner2a386882009-07-29 21:36:49 +0000515 const TargetRegisterClass *NewRC = 0;
516 if (i < MI->getDesc().getNumOperands())
517 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000518
519 // For now, only allow the register to be changed if its register
520 // class is consistent across all uses.
521 if (!Classes[Reg] && NewRC)
522 Classes[Reg] = NewRC;
523 else if (!NewRC || Classes[Reg] != NewRC)
524 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
525
526 RegRefs.insert(std::make_pair(Reg, &MO));
527
528 // It wasn't previously live but now it is, this is a kill.
529 if (KillIndices[Reg] == ~0u) {
530 KillIndices[Reg] = Count;
531 DefIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000532 assert(((KillIndices[Reg] == ~0u) !=
533 (DefIndices[Reg] == ~0u)) &&
534 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000535 }
536 // Repeat, for all aliases.
537 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
538 unsigned AliasReg = *Alias;
539 if (KillIndices[AliasReg] == ~0u) {
540 KillIndices[AliasReg] = Count;
541 DefIndices[AliasReg] = ~0u;
542 }
543 }
544 }
545}
546
Dan Gohman26255ad2009-08-12 01:33:27 +0000547unsigned
548SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
549 unsigned LastNewReg,
550 const TargetRegisterClass *RC) {
551 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
552 RE = RC->allocation_order_end(MF); R != RE; ++R) {
553 unsigned NewReg = *R;
554 // Don't replace a register with itself.
555 if (NewReg == AntiDepReg) continue;
556 // Don't replace a register with one that was recently used to repair
557 // an anti-dependence with this AntiDepReg, because that would
558 // re-introduce that anti-dependence.
559 if (NewReg == LastNewReg) continue;
560 // If NewReg is dead and NewReg's most recent def is not before
561 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
562 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
563 "Kill and Def maps aren't consistent for AntiDepReg!");
564 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
565 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohmanda277572009-08-12 01:44:20 +0000566 if (KillIndices[NewReg] != ~0u ||
567 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
568 KillIndices[AntiDepReg] > DefIndices[NewReg])
Dan Gohman26255ad2009-08-12 01:33:27 +0000569 continue;
570 return NewReg;
571 }
572
573 // No registers are free and available!
574 return 0;
575}
576
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000577/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
578/// of the ScheduleDAG and break them by renaming registers.
579///
580bool SchedulePostRATDList::BreakAntiDependencies() {
581 // The code below assumes that there is at least one instruction,
582 // so just duck out immediately if the block is empty.
583 if (SUnits.empty()) return false;
584
585 // Find the node at the bottom of the critical path.
586 SUnit *Max = 0;
587 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
588 SUnit *SU = &SUnits[i];
589 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
590 Max = SU;
591 }
592
David Goodwin3a5f0d42009-08-11 01:44:26 +0000593 DEBUG(errs() << "Critical path has total latency "
594 << (Max->getDepth() + Max->Latency) << "\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000595
596 // Track progress along the critical path through the SUnit graph as we walk
597 // the instructions.
598 SUnit *CriticalPathSU = Max;
599 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000600
601 // Consider this pattern:
602 // A = ...
603 // ... = A
604 // A = ...
605 // ... = A
606 // A = ...
607 // ... = A
608 // A = ...
609 // ... = A
610 // There are three anti-dependencies here, and without special care,
611 // we'd break all of them using the same register:
612 // A = ...
613 // ... = A
614 // B = ...
615 // ... = B
616 // B = ...
617 // ... = B
618 // B = ...
619 // ... = B
620 // because at each anti-dependence, B is the first register that
621 // isn't A which is free. This re-introduces anti-dependencies
622 // at all but one of the original anti-dependencies that we were
623 // trying to break. To avoid this, keep track of the most recent
David Goodwinc93d8372009-08-11 17:35:23 +0000624 // register that each register was replaced with, avoid
Dan Gohman21d90032008-11-25 00:52:40 +0000625 // using it to repair an anti-dependence on the same register.
626 // This lets us produce this:
627 // A = ...
628 // ... = A
629 // B = ...
630 // ... = B
631 // C = ...
632 // ... = C
633 // B = ...
634 // ... = B
635 // This still has an anti-dependence on B, but at least it isn't on the
636 // original critical path.
637 //
638 // TODO: If we tracked more than one register here, we could potentially
639 // fix that remaining critical edge too. This is a little more involved,
640 // because unlike the most recent register, less recent registers should
641 // still be considered, though only if no other registers are available.
642 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
643
Dan Gohman21d90032008-11-25 00:52:40 +0000644 // Attempt to break anti-dependence edges on the critical path. Walk the
645 // instructions from the bottom up, tracking information about liveness
646 // as we go to help determine which registers are available.
647 bool Changed = false;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000648 unsigned Count = InsertPosIndex - 1;
649 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000650 I != E; --Count) {
651 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000652
Dan Gohman490b1832008-12-05 05:30:02 +0000653 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
654 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
655 // is left behind appearing to clobber the super-register, while the
656 // subregister needs to remain live. So we just ignore them.
657 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
658 continue;
659
Dan Gohman00dc84a2008-12-16 19:27:52 +0000660 // Check if this instruction has a dependence on the critical path that
661 // is an anti-dependence that we may be able to break. If it is, set
662 // AntiDepReg to the non-zero register associated with the anti-dependence.
663 //
664 // We limit our attention to the critical path as a heuristic to avoid
665 // breaking anti-dependence edges that aren't going to significantly
666 // impact the overall schedule. There are a limited number of registers
667 // and we want to save them for the important edges.
668 //
669 // TODO: Instructions with multiple defs could have multiple
670 // anti-dependencies. The current code here only knows how to break one
671 // edge per instruction. Note that we'd have to be able to break all of
672 // the anti-dependencies in an instruction in order to be effective.
673 unsigned AntiDepReg = 0;
674 if (MI == CriticalPathMI) {
675 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
676 SUnit *NextSU = Edge->getSUnit();
677
678 // Only consider anti-dependence edges.
679 if (Edge->getKind() == SDep::Anti) {
680 AntiDepReg = Edge->getReg();
681 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
682 // Don't break anti-dependencies on non-allocatable registers.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000683 if (!AllocatableSet.test(AntiDepReg))
684 AntiDepReg = 0;
685 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000686 // If the SUnit has other dependencies on the SUnit that it
687 // anti-depends on, don't bother breaking the anti-dependency
688 // since those edges would prevent such units from being
689 // scheduled past each other regardless.
690 //
691 // Also, if there are dependencies on other SUnits with the
692 // same register as the anti-dependency, don't attempt to
693 // break it.
694 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
695 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
696 if (P->getSUnit() == NextSU ?
697 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
698 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
699 AntiDepReg = 0;
700 break;
701 }
702 }
703 }
704 CriticalPathSU = NextSU;
705 CriticalPathMI = CriticalPathSU->getInstr();
706 } else {
707 // We've reached the end of the critical path.
708 CriticalPathSU = 0;
709 CriticalPathMI = 0;
710 }
711 }
Dan Gohman21d90032008-11-25 00:52:40 +0000712
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000713 PrescanInstruction(MI);
714
715 // If this instruction has a use of AntiDepReg, breaking it
716 // is invalid.
Dan Gohman21d90032008-11-25 00:52:40 +0000717 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
718 MachineOperand &MO = MI->getOperand(i);
719 if (!MO.isReg()) continue;
720 unsigned Reg = MO.getReg();
721 if (Reg == 0) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000722 if (MO.isUse() && AntiDepReg == Reg) {
Dan Gohman21d90032008-11-25 00:52:40 +0000723 AntiDepReg = 0;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000724 break;
Dan Gohman21d90032008-11-25 00:52:40 +0000725 }
Dan Gohman21d90032008-11-25 00:52:40 +0000726 }
727
728 // Determine AntiDepReg's register class, if it is live and is
729 // consistently used within a single class.
730 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000731 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000732 "Register should be live if it's causing an anti-dependence!");
733 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
734 AntiDepReg = 0;
735
736 // Look for a suitable register to use to break the anti-depenence.
737 //
738 // TODO: Instead of picking the first free register, consider which might
739 // be the best.
740 if (AntiDepReg != 0) {
Dan Gohman26255ad2009-08-12 01:33:27 +0000741 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
742 LastNewReg[AntiDepReg],
743 RC)) {
744 DEBUG(errs() << "Breaking anti-dependence edge on "
745 << TRI->getName(AntiDepReg)
746 << " with " << RegRefs.count(AntiDepReg) << " references"
747 << " using " << TRI->getName(NewReg) << "!\n");
Dan Gohman21d90032008-11-25 00:52:40 +0000748
Dan Gohman26255ad2009-08-12 01:33:27 +0000749 // Update the references to the old register to refer to the new
750 // register.
751 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
752 std::multimap<unsigned, MachineOperand *>::iterator>
753 Range = RegRefs.equal_range(AntiDepReg);
754 for (std::multimap<unsigned, MachineOperand *>::iterator
755 Q = Range.first, QE = Range.second; Q != QE; ++Q)
756 Q->second->setReg(NewReg);
Dan Gohman21d90032008-11-25 00:52:40 +0000757
Dan Gohman26255ad2009-08-12 01:33:27 +0000758 // We just went back in time and modified history; the
759 // liveness information for the anti-depenence reg is now
760 // inconsistent. Set the state as if it were dead.
761 Classes[NewReg] = Classes[AntiDepReg];
762 DefIndices[NewReg] = DefIndices[AntiDepReg];
763 KillIndices[NewReg] = KillIndices[AntiDepReg];
764 assert(((KillIndices[NewReg] == ~0u) !=
765 (DefIndices[NewReg] == ~0u)) &&
766 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000767
Dan Gohman26255ad2009-08-12 01:33:27 +0000768 Classes[AntiDepReg] = 0;
769 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
770 KillIndices[AntiDepReg] = ~0u;
771 assert(((KillIndices[AntiDepReg] == ~0u) !=
772 (DefIndices[AntiDepReg] == ~0u)) &&
773 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000774
Dan Gohman26255ad2009-08-12 01:33:27 +0000775 RegRefs.erase(AntiDepReg);
776 Changed = true;
777 LastNewReg[AntiDepReg] = NewReg;
Dan Gohman21d90032008-11-25 00:52:40 +0000778 }
779 }
780
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000781 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000782 }
Dan Gohman21d90032008-11-25 00:52:40 +0000783
784 return Changed;
785}
786
David Goodwin5e411782009-09-03 22:15:25 +0000787/// StartBlockForKills - Initialize register live-range state for updating kills
788///
789void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
790 // Initialize the indices to indicate that no registers are live.
791 std::fill(KillIndices, array_endof(KillIndices), ~0u);
792
793 // Determine the live-out physregs for this block.
794 if (!BB->empty() && BB->back().getDesc().isReturn()) {
795 // In a return block, examine the function live-out regs.
796 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
797 E = MRI.liveout_end(); I != E; ++I) {
798 unsigned Reg = *I;
799 KillIndices[Reg] = BB->size();
800 // Repeat, for all subregs.
801 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
802 *Subreg; ++Subreg) {
803 KillIndices[*Subreg] = BB->size();
804 }
805 }
806 }
807 else {
808 // In a non-return block, examine the live-in regs of all successors.
809 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
810 SE = BB->succ_end(); SI != SE; ++SI) {
811 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
812 E = (*SI)->livein_end(); I != E; ++I) {
813 unsigned Reg = *I;
814 KillIndices[Reg] = BB->size();
815 // Repeat, for all subregs.
816 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
817 *Subreg; ++Subreg) {
818 KillIndices[*Subreg] = BB->size();
819 }
820 }
821 }
822 }
823}
824
David Goodwin88a589c2009-08-25 17:03:05 +0000825/// FixupKills - Fix the register kill flags, they may have been made
826/// incorrect by instruction reordering.
827///
828void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
829 DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
830
831 std::set<unsigned> killedRegs;
832 BitVector ReservedRegs = TRI->getReservedRegs(MF);
David Goodwin5e411782009-09-03 22:15:25 +0000833
834 StartBlockForKills(MBB);
David Goodwin7886cd82009-08-29 00:11:13 +0000835
836 // Examine block from end to start...
David Goodwin88a589c2009-08-25 17:03:05 +0000837 unsigned Count = MBB->size();
838 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
839 I != E; --Count) {
840 MachineInstr *MI = --I;
841
David Goodwin7886cd82009-08-29 00:11:13 +0000842 // Update liveness. Registers that are defed but not used in this
843 // instruction are now dead. Mark register and all subregs as they
844 // are completely defined.
845 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
846 MachineOperand &MO = MI->getOperand(i);
847 if (!MO.isReg()) continue;
848 unsigned Reg = MO.getReg();
849 if (Reg == 0) continue;
850 if (!MO.isDef()) continue;
851 // Ignore two-addr defs.
852 if (MI->isRegTiedToUseOperand(i)) continue;
853
David Goodwin7886cd82009-08-29 00:11:13 +0000854 KillIndices[Reg] = ~0u;
855
856 // Repeat for all subregs.
857 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
858 *Subreg; ++Subreg) {
859 KillIndices[*Subreg] = ~0u;
860 }
861 }
David Goodwin88a589c2009-08-25 17:03:05 +0000862
863 // Examine all used registers and set kill flag. When a register
864 // is used multiple times we only set the kill flag on the first
865 // use.
866 killedRegs.clear();
867 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
868 MachineOperand &MO = MI->getOperand(i);
869 if (!MO.isReg() || !MO.isUse()) continue;
870 unsigned Reg = MO.getReg();
871 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
872
David Goodwin7886cd82009-08-29 00:11:13 +0000873 bool kill = false;
874 if (killedRegs.find(Reg) == killedRegs.end()) {
875 kill = true;
876 // A register is not killed if any subregs are live...
877 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
878 *Subreg; ++Subreg) {
879 if (KillIndices[*Subreg] != ~0u) {
880 kill = false;
881 break;
882 }
883 }
884
885 // If subreg is not live, then register is killed if it became
886 // live in this instruction
887 if (kill)
888 kill = (KillIndices[Reg] == ~0u);
889 }
890
David Goodwin88a589c2009-08-25 17:03:05 +0000891 if (MO.isKill() != kill) {
892 MO.setIsKill(kill);
893 DEBUG(errs() << "Fixed " << MO << " in ");
894 DEBUG(MI->dump());
895 }
David Goodwin7886cd82009-08-29 00:11:13 +0000896
David Goodwin88a589c2009-08-25 17:03:05 +0000897 killedRegs.insert(Reg);
898 }
David Goodwin7886cd82009-08-29 00:11:13 +0000899
David Goodwina3251db2009-08-31 20:47:02 +0000900 // Mark any used register (that is not using undef) and subregs as
901 // now live...
David Goodwin7886cd82009-08-29 00:11:13 +0000902 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
903 MachineOperand &MO = MI->getOperand(i);
David Goodwina3251db2009-08-31 20:47:02 +0000904 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
David Goodwin7886cd82009-08-29 00:11:13 +0000905 unsigned Reg = MO.getReg();
906 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
907
David Goodwin7886cd82009-08-29 00:11:13 +0000908 KillIndices[Reg] = Count;
909
910 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
911 *Subreg; ++Subreg) {
912 KillIndices[*Subreg] = Count;
913 }
914 }
David Goodwin88a589c2009-08-25 17:03:05 +0000915 }
916}
917
Dan Gohman343f0c02008-11-19 23:18:57 +0000918//===----------------------------------------------------------------------===//
919// Top-Down Scheduling
920//===----------------------------------------------------------------------===//
921
922/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
923/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000924void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
925 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000926 --SuccSU->NumPredsLeft;
927
928#ifndef NDEBUG
929 if (SuccSU->NumPredsLeft < 0) {
Chris Lattner103289e2009-08-23 07:19:13 +0000930 errs() << "*** Scheduling failed! ***\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000931 SuccSU->dump(this);
Chris Lattner103289e2009-08-23 07:19:13 +0000932 errs() << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000933 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +0000934 }
935#endif
936
937 // Compute how many cycles it will be before this actually becomes
938 // available. This is the max of the start time of all predecessors plus
939 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000940 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000941
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000942 // If all the node's predecessors are scheduled, this node is ready
943 // to be scheduled. Ignore the special ExitSU node.
944 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000945 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000946}
947
948/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
949void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
950 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
951 I != E; ++I)
952 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000953}
954
955/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
956/// count of its successors. If a successor pending count is zero, add it to
957/// the Available queue.
958void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000959 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman343f0c02008-11-19 23:18:57 +0000960 DEBUG(SU->dump(this));
961
962 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000963 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
964 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000965
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000966 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000967 SU->isScheduled = true;
968 AvailableQueue.ScheduledNode(SU);
969}
970
971/// ListScheduleTopDown - The main loop of list scheduling for top-down
972/// schedulers.
973void SchedulePostRATDList::ListScheduleTopDown() {
974 unsigned CurCycle = 0;
975
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000976 // Release any successors of the special Entry node.
977 ReleaseSuccessors(&EntrySU);
978
Dan Gohman343f0c02008-11-19 23:18:57 +0000979 // All leaves to Available queue.
980 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
981 // It is available if it has no predecessors.
982 if (SUnits[i].Preds.empty()) {
983 AvailableQueue.push(&SUnits[i]);
984 SUnits[i].isAvailable = true;
985 }
986 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000987
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000988 // In any cycle where we can't schedule any instructions, we must
989 // stall or emit a noop, depending on the target.
Benjamin Kramerbe441c02009-09-06 12:10:17 +0000990 bool CycleHasInsts = false;
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000991
Dan Gohman343f0c02008-11-19 23:18:57 +0000992 // While Available queue is not empty, grab the node with the highest
993 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +0000994 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +0000995 Sequence.reserve(SUnits.size());
996 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
997 // Check to see if any of the pending instructions are ready to issue. If
998 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000999 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +00001000 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +00001001 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +00001002 AvailableQueue.push(PendingQueue[i]);
1003 PendingQueue[i]->isAvailable = true;
1004 PendingQueue[i] = PendingQueue.back();
1005 PendingQueue.pop_back();
1006 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +00001007 } else if (PendingQueue[i]->getDepth() < MinDepth)
1008 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +00001009 }
David Goodwinc93d8372009-08-11 17:35:23 +00001010
David Goodwin7cd01182009-08-11 17:56:42 +00001011 DEBUG(errs() << "\n*** Examining Available\n";
1012 LatencyPriorityQueue q = AvailableQueue;
1013 while (!q.empty()) {
1014 SUnit *su = q.pop();
1015 errs() << "Height " << su->getHeight() << ": ";
1016 su->dump(this);
1017 });
David Goodwinc93d8372009-08-11 17:35:23 +00001018
Dan Gohman2836c282009-01-16 01:33:36 +00001019 SUnit *FoundSUnit = 0;
1020
1021 bool HasNoopHazards = false;
1022 while (!AvailableQueue.empty()) {
1023 SUnit *CurSUnit = AvailableQueue.pop();
1024
1025 ScheduleHazardRecognizer::HazardType HT =
1026 HazardRec->getHazardType(CurSUnit);
1027 if (HT == ScheduleHazardRecognizer::NoHazard) {
1028 FoundSUnit = CurSUnit;
1029 break;
1030 }
1031
1032 // Remember if this is a noop hazard.
1033 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
1034
1035 NotReady.push_back(CurSUnit);
1036 }
1037
1038 // Add the nodes that aren't ready back onto the available list.
1039 if (!NotReady.empty()) {
1040 AvailableQueue.push_all(NotReady);
1041 NotReady.clear();
1042 }
1043
Dan Gohman343f0c02008-11-19 23:18:57 +00001044 // If we found a node to schedule, do it now.
1045 if (FoundSUnit) {
1046 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +00001047 HazardRec->EmitInstruction(FoundSUnit);
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001048 CycleHasInsts = true;
Dan Gohman343f0c02008-11-19 23:18:57 +00001049
David Goodwind94a4e52009-08-10 15:55:25 +00001050 // If we are using the target-specific hazards, then don't
1051 // advance the cycle time just because we schedule a node. If
1052 // the target allows it we can schedule multiple nodes in the
1053 // same cycle.
1054 if (!EnablePostRAHazardAvoidance) {
1055 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
1056 ++CurCycle;
1057 }
Dan Gohman2836c282009-01-16 01:33:36 +00001058 } else {
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001059 if (CycleHasInsts) {
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001060 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
1061 HazardRec->AdvanceCycle();
1062 } else if (!HasNoopHazards) {
1063 // Otherwise, we have a pipeline stall, but no other problem,
1064 // just advance the current cycle and try again.
1065 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
1066 HazardRec->AdvanceCycle();
1067 ++NumStalls;
1068 } else {
1069 // Otherwise, we have no instructions to issue and we have instructions
1070 // that will fault if we don't do this right. This is the case for
1071 // processors without pipeline interlocks and other cases.
1072 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
1073 HazardRec->EmitNoop();
1074 Sequence.push_back(0); // NULL here means noop
1075 ++NumNoops;
1076 }
1077
Dan Gohman2836c282009-01-16 01:33:36 +00001078 ++CurCycle;
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001079 CycleHasInsts = false;
Dan Gohman343f0c02008-11-19 23:18:57 +00001080 }
1081 }
1082
1083#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +00001084 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +00001085#endif
1086}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00001087
1088//===----------------------------------------------------------------------===//
1089// Public Constructor Functions
1090//===----------------------------------------------------------------------===//
1091
1092FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +00001093 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00001094}