blob: 4ee97e79b5ffb25961e5fc795518e0dc4a5510eb [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Goodwina8b85962009-10-26 19:32:42 +000022#include "AggressiveAntiDepBreaker.h"
David Goodwinad5789c2009-10-26 16:59:04 +000023#include "CriticalAntiDepBreaker.h"
David Goodwin5ab4fd42009-08-10 15:55:25 +000024#include "ExactHazardRecognizer.h"
25#include "SimpleHazardRecognizer.h"
Dan Gohman98c6cb32009-02-06 17:12:10 +000026#include "ScheduleDAGInstrs.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/CodeGen/Passes.h"
Dan Gohmand27a0e02008-11-19 23:18:57 +000028#include "llvm/CodeGen/LatencyPriorityQueue.h"
29#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman6b2ee8f2008-12-16 03:25:46 +000030#include "llvm/CodeGen/MachineDominators.h"
David Goodwincdb56fc2009-10-01 19:45:32 +000031#include "llvm/CodeGen/MachineFrameInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman6b2ee8f2008-12-16 03:25:46 +000033#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohmanc2c90e22008-11-25 00:52:40 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman99603bb2009-01-16 01:33:36 +000035#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohman0a4c09e2009-10-09 23:27:56 +000036#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman75cc17f2009-02-10 23:29:38 +000037#include "llvm/Target/TargetLowering.h"
Dan Gohman96eb47a2009-01-15 19:20:50 +000038#include "llvm/Target/TargetMachine.h"
Dan Gohmanc2c90e22008-11-25 00:52:40 +000039#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetRegisterInfo.h"
David Goodwincf89a602009-09-30 00:10:16 +000041#include "llvm/Target/TargetSubtarget.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000043#include "llvm/Support/ErrorHandling.h"
David Goodwin0eeb4512009-08-11 01:44:26 +000044#include "llvm/Support/raw_ostream.h"
David Goodwinad5789c2009-10-26 16:59:04 +000045#include "llvm/ADT/BitVector.h"
Dan Gohmand27a0e02008-11-19 23:18:57 +000046#include "llvm/ADT/Statistic.h"
Dan Gohmanc2c90e22008-11-25 00:52:40 +000047#include <map>
David Goodwina9c16fe2009-08-25 17:03:05 +000048#include <set>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049using namespace llvm;
50
Dan Gohman99603bb2009-01-16 01:33:36 +000051STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohmand27a0e02008-11-19 23:18:57 +000052STATISTIC(NumStalls, "Number of pipeline stalls");
David Goodwinad5789c2009-10-26 16:59:04 +000053STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
Dan Gohmand27a0e02008-11-19 23:18:57 +000054
David Goodwin089aa852009-10-01 21:46:35 +000055// Post-RA scheduling is enabled with
56// TargetSubtarget.enablePostRAScheduler(). This flag can be used to
57// override the target.
58static cl::opt<bool>
59EnablePostRAScheduler("post-RA-scheduler",
60 cl::desc("Enable scheduling after register allocation"),
David Goodwin736fed92009-10-01 22:19:57 +000061 cl::init(false), cl::Hidden);
David Goodwinad5789c2009-10-26 16:59:04 +000062static cl::opt<std::string>
Dan Gohmanc2c90e22008-11-25 00:52:40 +000063EnableAntiDepBreaking("break-anti-dependencies",
David Goodwinad5789c2009-10-26 16:59:04 +000064 cl::desc("Break post-RA scheduling anti-dependencies: "
65 "\"critical\", \"all\", or \"none\""),
66 cl::init("none"), cl::Hidden);
Dan Gohman99603bb2009-01-16 01:33:36 +000067static cl::opt<bool>
68EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwin5ab4fd42009-08-10 15:55:25 +000069 cl::desc("Enable exact hazard avoidance"),
David Goodwin856b38c2009-09-03 22:15:25 +000070 cl::init(true), cl::Hidden);
Dan Gohman99603bb2009-01-16 01:33:36 +000071
David Goodwin4b023dd2009-09-01 18:34:03 +000072// If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
73static cl::opt<int>
74DebugDiv("postra-sched-debugdiv",
75 cl::desc("Debug control MBBs that are scheduled"),
76 cl::init(0), cl::Hidden);
77static cl::opt<int>
78DebugMod("postra-sched-debugmod",
79 cl::desc("Debug control MBBs that are scheduled"),
80 cl::init(0), cl::Hidden);
81
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000083 class PostRAScheduler : public MachineFunctionPass {
Dan Gohman0a4c09e2009-10-09 23:27:56 +000084 AliasAnalysis *AA;
Evan Cheng86e24b02009-10-16 21:06:15 +000085 CodeGenOpt::Level OptLevel;
Dan Gohman0a4c09e2009-10-09 23:27:56 +000086
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087 public:
88 static char ID;
Evan Cheng86e24b02009-10-16 21:06:15 +000089 PostRAScheduler(CodeGenOpt::Level ol) :
90 MachineFunctionPass(&ID), OptLevel(ol) {}
Dan Gohmanc2c90e22008-11-25 00:52:40 +000091
Dan Gohman6b2ee8f2008-12-16 03:25:46 +000092 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanecb436f2009-07-31 23:37:33 +000093 AU.setPreservesCFG();
Dan Gohman0a4c09e2009-10-09 23:27:56 +000094 AU.addRequired<AliasAnalysis>();
Dan Gohman6b2ee8f2008-12-16 03:25:46 +000095 AU.addRequired<MachineDominatorTree>();
96 AU.addPreserved<MachineDominatorTree>();
97 AU.addRequired<MachineLoopInfo>();
98 AU.addPreserved<MachineLoopInfo>();
99 MachineFunctionPass::getAnalysisUsage(AU);
100 }
101
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000102 const char *getPassName() const {
Dan Gohmanc2c90e22008-11-25 00:52:40 +0000103 return "Post RA top-down list latency scheduler";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104 }
105
106 bool runOnMachineFunction(MachineFunction &Fn);
107 };
Dan Gohmand27a0e02008-11-19 23:18:57 +0000108 char PostRAScheduler::ID = 0;
109
Nick Lewycky492d06e2009-10-25 06:33:48 +0000110 class SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohmand27a0e02008-11-19 23:18:57 +0000111 /// AvailableQueue - The priority queue to use for the available SUnits.
Dan Gohmanfb035b42009-10-21 01:44:44 +0000112 ///
Dan Gohmand27a0e02008-11-19 23:18:57 +0000113 LatencyPriorityQueue AvailableQueue;
114
115 /// PendingQueue - This contains all of the instructions whose operands have
116 /// been issued, but their results are not ready yet (due to the latency of
117 /// the operation). Once the operands becomes available, the instruction is
118 /// added to the AvailableQueue.
119 std::vector<SUnit*> PendingQueue;
120
Dan Gohmanc2c90e22008-11-25 00:52:40 +0000121 /// Topo - A topological ordering for SUnits.
122 ScheduleDAGTopologicalSort Topo;
Dan Gohmand27a0e02008-11-19 23:18:57 +0000123
Dan Gohman99603bb2009-01-16 01:33:36 +0000124 /// HazardRec - The hazard recognizer to use.
125 ScheduleHazardRecognizer *HazardRec;
126
David Goodwinad5789c2009-10-26 16:59:04 +0000127 /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
128 AntiDepBreaker *AntiDepBreak;
129
Dan Gohman0a4c09e2009-10-09 23:27:56 +0000130 /// AA - AliasAnalysis for making memory reference queries.
131 AliasAnalysis *AA;
132
Dan Gohmanfb035b42009-10-21 01:44:44 +0000133 /// KillIndices - The index of the most recent kill (proceding bottom-up),
134 /// or ~0u if the register is not live.
Dan Gohmana91eb052009-02-10 23:27:53 +0000135 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
136
Dan Gohmanc2c90e22008-11-25 00:52:40 +0000137 public:
Dan Gohman96eb47a2009-01-15 19:20:50 +0000138 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman6b2ee8f2008-12-16 03:25:46 +0000139 const MachineLoopInfo &MLI,
Dan Gohman99603bb2009-01-16 01:33:36 +0000140 const MachineDominatorTree &MDT,
Dan Gohman0a4c09e2009-10-09 23:27:56 +0000141 ScheduleHazardRecognizer *HR,
David Goodwinad5789c2009-10-26 16:59:04 +0000142 AntiDepBreaker *ADB,
143 AliasAnalysis *aa)
Dan Gohman96eb47a2009-01-15 19:20:50 +0000144 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
David Goodwinad5789c2009-10-26 16:59:04 +0000145 HazardRec(HR), AntiDepBreak(ADB), AA(aa) {}
Dan Gohman99603bb2009-01-16 01:33:36 +0000146
147 ~SchedulePostRATDList() {
Dan Gohman99603bb2009-01-16 01:33:36 +0000148 }
Dan Gohmand27a0e02008-11-19 23:18:57 +0000149
Dan Gohmana91eb052009-02-10 23:27:53 +0000150 /// StartBlock - Initialize register live-range state for scheduling in
151 /// this block.
152 ///
153 void StartBlock(MachineBasicBlock *BB);
154
155 /// Schedule - Schedule the instruction range using list scheduling.
156 ///
Dan Gohmand27a0e02008-11-19 23:18:57 +0000157 void Schedule();
David Goodwina9c16fe2009-08-25 17:03:05 +0000158
Dan Gohmanfb035b42009-10-21 01:44:44 +0000159 /// Observe - Update liveness information to account for the current
160 /// instruction, which will not be scheduled.
161 ///
162 void Observe(MachineInstr *MI, unsigned Count);
163
164 /// FinishBlock - Clean up register live-range state.
165 ///
166 void FinishBlock();
167
David Goodwinad5789c2009-10-26 16:59:04 +0000168 /// FixupKills - Fix register kill flags that have been made
169 /// invalid due to scheduling
170 ///
171 void FixupKills(MachineBasicBlock *MBB);
172
Dan Gohmand27a0e02008-11-19 23:18:57 +0000173 private:
Dan Gohman604394b2008-12-09 22:54:47 +0000174 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohmana91eb052009-02-10 23:27:53 +0000175 void ReleaseSuccessors(SUnit *SU);
Dan Gohmand27a0e02008-11-19 23:18:57 +0000176 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
177 void ListScheduleTopDown();
David Goodwin856b38c2009-09-03 22:15:25 +0000178 void StartBlockForKills(MachineBasicBlock *BB);
David Goodwin83b6ace2009-09-23 16:35:25 +0000179
180 // ToggleKillFlag - Toggle a register operand kill flag. Other
181 // adjustments may be made to the instruction if necessary. Return
182 // true if the operand has been deleted, false if not.
183 bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
Dan Gohmand27a0e02008-11-19 23:18:57 +0000184 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185}
186
Dan Gohmana91eb052009-02-10 23:27:53 +0000187/// isSchedulingBoundary - Test if the given instruction should be
188/// considered a scheduling boundary. This primarily includes labels
189/// and terminators.
190///
191static bool isSchedulingBoundary(const MachineInstr *MI,
192 const MachineFunction &MF) {
193 // Terminators and labels can't be scheduled around.
194 if (MI->getDesc().isTerminator() || MI->isLabel())
195 return true;
196
Dan Gohman75cc17f2009-02-10 23:29:38 +0000197 // Don't attempt to schedule around any instruction that modifies
198 // a stack-oriented pointer, as it's unlikely to be profitable. This
199 // saves compile time, because it doesn't require every single
200 // stack slot reference to depend on the instruction that does the
201 // modification.
202 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
203 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
204 return true;
205
Dan Gohmana91eb052009-02-10 23:27:53 +0000206 return false;
207}
208
Dan Gohmand27a0e02008-11-19 23:18:57 +0000209bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
Dan Gohman101611d2009-10-10 00:15:38 +0000210 AA = &getAnalysis<AliasAnalysis>();
211
David Goodwin089aa852009-10-01 21:46:35 +0000212 // Check for explicit enable/disable of post-ra scheduling.
David Goodwine56e4a62009-10-22 23:19:17 +0000213 TargetSubtarget::AntiDepBreakMode AntiDepMode = TargetSubtarget::ANTIDEP_NONE;
David Goodwin089aa852009-10-01 21:46:35 +0000214 if (EnablePostRAScheduler.getPosition() > 0) {
215 if (!EnablePostRAScheduler)
Evan Cheng57796902009-10-16 06:10:34 +0000216 return false;
David Goodwin089aa852009-10-01 21:46:35 +0000217 } else {
Evan Cheng57796902009-10-16 06:10:34 +0000218 // Check that post-RA scheduling is enabled for this target.
David Goodwin089aa852009-10-01 21:46:35 +0000219 const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
David Goodwine56e4a62009-10-22 23:19:17 +0000220 if (!ST.enablePostRAScheduler(OptLevel, AntiDepMode))
Evan Cheng57796902009-10-16 06:10:34 +0000221 return false;
David Goodwin089aa852009-10-01 21:46:35 +0000222 }
David Goodwincf89a602009-09-30 00:10:16 +0000223
David Goodwine56e4a62009-10-22 23:19:17 +0000224 // Check for antidep breaking override...
225 if (EnableAntiDepBreaking.getPosition() > 0) {
David Goodwinad5789c2009-10-26 16:59:04 +0000226 AntiDepMode = (EnableAntiDepBreaking == "all") ? TargetSubtarget::ANTIDEP_ALL :
227 (EnableAntiDepBreaking == "critical") ? TargetSubtarget::ANTIDEP_CRITICAL :
228 TargetSubtarget::ANTIDEP_NONE;
David Goodwine56e4a62009-10-22 23:19:17 +0000229 }
230
David Goodwin0eeb4512009-08-11 01:44:26 +0000231 DEBUG(errs() << "PostRAScheduler\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232
Dan Gohman6b2ee8f2008-12-16 03:25:46 +0000233 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
234 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwin5ab4fd42009-08-10 15:55:25 +0000235 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman99603bb2009-01-16 01:33:36 +0000236 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwin5ab4fd42009-08-10 15:55:25 +0000237 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
238 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
David Goodwinad5789c2009-10-26 16:59:04 +0000239 AntiDepBreaker *ADB =
David Goodwina8b85962009-10-26 19:32:42 +0000240 ((AntiDepMode == TargetSubtarget::ANTIDEP_ALL) ?
241 (AntiDepBreaker *)new AggressiveAntiDepBreaker(Fn) :
242 ((AntiDepMode == TargetSubtarget::ANTIDEP_CRITICAL) ?
243 (AntiDepBreaker *)new CriticalAntiDepBreaker(Fn) : NULL));
Dan Gohman6b2ee8f2008-12-16 03:25:46 +0000244
David Goodwinad5789c2009-10-26 16:59:04 +0000245 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR, ADB, AA);
Dan Gohman96eb47a2009-01-15 19:20:50 +0000246
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 // Loop over all of the basic blocks
248 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohmand27a0e02008-11-19 23:18:57 +0000249 MBB != MBBe; ++MBB) {
David Goodwin4b023dd2009-09-01 18:34:03 +0000250#ifndef NDEBUG
251 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
252 if (DebugDiv > 0) {
253 static int bbcnt = 0;
254 if (bbcnt++ % DebugDiv != DebugMod)
255 continue;
256 errs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
257 ":MBB ID#" << MBB->getNumber() << " ***\n";
258 }
259#endif
260
Dan Gohmana91eb052009-02-10 23:27:53 +0000261 // Initialize register live-range state for scheduling in this block.
262 Scheduler.StartBlock(MBB);
263
Dan Gohman14bb9922009-01-16 22:10:20 +0000264 // Schedule each sequence of instructions not interrupted by a label
265 // or anything else that effectively needs to shut down scheduling.
Dan Gohmana91eb052009-02-10 23:27:53 +0000266 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman7c968a82009-02-11 04:27:20 +0000267 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohmana91eb052009-02-10 23:27:53 +0000268 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
269 MachineInstr *MI = prior(I);
270 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman68ade7b2009-03-10 18:10:43 +0000271 Scheduler.Run(MBB, I, Current, CurrentCount);
Evan Chengd7dc9832009-09-18 21:02:19 +0000272 Scheduler.EmitSchedule(0);
Dan Gohmana91eb052009-02-10 23:27:53 +0000273 Current = MI;
Dan Gohman7c968a82009-02-11 04:27:20 +0000274 CurrentCount = Count - 1;
Dan Gohman68ade7b2009-03-10 18:10:43 +0000275 Scheduler.Observe(MI, CurrentCount);
Dan Gohman14bb9922009-01-16 22:10:20 +0000276 }
Dan Gohmana91eb052009-02-10 23:27:53 +0000277 I = MI;
Dan Gohman7c968a82009-02-11 04:27:20 +0000278 --Count;
Dan Gohman0dcda312009-02-03 18:57:45 +0000279 }
Dan Gohman7c968a82009-02-11 04:27:20 +0000280 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands34468542009-03-11 09:04:34 +0000281 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman68ade7b2009-03-10 18:10:43 +0000282 "Instruction count mismatch!");
283 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Evan Chengd7dc9832009-09-18 21:02:19 +0000284 Scheduler.EmitSchedule(0);
Dan Gohmana91eb052009-02-10 23:27:53 +0000285
286 // Clean up register live-range state.
287 Scheduler.FinishBlock();
David Goodwina9c16fe2009-08-25 17:03:05 +0000288
David Goodwin856b38c2009-09-03 22:15:25 +0000289 // Update register kills
David Goodwina9c16fe2009-08-25 17:03:05 +0000290 Scheduler.FixupKills(MBB);
Dan Gohmand27a0e02008-11-19 23:18:57 +0000291 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292
David Goodwinad5789c2009-10-26 16:59:04 +0000293 delete HR;
294 delete ADB;
295
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 return true;
297}
298
Dan Gohmana91eb052009-02-10 23:27:53 +0000299/// StartBlock - Initialize register live-range state for scheduling in
300/// this block.
Dan Gohmanc2c90e22008-11-25 00:52:40 +0000301///
Dan Gohmana91eb052009-02-10 23:27:53 +0000302void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
303 // Call the superclass.
304 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohmanc2c90e22008-11-25 00:52:40 +0000305
David Goodwinad5789c2009-10-26 16:59:04 +0000306 // Reset the hazard recognizer and anti-dep breaker.
David Goodwin5ab4fd42009-08-10 15:55:25 +0000307 HazardRec->Reset();
David Goodwinad5789c2009-10-26 16:59:04 +0000308 if (AntiDepBreak != NULL)
309 AntiDepBreak->StartBlock(BB);
Dan Gohmana91eb052009-02-10 23:27:53 +0000310}
311
312/// Schedule - Schedule the instruction range using list scheduling.
313///
314void SchedulePostRATDList::Schedule() {
David Goodwin0eeb4512009-08-11 01:44:26 +0000315 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohmana91eb052009-02-10 23:27:53 +0000316
317 // Build the scheduling graph.
Dan Gohman0a4c09e2009-10-09 23:27:56 +0000318 BuildSchedGraph(AA);
Dan Gohmana91eb052009-02-10 23:27:53 +0000319
David Goodwinad5789c2009-10-26 16:59:04 +0000320 if (AntiDepBreak != NULL) {
321 unsigned Broken =
322 AntiDepBreak->BreakAntiDependencies(SUnits, Begin, InsertPos,
323 InsertPosIndex);
324 if (Broken > 0) {
Dan Gohmana91eb052009-02-10 23:27:53 +0000325 // We made changes. Update the dependency graph.
326 // Theoretically we could update the graph in place:
327 // When a live range is changed to use a different register, remove
328 // the def's anti-dependence *and* output-dependence edges due to
329 // that register, and add new anti-dependence and output-dependence
330 // edges based on the next live range of the register.
331 SUnits.clear();
332 EntrySU = SUnit();
333 ExitSU = SUnit();
Dan Gohman0a4c09e2009-10-09 23:27:56 +0000334 BuildSchedGraph(AA);
David Goodwinad5789c2009-10-26 16:59:04 +0000335
336 NumFixedAnti += Broken;
Dan Gohmana91eb052009-02-10 23:27:53 +0000337 }
338 }
339
David Goodwin5ab4fd42009-08-10 15:55:25 +0000340 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
341 SUnits[su].dumpAll(this));
342
Dan Gohmana91eb052009-02-10 23:27:53 +0000343 AvailableQueue.initNodes(SUnits);
344
345 ListScheduleTopDown();
346
347 AvailableQueue.releaseState();
348}
349
350/// Observe - Update liveness information to account for the current
351/// instruction, which will not be scheduled.
352///
Dan Gohman7c968a82009-02-11 04:27:20 +0000353void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
David Goodwinad5789c2009-10-26 16:59:04 +0000354 if (AntiDepBreak != NULL)
355 AntiDepBreak->Observe(MI, Count, InsertPosIndex);
Dan Gohmana91eb052009-02-10 23:27:53 +0000356}
357
358/// FinishBlock - Clean up register live-range state.
359///
360void SchedulePostRATDList::FinishBlock() {
David Goodwinad5789c2009-10-26 16:59:04 +0000361 if (AntiDepBreak != NULL)
362 AntiDepBreak->FinishBlock();
Dan Gohmana91eb052009-02-10 23:27:53 +0000363
364 // Call the superclass.
365 ScheduleDAGInstrs::FinishBlock();
366}
367
David Goodwin856b38c2009-09-03 22:15:25 +0000368/// StartBlockForKills - Initialize register live-range state for updating kills
369///
370void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
371 // Initialize the indices to indicate that no registers are live.
372 std::fill(KillIndices, array_endof(KillIndices), ~0u);
373
374 // Determine the live-out physregs for this block.
375 if (!BB->empty() && BB->back().getDesc().isReturn()) {
376 // In a return block, examine the function live-out regs.
377 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
378 E = MRI.liveout_end(); I != E; ++I) {
379 unsigned Reg = *I;
380 KillIndices[Reg] = BB->size();
381 // Repeat, for all subregs.
382 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
383 *Subreg; ++Subreg) {
384 KillIndices[*Subreg] = BB->size();
385 }
386 }
387 }
388 else {
389 // In a non-return block, examine the live-in regs of all successors.
390 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
391 SE = BB->succ_end(); SI != SE; ++SI) {
392 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
393 E = (*SI)->livein_end(); I != E; ++I) {
394 unsigned Reg = *I;
395 KillIndices[Reg] = BB->size();
396 // Repeat, for all subregs.
397 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
398 *Subreg; ++Subreg) {
399 KillIndices[*Subreg] = BB->size();
400 }
401 }
402 }
403 }
404}
405
David Goodwin83b6ace2009-09-23 16:35:25 +0000406bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
407 MachineOperand &MO) {
408 // Setting kill flag...
409 if (!MO.isKill()) {
410 MO.setIsKill(true);
411 return false;
412 }
413
414 // If MO itself is live, clear the kill flag...
415 if (KillIndices[MO.getReg()] != ~0u) {
416 MO.setIsKill(false);
417 return false;
418 }
419
420 // If any subreg of MO is live, then create an imp-def for that
421 // subreg and keep MO marked as killed.
Benjamin Kramere3901ce2009-10-02 15:59:52 +0000422 MO.setIsKill(false);
David Goodwin83b6ace2009-09-23 16:35:25 +0000423 bool AllDead = true;
424 const unsigned SuperReg = MO.getReg();
425 for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
426 *Subreg; ++Subreg) {
427 if (KillIndices[*Subreg] != ~0u) {
428 MI->addOperand(MachineOperand::CreateReg(*Subreg,
429 true /*IsDef*/,
430 true /*IsImp*/,
431 false /*IsKill*/,
432 false /*IsDead*/));
433 AllDead = false;
434 }
435 }
436
Dan Gohmanfb035b42009-10-21 01:44:44 +0000437 if(AllDead)
Benjamin Kramere3901ce2009-10-02 15:59:52 +0000438 MO.setIsKill(true);
David Goodwin83b6ace2009-09-23 16:35:25 +0000439 return false;
440}
441
David Goodwina9c16fe2009-08-25 17:03:05 +0000442/// FixupKills - Fix the register kill flags, they may have been made
443/// incorrect by instruction reordering.
444///
445void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
446 DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
447
448 std::set<unsigned> killedRegs;
449 BitVector ReservedRegs = TRI->getReservedRegs(MF);
David Goodwin856b38c2009-09-03 22:15:25 +0000450
451 StartBlockForKills(MBB);
David Goodwine54c0042009-08-29 00:11:13 +0000452
453 // Examine block from end to start...
David Goodwina9c16fe2009-08-25 17:03:05 +0000454 unsigned Count = MBB->size();
455 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
456 I != E; --Count) {
457 MachineInstr *MI = --I;
458
David Goodwine54c0042009-08-29 00:11:13 +0000459 // Update liveness. Registers that are defed but not used in this
460 // instruction are now dead. Mark register and all subregs as they
461 // are completely defined.
462 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
463 MachineOperand &MO = MI->getOperand(i);
464 if (!MO.isReg()) continue;
465 unsigned Reg = MO.getReg();
466 if (Reg == 0) continue;
467 if (!MO.isDef()) continue;
468 // Ignore two-addr defs.
469 if (MI->isRegTiedToUseOperand(i)) continue;
470
David Goodwine54c0042009-08-29 00:11:13 +0000471 KillIndices[Reg] = ~0u;
472
473 // Repeat for all subregs.
474 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
475 *Subreg; ++Subreg) {
476 KillIndices[*Subreg] = ~0u;
477 }
478 }
David Goodwina9c16fe2009-08-25 17:03:05 +0000479
David Goodwin83b6ace2009-09-23 16:35:25 +0000480 // Examine all used registers and set/clear kill flag. When a
481 // register is used multiple times we only set the kill flag on
482 // the first use.
David Goodwina9c16fe2009-08-25 17:03:05 +0000483 killedRegs.clear();
484 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
485 MachineOperand &MO = MI->getOperand(i);
486 if (!MO.isReg() || !MO.isUse()) continue;
487 unsigned Reg = MO.getReg();
488 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
489
David Goodwine54c0042009-08-29 00:11:13 +0000490 bool kill = false;
491 if (killedRegs.find(Reg) == killedRegs.end()) {
492 kill = true;
493 // A register is not killed if any subregs are live...
494 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
495 *Subreg; ++Subreg) {
496 if (KillIndices[*Subreg] != ~0u) {
497 kill = false;
498 break;
499 }
500 }
501
502 // If subreg is not live, then register is killed if it became
503 // live in this instruction
504 if (kill)
505 kill = (KillIndices[Reg] == ~0u);
506 }
507
David Goodwina9c16fe2009-08-25 17:03:05 +0000508 if (MO.isKill() != kill) {
David Goodwin83b6ace2009-09-23 16:35:25 +0000509 bool removed = ToggleKillFlag(MI, MO);
510 if (removed) {
511 DEBUG(errs() << "Fixed <removed> in ");
512 } else {
513 DEBUG(errs() << "Fixed " << MO << " in ");
514 }
David Goodwina9c16fe2009-08-25 17:03:05 +0000515 DEBUG(MI->dump());
516 }
David Goodwine54c0042009-08-29 00:11:13 +0000517
David Goodwina9c16fe2009-08-25 17:03:05 +0000518 killedRegs.insert(Reg);
519 }
David Goodwine54c0042009-08-29 00:11:13 +0000520
David Goodwin864c4b82009-08-31 20:47:02 +0000521 // Mark any used register (that is not using undef) and subregs as
522 // now live...
David Goodwine54c0042009-08-29 00:11:13 +0000523 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
524 MachineOperand &MO = MI->getOperand(i);
David Goodwin864c4b82009-08-31 20:47:02 +0000525 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
David Goodwine54c0042009-08-29 00:11:13 +0000526 unsigned Reg = MO.getReg();
527 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
528
David Goodwine54c0042009-08-29 00:11:13 +0000529 KillIndices[Reg] = Count;
530
531 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
532 *Subreg; ++Subreg) {
533 KillIndices[*Subreg] = Count;
534 }
535 }
David Goodwina9c16fe2009-08-25 17:03:05 +0000536 }
537}
538
Dan Gohmand27a0e02008-11-19 23:18:57 +0000539//===----------------------------------------------------------------------===//
540// Top-Down Scheduling
541//===----------------------------------------------------------------------===//
542
543/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
544/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman604394b2008-12-09 22:54:47 +0000545void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
546 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Klecknere9b95fd2009-09-30 20:15:38 +0000547
Dan Gohmand27a0e02008-11-19 23:18:57 +0000548#ifndef NDEBUG
Reid Klecknere9b95fd2009-09-30 20:15:38 +0000549 if (SuccSU->NumPredsLeft == 0) {
Chris Lattnerbf9d76d2009-08-23 07:19:13 +0000550 errs() << "*** Scheduling failed! ***\n";
Dan Gohmand27a0e02008-11-19 23:18:57 +0000551 SuccSU->dump(this);
Chris Lattnerbf9d76d2009-08-23 07:19:13 +0000552 errs() << " has been released too many times!\n";
Edwin Törökbd448e32009-07-14 16:55:14 +0000553 llvm_unreachable(0);
Dan Gohmand27a0e02008-11-19 23:18:57 +0000554 }
555#endif
Reid Klecknere9b95fd2009-09-30 20:15:38 +0000556 --SuccSU->NumPredsLeft;
557
Dan Gohmand27a0e02008-11-19 23:18:57 +0000558 // Compute how many cycles it will be before this actually becomes
559 // available. This is the max of the start time of all predecessors plus
560 // their latencies.
Dan Gohman6b2ee8f2008-12-16 03:25:46 +0000561 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohmand27a0e02008-11-19 23:18:57 +0000562
Dan Gohmana91eb052009-02-10 23:27:53 +0000563 // If all the node's predecessors are scheduled, this node is ready
564 // to be scheduled. Ignore the special ExitSU node.
565 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohmand27a0e02008-11-19 23:18:57 +0000566 PendingQueue.push_back(SuccSU);
Dan Gohmana91eb052009-02-10 23:27:53 +0000567}
568
569/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
570void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
571 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
572 I != E; ++I)
573 ReleaseSucc(SU, &*I);
Dan Gohmand27a0e02008-11-19 23:18:57 +0000574}
575
576/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
577/// count of its successors. If a successor pending count is zero, add it to
578/// the Available queue.
579void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin0eeb4512009-08-11 01:44:26 +0000580 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohmand27a0e02008-11-19 23:18:57 +0000581 DEBUG(SU->dump(this));
582
583 Sequence.push_back(SU);
Dan Gohman6b2ee8f2008-12-16 03:25:46 +0000584 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
585 SU->setDepthToAtLeast(CurCycle);
Dan Gohmand27a0e02008-11-19 23:18:57 +0000586
Dan Gohmana91eb052009-02-10 23:27:53 +0000587 ReleaseSuccessors(SU);
Dan Gohmand27a0e02008-11-19 23:18:57 +0000588 SU->isScheduled = true;
589 AvailableQueue.ScheduledNode(SU);
590}
591
592/// ListScheduleTopDown - The main loop of list scheduling for top-down
593/// schedulers.
594void SchedulePostRATDList::ListScheduleTopDown() {
595 unsigned CurCycle = 0;
596
Dan Gohmana91eb052009-02-10 23:27:53 +0000597 // Release any successors of the special Entry node.
598 ReleaseSuccessors(&EntrySU);
599
Dan Gohmand27a0e02008-11-19 23:18:57 +0000600 // All leaves to Available queue.
601 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
602 // It is available if it has no predecessors.
603 if (SUnits[i].Preds.empty()) {
604 AvailableQueue.push(&SUnits[i]);
605 SUnits[i].isAvailable = true;
606 }
607 }
Dan Gohmana91eb052009-02-10 23:27:53 +0000608
David Goodwin745d9d32009-08-12 21:47:46 +0000609 // In any cycle where we can't schedule any instructions, we must
610 // stall or emit a noop, depending on the target.
Benjamin Kramer0db71af2009-09-06 12:10:17 +0000611 bool CycleHasInsts = false;
David Goodwin745d9d32009-08-12 21:47:46 +0000612
Dan Gohmand27a0e02008-11-19 23:18:57 +0000613 // While Available queue is not empty, grab the node with the highest
614 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman99603bb2009-01-16 01:33:36 +0000615 std::vector<SUnit*> NotReady;
Dan Gohmand27a0e02008-11-19 23:18:57 +0000616 Sequence.reserve(SUnits.size());
617 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
618 // Check to see if any of the pending instructions are ready to issue. If
619 // so, add them to the available queue.
Dan Gohman6b2ee8f2008-12-16 03:25:46 +0000620 unsigned MinDepth = ~0u;
Dan Gohmand27a0e02008-11-19 23:18:57 +0000621 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman6b2ee8f2008-12-16 03:25:46 +0000622 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohmand27a0e02008-11-19 23:18:57 +0000623 AvailableQueue.push(PendingQueue[i]);
624 PendingQueue[i]->isAvailable = true;
625 PendingQueue[i] = PendingQueue.back();
626 PendingQueue.pop_back();
627 --i; --e;
Dan Gohman6b2ee8f2008-12-16 03:25:46 +0000628 } else if (PendingQueue[i]->getDepth() < MinDepth)
629 MinDepth = PendingQueue[i]->getDepth();
Dan Gohmand27a0e02008-11-19 23:18:57 +0000630 }
David Goodwin391efe02009-08-11 17:35:23 +0000631
David Goodwin387579f2009-08-11 17:56:42 +0000632 DEBUG(errs() << "\n*** Examining Available\n";
633 LatencyPriorityQueue q = AvailableQueue;
634 while (!q.empty()) {
635 SUnit *su = q.pop();
636 errs() << "Height " << su->getHeight() << ": ";
637 su->dump(this);
638 });
David Goodwin391efe02009-08-11 17:35:23 +0000639
Dan Gohman99603bb2009-01-16 01:33:36 +0000640 SUnit *FoundSUnit = 0;
641
642 bool HasNoopHazards = false;
643 while (!AvailableQueue.empty()) {
644 SUnit *CurSUnit = AvailableQueue.pop();
645
646 ScheduleHazardRecognizer::HazardType HT =
647 HazardRec->getHazardType(CurSUnit);
648 if (HT == ScheduleHazardRecognizer::NoHazard) {
649 FoundSUnit = CurSUnit;
650 break;
651 }
652
653 // Remember if this is a noop hazard.
654 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
655
656 NotReady.push_back(CurSUnit);
657 }
658
659 // Add the nodes that aren't ready back onto the available list.
660 if (!NotReady.empty()) {
661 AvailableQueue.push_all(NotReady);
662 NotReady.clear();
663 }
664
Dan Gohmand27a0e02008-11-19 23:18:57 +0000665 // If we found a node to schedule, do it now.
666 if (FoundSUnit) {
667 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman99603bb2009-01-16 01:33:36 +0000668 HazardRec->EmitInstruction(FoundSUnit);
Benjamin Kramer0db71af2009-09-06 12:10:17 +0000669 CycleHasInsts = true;
Dan Gohmand27a0e02008-11-19 23:18:57 +0000670
David Goodwin5ab4fd42009-08-10 15:55:25 +0000671 // If we are using the target-specific hazards, then don't
672 // advance the cycle time just because we schedule a node. If
673 // the target allows it we can schedule multiple nodes in the
674 // same cycle.
675 if (!EnablePostRAHazardAvoidance) {
676 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
677 ++CurCycle;
678 }
Dan Gohman99603bb2009-01-16 01:33:36 +0000679 } else {
Benjamin Kramer0db71af2009-09-06 12:10:17 +0000680 if (CycleHasInsts) {
David Goodwin745d9d32009-08-12 21:47:46 +0000681 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
682 HazardRec->AdvanceCycle();
683 } else if (!HasNoopHazards) {
684 // Otherwise, we have a pipeline stall, but no other problem,
685 // just advance the current cycle and try again.
686 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
687 HazardRec->AdvanceCycle();
688 ++NumStalls;
689 } else {
690 // Otherwise, we have no instructions to issue and we have instructions
691 // that will fault if we don't do this right. This is the case for
692 // processors without pipeline interlocks and other cases.
693 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
694 HazardRec->EmitNoop();
695 Sequence.push_back(0); // NULL here means noop
696 ++NumNoops;
697 }
698
Dan Gohman99603bb2009-01-16 01:33:36 +0000699 ++CurCycle;
Benjamin Kramer0db71af2009-09-06 12:10:17 +0000700 CycleHasInsts = false;
Dan Gohmand27a0e02008-11-19 23:18:57 +0000701 }
702 }
703
704#ifndef NDEBUG
Dan Gohmanf6e4a002008-11-20 01:26:25 +0000705 VerifySchedule(/*isBottomUp=*/false);
Dan Gohmand27a0e02008-11-19 23:18:57 +0000706#endif
707}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708
709//===----------------------------------------------------------------------===//
710// Public Constructor Functions
711//===----------------------------------------------------------------------===//
712
Evan Cheng86e24b02009-10-16 21:06:15 +0000713FunctionPass *llvm::createPostRAScheduler(CodeGenOpt::Level OptLevel) {
714 return new PostRAScheduler(OptLevel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715}