blob: 42954eac4f6d7c223349a9b17f5015113f8ba024 [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"
David Goodwin0dad89f2009-09-30 00:10:16 +000037#include "llvm/Target/TargetSubtarget.h"
Chris Lattner459525d2008-01-14 19:00:06 +000038#include "llvm/Support/Compiler.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000039#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000040#include "llvm/Support/ErrorHandling.h"
David Goodwin3a5f0d42009-08-11 01:44:26 +000041#include "llvm/Support/raw_ostream.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000042#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000043#include <map>
David Goodwin88a589c2009-08-25 17:03:05 +000044#include <set>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000045using namespace llvm;
46
Dan Gohman2836c282009-01-16 01:33:36 +000047STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000048STATISTIC(NumStalls, "Number of pipeline stalls");
49
Dan Gohman21d90032008-11-25 00:52:40 +000050static cl::opt<bool>
51EnableAntiDepBreaking("break-anti-dependencies",
Dan Gohman00dc84a2008-12-16 19:27:52 +000052 cl::desc("Break post-RA scheduling anti-dependencies"),
53 cl::init(true), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000054
Dan Gohman2836c282009-01-16 01:33:36 +000055static cl::opt<bool>
56EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwind94a4e52009-08-10 15:55:25 +000057 cl::desc("Enable exact hazard avoidance"),
David Goodwin5e411782009-09-03 22:15:25 +000058 cl::init(true), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000059
David Goodwin1f152282009-09-01 18:34:03 +000060// If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
61static cl::opt<int>
62DebugDiv("postra-sched-debugdiv",
63 cl::desc("Debug control MBBs that are scheduled"),
64 cl::init(0), cl::Hidden);
65static cl::opt<int>
66DebugMod("postra-sched-debugmod",
67 cl::desc("Debug control MBBs that are scheduled"),
68 cl::init(0), cl::Hidden);
69
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000070namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000071 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000072 public:
73 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000074 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000075
Dan Gohman3f237442008-12-16 03:25:46 +000076 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000077 AU.setPreservesCFG();
Dan Gohman3f237442008-12-16 03:25:46 +000078 AU.addRequired<MachineDominatorTree>();
79 AU.addPreserved<MachineDominatorTree>();
80 AU.addRequired<MachineLoopInfo>();
81 AU.addPreserved<MachineLoopInfo>();
82 MachineFunctionPass::getAnalysisUsage(AU);
83 }
84
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000085 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000086 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000087 }
88
89 bool runOnMachineFunction(MachineFunction &Fn);
90 };
Dan Gohman343f0c02008-11-19 23:18:57 +000091 char PostRAScheduler::ID = 0;
92
93 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000094 /// AvailableQueue - The priority queue to use for the available SUnits.
95 ///
96 LatencyPriorityQueue AvailableQueue;
97
98 /// PendingQueue - This contains all of the instructions whose operands have
99 /// been issued, but their results are not ready yet (due to the latency of
100 /// the operation). Once the operands becomes available, the instruction is
101 /// added to the AvailableQueue.
102 std::vector<SUnit*> PendingQueue;
103
Dan Gohman21d90032008-11-25 00:52:40 +0000104 /// Topo - A topological ordering for SUnits.
105 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +0000106
Dan Gohman79ce2762009-01-15 19:20:50 +0000107 /// AllocatableSet - The set of allocatable registers.
108 /// We'll be ignoring anti-dependencies on non-allocatable registers,
109 /// because they may not be safe to break.
110 const BitVector AllocatableSet;
111
Dan Gohman2836c282009-01-16 01:33:36 +0000112 /// HazardRec - The hazard recognizer to use.
113 ScheduleHazardRecognizer *HazardRec;
114
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000115 /// Classes - For live regs that are only used in one register class in a
116 /// live range, the register class. If the register is not live, the
117 /// corresponding value is null. If the register is live but used in
118 /// multiple register classes, the corresponding value is -1 casted to a
119 /// pointer.
120 const TargetRegisterClass *
121 Classes[TargetRegisterInfo::FirstVirtualRegister];
122
123 /// RegRegs - Map registers to all their references within a live range.
124 std::multimap<unsigned, MachineOperand *> RegRefs;
125
126 /// The index of the most recent kill (proceding bottom-up), or ~0u if
127 /// the register is not live.
128 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
129
130 /// The index of the most recent complete def (proceding bottom up), or ~0u
131 /// if the register is live.
132 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
133
Dan Gohman21d90032008-11-25 00:52:40 +0000134 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000135 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000136 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000137 const MachineDominatorTree &MDT,
138 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000139 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000140 AllocatableSet(TRI->getAllocatableSet(MF)),
141 HazardRec(HR) {}
142
143 ~SchedulePostRATDList() {
144 delete HazardRec;
145 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000146
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000147 /// StartBlock - Initialize register live-range state for scheduling in
148 /// this block.
149 ///
150 void StartBlock(MachineBasicBlock *BB);
151
152 /// Schedule - Schedule the instruction range using list scheduling.
153 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000154 void Schedule();
David Goodwin88a589c2009-08-25 17:03:05 +0000155
156 /// FixupKills - Fix register kill flags that have been made
157 /// invalid due to scheduling
158 ///
159 void FixupKills(MachineBasicBlock *MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000160
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000161 /// Observe - Update liveness information to account for the current
162 /// instruction, which will not be scheduled.
163 ///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000164 void Observe(MachineInstr *MI, unsigned Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000165
166 /// FinishBlock - Clean up register live-range state.
167 ///
168 void FinishBlock();
169
Dan Gohman343f0c02008-11-19 23:18:57 +0000170 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000171 void PrescanInstruction(MachineInstr *MI);
172 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000173 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000174 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000175 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
176 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000177 bool BreakAntiDependencies();
Dan Gohman26255ad2009-08-12 01:33:27 +0000178 unsigned findSuitableFreeRegister(unsigned AntiDepReg,
179 unsigned LastNewReg,
180 const TargetRegisterClass *);
David Goodwin5e411782009-09-03 22:15:25 +0000181 void StartBlockForKills(MachineBasicBlock *BB);
David Goodwin8f909342009-09-23 16:35:25 +0000182
183 // ToggleKillFlag - Toggle a register operand kill flag. Other
184 // adjustments may be made to the instruction if necessary. Return
185 // true if the operand has been deleted, false if not.
186 bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
Dan Gohman343f0c02008-11-19 23:18:57 +0000187 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000188}
189
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000190/// isSchedulingBoundary - Test if the given instruction should be
191/// considered a scheduling boundary. This primarily includes labels
192/// and terminators.
193///
194static bool isSchedulingBoundary(const MachineInstr *MI,
195 const MachineFunction &MF) {
196 // Terminators and labels can't be scheduled around.
197 if (MI->getDesc().isTerminator() || MI->isLabel())
198 return true;
199
Dan Gohmanbed353d2009-02-10 23:29:38 +0000200 // Don't attempt to schedule around any instruction that modifies
201 // a stack-oriented pointer, as it's unlikely to be profitable. This
202 // saves compile time, because it doesn't require every single
203 // stack slot reference to depend on the instruction that does the
204 // modification.
205 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
206 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
207 return true;
208
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000209 return false;
210}
211
Dan Gohman343f0c02008-11-19 23:18:57 +0000212bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
David Goodwin0dad89f2009-09-30 00:10:16 +0000213 // Check that post-RA scheduling is enabled for this function
214 const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
215 if (!ST.enablePostRAScheduler())
216 return true;
217
David Goodwin3a5f0d42009-08-11 01:44:26 +0000218 DEBUG(errs() << "PostRAScheduler\n");
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000219
Dan Gohman3f237442008-12-16 03:25:46 +0000220 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
221 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000222 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000223 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000224 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
225 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000226
Dan Gohman2836c282009-01-16 01:33:36 +0000227 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000228
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000229 // Loop over all of the basic blocks
230 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000231 MBB != MBBe; ++MBB) {
David Goodwin1f152282009-09-01 18:34:03 +0000232#ifndef NDEBUG
233 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
234 if (DebugDiv > 0) {
235 static int bbcnt = 0;
236 if (bbcnt++ % DebugDiv != DebugMod)
237 continue;
238 errs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
239 ":MBB ID#" << MBB->getNumber() << " ***\n";
240 }
241#endif
242
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000243 // Initialize register live-range state for scheduling in this block.
244 Scheduler.StartBlock(MBB);
245
Dan Gohmanf7119392009-01-16 22:10:20 +0000246 // Schedule each sequence of instructions not interrupted by a label
247 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000248 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000249 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000250 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
251 MachineInstr *MI = prior(I);
252 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000253 Scheduler.Run(MBB, I, Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000254 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000255 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000256 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000257 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000258 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000259 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000260 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000261 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000262 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000263 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000264 "Instruction count mismatch!");
265 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000266 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000267
268 // Clean up register live-range state.
269 Scheduler.FinishBlock();
David Goodwin88a589c2009-08-25 17:03:05 +0000270
David Goodwin5e411782009-09-03 22:15:25 +0000271 // Update register kills
David Goodwin88a589c2009-08-25 17:03:05 +0000272 Scheduler.FixupKills(MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000273 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000274
275 return true;
276}
277
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000278/// StartBlock - Initialize register live-range state for scheduling in
279/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000280///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000281void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
282 // Call the superclass.
283 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000284
David Goodwind94a4e52009-08-10 15:55:25 +0000285 // Reset the hazard recognizer.
286 HazardRec->Reset();
287
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000288 // Clear out the register class data.
289 std::fill(Classes, array_endof(Classes),
290 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000291
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000292 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000293 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000294 std::fill(DefIndices, array_endof(DefIndices), BB->size());
295
296 // Determine the live-out physregs for this block.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000297 if (!BB->empty() && BB->back().getDesc().isReturn())
Dan Gohman21d90032008-11-25 00:52:40 +0000298 // In a return block, examine the function live-out regs.
299 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
300 E = MRI.liveout_end(); I != E; ++I) {
301 unsigned Reg = *I;
302 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
303 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000304 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000305 // Repeat, for all aliases.
306 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
307 unsigned AliasReg = *Alias;
308 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
309 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000310 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000311 }
312 }
313 else
314 // In a non-return block, examine the live-in regs of all successors.
315 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
Dan Gohman47ac0f02009-02-11 04:27:20 +0000316 SE = BB->succ_end(); SI != SE; ++SI)
Dan Gohman21d90032008-11-25 00:52:40 +0000317 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
318 E = (*SI)->livein_end(); I != E; ++I) {
319 unsigned Reg = *I;
320 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
321 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000322 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000323 // 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();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000328 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000329 }
330 }
331
David Goodwin5e411782009-09-03 22:15:25 +0000332 // Consider callee-saved registers as live-out, since we're running after
333 // prologue/epilogue insertion so there's no way to add additional
334 // saved registers.
335 //
336 // TODO: there is a new method
337 // MachineFrameInfo::getPristineRegs(MBB). It gives you a list of
338 // CSRs that have not been saved when entering the MBB. The
339 // remaining CSRs have been saved and can be treated like call
340 // clobbered registers.
341 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
342 unsigned Reg = *I;
343 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
344 KillIndices[Reg] = BB->size();
345 DefIndices[Reg] = ~0u;
346 // Repeat, for all aliases.
347 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
348 unsigned AliasReg = *Alias;
349 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
350 KillIndices[AliasReg] = BB->size();
351 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000352 }
353 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000354}
355
356/// Schedule - Schedule the instruction range using list scheduling.
357///
358void SchedulePostRATDList::Schedule() {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000359 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000360
361 // Build the scheduling graph.
362 BuildSchedGraph();
363
364 if (EnableAntiDepBreaking) {
365 if (BreakAntiDependencies()) {
366 // We made changes. Update the dependency graph.
367 // Theoretically we could update the graph in place:
368 // When a live range is changed to use a different register, remove
369 // the def's anti-dependence *and* output-dependence edges due to
370 // that register, and add new anti-dependence and output-dependence
371 // edges based on the next live range of the register.
372 SUnits.clear();
373 EntrySU = SUnit();
374 ExitSU = SUnit();
375 BuildSchedGraph();
376 }
377 }
378
David Goodwind94a4e52009-08-10 15:55:25 +0000379 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
380 SUnits[su].dumpAll(this));
381
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000382 AvailableQueue.initNodes(SUnits);
383
384 ListScheduleTopDown();
385
386 AvailableQueue.releaseState();
387}
388
389/// Observe - Update liveness information to account for the current
390/// instruction, which will not be scheduled.
391///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000392void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000393 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
394
395 // Any register which was defined within the previous scheduling region
396 // may have been rescheduled and its lifetime may overlap with registers
397 // in ways not reflected in our current liveness state. For each such
398 // register, adjust the liveness state to be conservatively correct.
399 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
400 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
401 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
402 // Mark this register to be non-renamable.
403 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
404 // Move the def index to the end of the previous region, to reflect
405 // that the def could theoretically have been scheduled at the end.
406 DefIndices[Reg] = InsertPosIndex;
407 }
408
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000409 PrescanInstruction(MI);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000410 ScanInstruction(MI, Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000411}
412
413/// FinishBlock - Clean up register live-range state.
414///
415void SchedulePostRATDList::FinishBlock() {
416 RegRefs.clear();
417
418 // Call the superclass.
419 ScheduleDAGInstrs::FinishBlock();
420}
421
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000422/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
423/// critical path.
424static SDep *CriticalPathStep(SUnit *SU) {
425 SDep *Next = 0;
426 unsigned NextDepth = 0;
427 // Find the predecessor edge with the greatest depth.
428 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
429 P != PE; ++P) {
430 SUnit *PredSU = P->getSUnit();
431 unsigned PredLatency = P->getLatency();
432 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
433 // In the case of a latency tie, prefer an anti-dependency edge over
434 // other types of edges.
435 if (NextDepth < PredTotalLatency ||
436 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
437 NextDepth = PredTotalLatency;
438 Next = &*P;
439 }
440 }
441 return Next;
442}
443
444void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
445 // Scan the register operands for this instruction and update
446 // Classes and RegRefs.
447 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
448 MachineOperand &MO = MI->getOperand(i);
449 if (!MO.isReg()) continue;
450 unsigned Reg = MO.getReg();
451 if (Reg == 0) continue;
Chris Lattner2a386882009-07-29 21:36:49 +0000452 const TargetRegisterClass *NewRC = 0;
453
454 if (i < MI->getDesc().getNumOperands())
455 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000456
457 // For now, only allow the register to be changed if its register
458 // class is consistent across all uses.
459 if (!Classes[Reg] && NewRC)
460 Classes[Reg] = NewRC;
461 else if (!NewRC || Classes[Reg] != NewRC)
462 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
463
464 // Now check for aliases.
465 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
466 // If an alias of the reg is used during the live range, give up.
467 // Note that this allows us to skip checking if AntiDepReg
468 // overlaps with any of the aliases, among other things.
469 unsigned AliasReg = *Alias;
470 if (Classes[AliasReg]) {
471 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
472 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
473 }
474 }
475
476 // If we're still willing to consider this register, note the reference.
477 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
478 RegRefs.insert(std::make_pair(Reg, &MO));
479 }
480}
481
482void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
483 unsigned Count) {
484 // Update liveness.
485 // Proceding upwards, registers that are defed but not used in this
486 // instruction are now dead.
487 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
488 MachineOperand &MO = MI->getOperand(i);
489 if (!MO.isReg()) continue;
490 unsigned Reg = MO.getReg();
491 if (Reg == 0) continue;
492 if (!MO.isDef()) continue;
493 // Ignore two-addr defs.
Bob Wilsond9df5012009-04-09 17:16:43 +0000494 if (MI->isRegTiedToUseOperand(i)) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000495
496 DefIndices[Reg] = Count;
497 KillIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000498 assert(((KillIndices[Reg] == ~0u) !=
499 (DefIndices[Reg] == ~0u)) &&
500 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000501 Classes[Reg] = 0;
502 RegRefs.erase(Reg);
503 // Repeat, for all subregs.
504 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
505 *Subreg; ++Subreg) {
506 unsigned SubregReg = *Subreg;
507 DefIndices[SubregReg] = Count;
508 KillIndices[SubregReg] = ~0u;
509 Classes[SubregReg] = 0;
510 RegRefs.erase(SubregReg);
511 }
David Goodwin7886cd82009-08-29 00:11:13 +0000512 // Conservatively mark super-registers as unusable.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000513 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
514 *Super; ++Super) {
515 unsigned SuperReg = *Super;
516 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
517 }
518 }
519 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
520 MachineOperand &MO = MI->getOperand(i);
521 if (!MO.isReg()) continue;
522 unsigned Reg = MO.getReg();
523 if (Reg == 0) continue;
524 if (!MO.isUse()) continue;
525
Chris Lattner2a386882009-07-29 21:36:49 +0000526 const TargetRegisterClass *NewRC = 0;
527 if (i < MI->getDesc().getNumOperands())
528 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000529
530 // For now, only allow the register to be changed if its register
531 // class is consistent across all uses.
532 if (!Classes[Reg] && NewRC)
533 Classes[Reg] = NewRC;
534 else if (!NewRC || Classes[Reg] != NewRC)
535 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
536
537 RegRefs.insert(std::make_pair(Reg, &MO));
538
539 // It wasn't previously live but now it is, this is a kill.
540 if (KillIndices[Reg] == ~0u) {
541 KillIndices[Reg] = Count;
542 DefIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000543 assert(((KillIndices[Reg] == ~0u) !=
544 (DefIndices[Reg] == ~0u)) &&
545 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000546 }
547 // Repeat, for all aliases.
548 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
549 unsigned AliasReg = *Alias;
550 if (KillIndices[AliasReg] == ~0u) {
551 KillIndices[AliasReg] = Count;
552 DefIndices[AliasReg] = ~0u;
553 }
554 }
555 }
556}
557
Dan Gohman26255ad2009-08-12 01:33:27 +0000558unsigned
559SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
560 unsigned LastNewReg,
561 const TargetRegisterClass *RC) {
562 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
563 RE = RC->allocation_order_end(MF); R != RE; ++R) {
564 unsigned NewReg = *R;
565 // Don't replace a register with itself.
566 if (NewReg == AntiDepReg) continue;
567 // Don't replace a register with one that was recently used to repair
568 // an anti-dependence with this AntiDepReg, because that would
569 // re-introduce that anti-dependence.
570 if (NewReg == LastNewReg) continue;
571 // If NewReg is dead and NewReg's most recent def is not before
572 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
573 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
574 "Kill and Def maps aren't consistent for AntiDepReg!");
575 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
576 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohmanda277572009-08-12 01:44:20 +0000577 if (KillIndices[NewReg] != ~0u ||
578 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
579 KillIndices[AntiDepReg] > DefIndices[NewReg])
Dan Gohman26255ad2009-08-12 01:33:27 +0000580 continue;
581 return NewReg;
582 }
583
584 // No registers are free and available!
585 return 0;
586}
587
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000588/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
589/// of the ScheduleDAG and break them by renaming registers.
590///
591bool SchedulePostRATDList::BreakAntiDependencies() {
592 // The code below assumes that there is at least one instruction,
593 // so just duck out immediately if the block is empty.
594 if (SUnits.empty()) return false;
595
596 // Find the node at the bottom of the critical path.
597 SUnit *Max = 0;
598 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
599 SUnit *SU = &SUnits[i];
600 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
601 Max = SU;
602 }
603
David Goodwin3a5f0d42009-08-11 01:44:26 +0000604 DEBUG(errs() << "Critical path has total latency "
605 << (Max->getDepth() + Max->Latency) << "\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000606
607 // Track progress along the critical path through the SUnit graph as we walk
608 // the instructions.
609 SUnit *CriticalPathSU = Max;
610 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000611
612 // Consider this pattern:
613 // A = ...
614 // ... = A
615 // A = ...
616 // ... = A
617 // A = ...
618 // ... = A
619 // A = ...
620 // ... = A
621 // There are three anti-dependencies here, and without special care,
622 // we'd break all of them using the same register:
623 // A = ...
624 // ... = A
625 // B = ...
626 // ... = B
627 // B = ...
628 // ... = B
629 // B = ...
630 // ... = B
631 // because at each anti-dependence, B is the first register that
632 // isn't A which is free. This re-introduces anti-dependencies
633 // at all but one of the original anti-dependencies that we were
634 // trying to break. To avoid this, keep track of the most recent
David Goodwinc93d8372009-08-11 17:35:23 +0000635 // register that each register was replaced with, avoid
Dan Gohman21d90032008-11-25 00:52:40 +0000636 // using it to repair an anti-dependence on the same register.
637 // This lets us produce this:
638 // A = ...
639 // ... = A
640 // B = ...
641 // ... = B
642 // C = ...
643 // ... = C
644 // B = ...
645 // ... = B
646 // This still has an anti-dependence on B, but at least it isn't on the
647 // original critical path.
648 //
649 // TODO: If we tracked more than one register here, we could potentially
650 // fix that remaining critical edge too. This is a little more involved,
651 // because unlike the most recent register, less recent registers should
652 // still be considered, though only if no other registers are available.
653 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
654
Dan Gohman21d90032008-11-25 00:52:40 +0000655 // Attempt to break anti-dependence edges on the critical path. Walk the
656 // instructions from the bottom up, tracking information about liveness
657 // as we go to help determine which registers are available.
658 bool Changed = false;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000659 unsigned Count = InsertPosIndex - 1;
660 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000661 I != E; --Count) {
662 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000663
Jakob Stoklund Olesen544df362009-09-28 20:32:46 +0000664 // After regalloc, KILL instructions aren't safe to treat as
665 // dependence-breaking. In the case of an INSERT_SUBREG, the KILL
Dan Gohman490b1832008-12-05 05:30:02 +0000666 // is left behind appearing to clobber the super-register, while the
667 // subregister needs to remain live. So we just ignore them.
Jakob Stoklund Olesen544df362009-09-28 20:32:46 +0000668 if (MI->getOpcode() == TargetInstrInfo::KILL)
Dan Gohman490b1832008-12-05 05:30:02 +0000669 continue;
670
Dan Gohman00dc84a2008-12-16 19:27:52 +0000671 // Check if this instruction has a dependence on the critical path that
672 // is an anti-dependence that we may be able to break. If it is, set
673 // AntiDepReg to the non-zero register associated with the anti-dependence.
674 //
675 // We limit our attention to the critical path as a heuristic to avoid
676 // breaking anti-dependence edges that aren't going to significantly
677 // impact the overall schedule. There are a limited number of registers
678 // and we want to save them for the important edges.
679 //
680 // TODO: Instructions with multiple defs could have multiple
681 // anti-dependencies. The current code here only knows how to break one
682 // edge per instruction. Note that we'd have to be able to break all of
683 // the anti-dependencies in an instruction in order to be effective.
684 unsigned AntiDepReg = 0;
685 if (MI == CriticalPathMI) {
686 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
687 SUnit *NextSU = Edge->getSUnit();
688
689 // Only consider anti-dependence edges.
690 if (Edge->getKind() == SDep::Anti) {
691 AntiDepReg = Edge->getReg();
692 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
693 // Don't break anti-dependencies on non-allocatable registers.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000694 if (!AllocatableSet.test(AntiDepReg))
695 AntiDepReg = 0;
696 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000697 // If the SUnit has other dependencies on the SUnit that it
698 // anti-depends on, don't bother breaking the anti-dependency
699 // since those edges would prevent such units from being
700 // scheduled past each other regardless.
701 //
702 // Also, if there are dependencies on other SUnits with the
703 // same register as the anti-dependency, don't attempt to
704 // break it.
705 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
706 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
707 if (P->getSUnit() == NextSU ?
708 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
709 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
710 AntiDepReg = 0;
711 break;
712 }
713 }
714 }
715 CriticalPathSU = NextSU;
716 CriticalPathMI = CriticalPathSU->getInstr();
717 } else {
718 // We've reached the end of the critical path.
719 CriticalPathSU = 0;
720 CriticalPathMI = 0;
721 }
722 }
Dan Gohman21d90032008-11-25 00:52:40 +0000723
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000724 PrescanInstruction(MI);
725
726 // If this instruction has a use of AntiDepReg, breaking it
727 // is invalid.
Dan Gohman21d90032008-11-25 00:52:40 +0000728 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
729 MachineOperand &MO = MI->getOperand(i);
730 if (!MO.isReg()) continue;
731 unsigned Reg = MO.getReg();
732 if (Reg == 0) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000733 if (MO.isUse() && AntiDepReg == Reg) {
Dan Gohman21d90032008-11-25 00:52:40 +0000734 AntiDepReg = 0;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000735 break;
Dan Gohman21d90032008-11-25 00:52:40 +0000736 }
Dan Gohman21d90032008-11-25 00:52:40 +0000737 }
738
739 // Determine AntiDepReg's register class, if it is live and is
740 // consistently used within a single class.
741 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000742 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000743 "Register should be live if it's causing an anti-dependence!");
744 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
745 AntiDepReg = 0;
746
747 // Look for a suitable register to use to break the anti-depenence.
748 //
749 // TODO: Instead of picking the first free register, consider which might
750 // be the best.
751 if (AntiDepReg != 0) {
Dan Gohman26255ad2009-08-12 01:33:27 +0000752 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
753 LastNewReg[AntiDepReg],
754 RC)) {
755 DEBUG(errs() << "Breaking anti-dependence edge on "
756 << TRI->getName(AntiDepReg)
757 << " with " << RegRefs.count(AntiDepReg) << " references"
758 << " using " << TRI->getName(NewReg) << "!\n");
Dan Gohman21d90032008-11-25 00:52:40 +0000759
Dan Gohman26255ad2009-08-12 01:33:27 +0000760 // Update the references to the old register to refer to the new
761 // register.
762 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
763 std::multimap<unsigned, MachineOperand *>::iterator>
764 Range = RegRefs.equal_range(AntiDepReg);
765 for (std::multimap<unsigned, MachineOperand *>::iterator
766 Q = Range.first, QE = Range.second; Q != QE; ++Q)
767 Q->second->setReg(NewReg);
Dan Gohman21d90032008-11-25 00:52:40 +0000768
Dan Gohman26255ad2009-08-12 01:33:27 +0000769 // We just went back in time and modified history; the
770 // liveness information for the anti-depenence reg is now
771 // inconsistent. Set the state as if it were dead.
772 Classes[NewReg] = Classes[AntiDepReg];
773 DefIndices[NewReg] = DefIndices[AntiDepReg];
774 KillIndices[NewReg] = KillIndices[AntiDepReg];
775 assert(((KillIndices[NewReg] == ~0u) !=
776 (DefIndices[NewReg] == ~0u)) &&
777 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000778
Dan Gohman26255ad2009-08-12 01:33:27 +0000779 Classes[AntiDepReg] = 0;
780 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
781 KillIndices[AntiDepReg] = ~0u;
782 assert(((KillIndices[AntiDepReg] == ~0u) !=
783 (DefIndices[AntiDepReg] == ~0u)) &&
784 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000785
Dan Gohman26255ad2009-08-12 01:33:27 +0000786 RegRefs.erase(AntiDepReg);
787 Changed = true;
788 LastNewReg[AntiDepReg] = NewReg;
Dan Gohman21d90032008-11-25 00:52:40 +0000789 }
790 }
791
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000792 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000793 }
Dan Gohman21d90032008-11-25 00:52:40 +0000794
795 return Changed;
796}
797
David Goodwin5e411782009-09-03 22:15:25 +0000798/// StartBlockForKills - Initialize register live-range state for updating kills
799///
800void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
801 // Initialize the indices to indicate that no registers are live.
802 std::fill(KillIndices, array_endof(KillIndices), ~0u);
803
804 // Determine the live-out physregs for this block.
805 if (!BB->empty() && BB->back().getDesc().isReturn()) {
806 // In a return block, examine the function live-out regs.
807 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
808 E = MRI.liveout_end(); I != E; ++I) {
809 unsigned Reg = *I;
810 KillIndices[Reg] = BB->size();
811 // Repeat, for all subregs.
812 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
813 *Subreg; ++Subreg) {
814 KillIndices[*Subreg] = BB->size();
815 }
816 }
817 }
818 else {
819 // In a non-return block, examine the live-in regs of all successors.
820 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
821 SE = BB->succ_end(); SI != SE; ++SI) {
822 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
823 E = (*SI)->livein_end(); I != E; ++I) {
824 unsigned Reg = *I;
825 KillIndices[Reg] = BB->size();
826 // Repeat, for all subregs.
827 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
828 *Subreg; ++Subreg) {
829 KillIndices[*Subreg] = BB->size();
830 }
831 }
832 }
833 }
834}
835
David Goodwin8f909342009-09-23 16:35:25 +0000836bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
837 MachineOperand &MO) {
838 // Setting kill flag...
839 if (!MO.isKill()) {
840 MO.setIsKill(true);
841 return false;
842 }
843
844 // If MO itself is live, clear the kill flag...
845 if (KillIndices[MO.getReg()] != ~0u) {
846 MO.setIsKill(false);
847 return false;
848 }
849
850 // If any subreg of MO is live, then create an imp-def for that
851 // subreg and keep MO marked as killed.
852 bool AllDead = true;
853 const unsigned SuperReg = MO.getReg();
854 for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
855 *Subreg; ++Subreg) {
856 if (KillIndices[*Subreg] != ~0u) {
857 MI->addOperand(MachineOperand::CreateReg(*Subreg,
858 true /*IsDef*/,
859 true /*IsImp*/,
860 false /*IsKill*/,
861 false /*IsDead*/));
862 AllDead = false;
863 }
864 }
865
866 MO.setIsKill(AllDead);
867 return false;
868}
869
David Goodwin88a589c2009-08-25 17:03:05 +0000870/// FixupKills - Fix the register kill flags, they may have been made
871/// incorrect by instruction reordering.
872///
873void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
874 DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
875
876 std::set<unsigned> killedRegs;
877 BitVector ReservedRegs = TRI->getReservedRegs(MF);
David Goodwin5e411782009-09-03 22:15:25 +0000878
879 StartBlockForKills(MBB);
David Goodwin7886cd82009-08-29 00:11:13 +0000880
881 // Examine block from end to start...
David Goodwin88a589c2009-08-25 17:03:05 +0000882 unsigned Count = MBB->size();
883 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
884 I != E; --Count) {
885 MachineInstr *MI = --I;
886
David Goodwin7886cd82009-08-29 00:11:13 +0000887 // Update liveness. Registers that are defed but not used in this
888 // instruction are now dead. Mark register and all subregs as they
889 // are completely defined.
890 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
891 MachineOperand &MO = MI->getOperand(i);
892 if (!MO.isReg()) continue;
893 unsigned Reg = MO.getReg();
894 if (Reg == 0) continue;
895 if (!MO.isDef()) continue;
896 // Ignore two-addr defs.
897 if (MI->isRegTiedToUseOperand(i)) continue;
898
David Goodwin7886cd82009-08-29 00:11:13 +0000899 KillIndices[Reg] = ~0u;
900
901 // Repeat for all subregs.
902 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
903 *Subreg; ++Subreg) {
904 KillIndices[*Subreg] = ~0u;
905 }
906 }
David Goodwin88a589c2009-08-25 17:03:05 +0000907
David Goodwin8f909342009-09-23 16:35:25 +0000908 // Examine all used registers and set/clear kill flag. When a
909 // register is used multiple times we only set the kill flag on
910 // the first use.
David Goodwin88a589c2009-08-25 17:03:05 +0000911 killedRegs.clear();
912 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
913 MachineOperand &MO = MI->getOperand(i);
914 if (!MO.isReg() || !MO.isUse()) continue;
915 unsigned Reg = MO.getReg();
916 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
917
David Goodwin7886cd82009-08-29 00:11:13 +0000918 bool kill = false;
919 if (killedRegs.find(Reg) == killedRegs.end()) {
920 kill = true;
921 // A register is not killed if any subregs are live...
922 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
923 *Subreg; ++Subreg) {
924 if (KillIndices[*Subreg] != ~0u) {
925 kill = false;
926 break;
927 }
928 }
929
930 // If subreg is not live, then register is killed if it became
931 // live in this instruction
932 if (kill)
933 kill = (KillIndices[Reg] == ~0u);
934 }
935
David Goodwin88a589c2009-08-25 17:03:05 +0000936 if (MO.isKill() != kill) {
David Goodwin8f909342009-09-23 16:35:25 +0000937 bool removed = ToggleKillFlag(MI, MO);
938 if (removed) {
939 DEBUG(errs() << "Fixed <removed> in ");
940 } else {
941 DEBUG(errs() << "Fixed " << MO << " in ");
942 }
David Goodwin88a589c2009-08-25 17:03:05 +0000943 DEBUG(MI->dump());
944 }
David Goodwin7886cd82009-08-29 00:11:13 +0000945
David Goodwin88a589c2009-08-25 17:03:05 +0000946 killedRegs.insert(Reg);
947 }
David Goodwin7886cd82009-08-29 00:11:13 +0000948
David Goodwina3251db2009-08-31 20:47:02 +0000949 // Mark any used register (that is not using undef) and subregs as
950 // now live...
David Goodwin7886cd82009-08-29 00:11:13 +0000951 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
952 MachineOperand &MO = MI->getOperand(i);
David Goodwina3251db2009-08-31 20:47:02 +0000953 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
David Goodwin7886cd82009-08-29 00:11:13 +0000954 unsigned Reg = MO.getReg();
955 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
956
David Goodwin7886cd82009-08-29 00:11:13 +0000957 KillIndices[Reg] = Count;
958
959 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
960 *Subreg; ++Subreg) {
961 KillIndices[*Subreg] = Count;
962 }
963 }
David Goodwin88a589c2009-08-25 17:03:05 +0000964 }
965}
966
Dan Gohman343f0c02008-11-19 23:18:57 +0000967//===----------------------------------------------------------------------===//
968// Top-Down Scheduling
969//===----------------------------------------------------------------------===//
970
971/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
972/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000973void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
974 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000975 --SuccSU->NumPredsLeft;
976
977#ifndef NDEBUG
978 if (SuccSU->NumPredsLeft < 0) {
Chris Lattner103289e2009-08-23 07:19:13 +0000979 errs() << "*** Scheduling failed! ***\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000980 SuccSU->dump(this);
Chris Lattner103289e2009-08-23 07:19:13 +0000981 errs() << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000982 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +0000983 }
984#endif
985
986 // Compute how many cycles it will be before this actually becomes
987 // available. This is the max of the start time of all predecessors plus
988 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000989 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000990
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000991 // If all the node's predecessors are scheduled, this node is ready
992 // to be scheduled. Ignore the special ExitSU node.
993 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000994 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000995}
996
997/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
998void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
999 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1000 I != E; ++I)
1001 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +00001002}
1003
1004/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1005/// count of its successors. If a successor pending count is zero, add it to
1006/// the Available queue.
1007void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin3a5f0d42009-08-11 01:44:26 +00001008 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman343f0c02008-11-19 23:18:57 +00001009 DEBUG(SU->dump(this));
1010
1011 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +00001012 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1013 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +00001014
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001015 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +00001016 SU->isScheduled = true;
1017 AvailableQueue.ScheduledNode(SU);
1018}
1019
1020/// ListScheduleTopDown - The main loop of list scheduling for top-down
1021/// schedulers.
1022void SchedulePostRATDList::ListScheduleTopDown() {
1023 unsigned CurCycle = 0;
1024
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001025 // Release any successors of the special Entry node.
1026 ReleaseSuccessors(&EntrySU);
1027
Dan Gohman343f0c02008-11-19 23:18:57 +00001028 // All leaves to Available queue.
1029 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1030 // It is available if it has no predecessors.
1031 if (SUnits[i].Preds.empty()) {
1032 AvailableQueue.push(&SUnits[i]);
1033 SUnits[i].isAvailable = true;
1034 }
1035 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001036
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001037 // In any cycle where we can't schedule any instructions, we must
1038 // stall or emit a noop, depending on the target.
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001039 bool CycleHasInsts = false;
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001040
Dan Gohman343f0c02008-11-19 23:18:57 +00001041 // While Available queue is not empty, grab the node with the highest
1042 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +00001043 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +00001044 Sequence.reserve(SUnits.size());
1045 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
1046 // Check to see if any of the pending instructions are ready to issue. If
1047 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +00001048 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +00001049 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +00001050 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +00001051 AvailableQueue.push(PendingQueue[i]);
1052 PendingQueue[i]->isAvailable = true;
1053 PendingQueue[i] = PendingQueue.back();
1054 PendingQueue.pop_back();
1055 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +00001056 } else if (PendingQueue[i]->getDepth() < MinDepth)
1057 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +00001058 }
David Goodwinc93d8372009-08-11 17:35:23 +00001059
David Goodwin7cd01182009-08-11 17:56:42 +00001060 DEBUG(errs() << "\n*** Examining Available\n";
1061 LatencyPriorityQueue q = AvailableQueue;
1062 while (!q.empty()) {
1063 SUnit *su = q.pop();
1064 errs() << "Height " << su->getHeight() << ": ";
1065 su->dump(this);
1066 });
David Goodwinc93d8372009-08-11 17:35:23 +00001067
Dan Gohman2836c282009-01-16 01:33:36 +00001068 SUnit *FoundSUnit = 0;
1069
1070 bool HasNoopHazards = false;
1071 while (!AvailableQueue.empty()) {
1072 SUnit *CurSUnit = AvailableQueue.pop();
1073
1074 ScheduleHazardRecognizer::HazardType HT =
1075 HazardRec->getHazardType(CurSUnit);
1076 if (HT == ScheduleHazardRecognizer::NoHazard) {
1077 FoundSUnit = CurSUnit;
1078 break;
1079 }
1080
1081 // Remember if this is a noop hazard.
1082 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
1083
1084 NotReady.push_back(CurSUnit);
1085 }
1086
1087 // Add the nodes that aren't ready back onto the available list.
1088 if (!NotReady.empty()) {
1089 AvailableQueue.push_all(NotReady);
1090 NotReady.clear();
1091 }
1092
Dan Gohman343f0c02008-11-19 23:18:57 +00001093 // If we found a node to schedule, do it now.
1094 if (FoundSUnit) {
1095 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +00001096 HazardRec->EmitInstruction(FoundSUnit);
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001097 CycleHasInsts = true;
Dan Gohman343f0c02008-11-19 23:18:57 +00001098
David Goodwind94a4e52009-08-10 15:55:25 +00001099 // If we are using the target-specific hazards, then don't
1100 // advance the cycle time just because we schedule a node. If
1101 // the target allows it we can schedule multiple nodes in the
1102 // same cycle.
1103 if (!EnablePostRAHazardAvoidance) {
1104 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
1105 ++CurCycle;
1106 }
Dan Gohman2836c282009-01-16 01:33:36 +00001107 } else {
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001108 if (CycleHasInsts) {
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001109 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
1110 HazardRec->AdvanceCycle();
1111 } else if (!HasNoopHazards) {
1112 // Otherwise, we have a pipeline stall, but no other problem,
1113 // just advance the current cycle and try again.
1114 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
1115 HazardRec->AdvanceCycle();
1116 ++NumStalls;
1117 } else {
1118 // Otherwise, we have no instructions to issue and we have instructions
1119 // that will fault if we don't do this right. This is the case for
1120 // processors without pipeline interlocks and other cases.
1121 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
1122 HazardRec->EmitNoop();
1123 Sequence.push_back(0); // NULL here means noop
1124 ++NumNoops;
1125 }
1126
Dan Gohman2836c282009-01-16 01:33:36 +00001127 ++CurCycle;
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001128 CycleHasInsts = false;
Dan Gohman343f0c02008-11-19 23:18:57 +00001129 }
1130 }
1131
1132#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +00001133 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +00001134#endif
1135}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00001136
1137//===----------------------------------------------------------------------===//
1138// Public Constructor Functions
1139//===----------------------------------------------------------------------===//
1140
1141FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +00001142 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00001143}