blob: b2e9c15b68bcb094a240db621b00624b3deba788 [file] [log] [blame]
Dan Gohman23785a12008-08-12 17:42:33 +00001//===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
Evan Chengd38c22b2006-05-11 23:55:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengd38c22b2006-05-11 23:55:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This implements bottom-up and top-down register pressure reduction list
11// schedulers, using standard algorithms. The basic approach uses a priority
12// queue of available nodes to schedule. One at a time, nodes are taken from
13// the priority queue (thus in priority order), checked for legality to
14// schedule, and emitted if legal.
15//
16//===----------------------------------------------------------------------===//
17
Dale Johannesen2182f062007-07-13 17:13:54 +000018#define DEBUG_TYPE "pre-RA-sched"
Dan Gohman483377c2009-02-06 17:22:58 +000019#include "ScheduleDAGSDNodes.h"
Chris Lattner3b9f02a2010-04-07 05:20:54 +000020#include "llvm/InlineAsm.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000021#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman619ef482009-01-15 19:20:50 +000022#include "llvm/CodeGen/SelectionDAGISel.h"
Andrew Trick10ffc2b2010-12-24 05:03:26 +000023#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohman3a4be0f2008-02-10 18:45:23 +000024#include "llvm/Target/TargetRegisterInfo.h"
Owen Anderson8c2c1e92006-05-12 06:33:49 +000025#include "llvm/Target/TargetData.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000026#include "llvm/Target/TargetMachine.h"
27#include "llvm/Target/TargetInstrInfo.h"
Evan Chenga77f3d32010-07-21 06:09:07 +000028#include "llvm/Target/TargetLowering.h"
Evan Cheng5924bf72007-09-25 01:54:36 +000029#include "llvm/ADT/SmallSet.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000030#include "llvm/ADT/Statistic.h"
Roman Levenstein6b371142008-04-29 09:07:59 +000031#include "llvm/ADT/STLExtras.h"
Chris Lattner3b9f02a2010-04-07 05:20:54 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000035#include <climits>
Evan Chengd38c22b2006-05-11 23:55:42 +000036using namespace llvm;
37
Dan Gohmanfd227e92008-03-25 17:10:29 +000038STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
Evan Cheng79e97132007-10-05 01:39:18 +000039STATISTIC(NumUnfolds, "Number of nodes unfolded");
Evan Cheng1ec79b42007-09-27 07:09:03 +000040STATISTIC(NumDups, "Number of duplicated nodes");
Evan Chengb2c42c62009-01-12 03:19:55 +000041STATISTIC(NumPRCopies, "Number of physical register copies");
Evan Cheng1ec79b42007-09-27 07:09:03 +000042
Jim Laskey95eda5b2006-08-01 14:21:23 +000043static RegisterScheduler
44 burrListDAGScheduler("list-burr",
Dan Gohman9c4b7d52008-10-14 20:25:08 +000045 "Bottom-up register reduction list scheduling",
Jim Laskey95eda5b2006-08-01 14:21:23 +000046 createBURRListDAGScheduler);
47static RegisterScheduler
48 tdrListrDAGScheduler("list-tdrr",
Dan Gohman9c4b7d52008-10-14 20:25:08 +000049 "Top-down register reduction list scheduling",
Jim Laskey95eda5b2006-08-01 14:21:23 +000050 createTDRRListDAGScheduler);
Bill Wendling8cbc25d2010-01-23 10:26:57 +000051static RegisterScheduler
52 sourceListDAGScheduler("source",
53 "Similar to list-burr but schedules in source "
54 "order when possible",
55 createSourceListDAGScheduler);
Jim Laskey95eda5b2006-08-01 14:21:23 +000056
Evan Chengbdd062d2010-05-20 06:13:19 +000057static RegisterScheduler
Evan Cheng725211e2010-05-21 00:42:32 +000058 hybridListDAGScheduler("list-hybrid",
Evan Cheng37b740c2010-07-24 00:39:05 +000059 "Bottom-up register pressure aware list scheduling "
60 "which tries to balance latency and register pressure",
Evan Chengbdd062d2010-05-20 06:13:19 +000061 createHybridListDAGScheduler);
62
Evan Cheng37b740c2010-07-24 00:39:05 +000063static RegisterScheduler
64 ILPListDAGScheduler("list-ilp",
65 "Bottom-up register pressure aware list scheduling "
66 "which tries to balance ILP and register pressure",
67 createILPListDAGScheduler);
68
Andrew Trick47ff14b2011-01-21 05:51:33 +000069static cl::opt<bool> DisableSchedCycles(
Andrew Trickbd428ec2011-01-21 06:19:05 +000070 "disable-sched-cycles", cl::Hidden, cl::init(false),
Andrew Trick47ff14b2011-01-21 05:51:33 +000071 cl::desc("Disable cycle-level precision during preRA scheduling"));
Andrew Trick10ffc2b2010-12-24 05:03:26 +000072
Andrew Trick641e2d42011-03-05 08:00:22 +000073// Temporary sched=list-ilp flags until the heuristics are robust.
74static cl::opt<bool> DisableSchedRegPressure(
75 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
76 cl::desc("Disable regpressure priority in sched=list-ilp"));
77static cl::opt<bool> DisableSchedLiveUses(
Andrew Trickdd017322011-03-06 00:03:32 +000078 "disable-sched-live-uses", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000079 cl::desc("Disable live use priority in sched=list-ilp"));
Andrew Trick2ad0b372011-04-07 19:54:57 +000080static cl::opt<bool> DisableSchedVRegCycle(
81 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
82 cl::desc("Disable virtual register cycle interference checks"));
Andrew Trick641e2d42011-03-05 08:00:22 +000083static cl::opt<bool> DisableSchedStalls(
Andrew Trickdd017322011-03-06 00:03:32 +000084 "disable-sched-stalls", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000085 cl::desc("Disable no-stall priority in sched=list-ilp"));
86static cl::opt<bool> DisableSchedCriticalPath(
87 "disable-sched-critical-path", cl::Hidden, cl::init(false),
88 cl::desc("Disable critical path priority in sched=list-ilp"));
89static cl::opt<bool> DisableSchedHeight(
90 "disable-sched-height", cl::Hidden, cl::init(false),
91 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
92
93static cl::opt<int> MaxReorderWindow(
94 "max-sched-reorder", cl::Hidden, cl::init(6),
95 cl::desc("Number of instructions to allow ahead of the critical path "
96 "in sched=list-ilp"));
97
98static cl::opt<unsigned> AvgIPC(
99 "sched-avg-ipc", cl::Hidden, cl::init(1),
100 cl::desc("Average inst/cycle whan no target itinerary exists."));
101
102#ifndef NDEBUG
103namespace {
104 // For sched=list-ilp, Count the number of times each factor comes into play.
Andrew Trick1b60ad62011-04-12 20:14:07 +0000105 enum { FactPressureDiff, FactRegUses, FactHeight, FactDepth, FactStatic,
106 FactOther, NumFactors };
Andrew Trick641e2d42011-03-05 08:00:22 +0000107}
108static const char *FactorName[NumFactors] =
Andrew Trick1b60ad62011-04-12 20:14:07 +0000109{"PressureDiff", "RegUses", "Height", "Depth","Static", "Other"};
Andrew Trick641e2d42011-03-05 08:00:22 +0000110static int FactorCount[NumFactors];
111#endif //!NDEBUG
112
Evan Chengd38c22b2006-05-11 23:55:42 +0000113namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +0000114//===----------------------------------------------------------------------===//
115/// ScheduleDAGRRList - The actual register reduction list scheduler
116/// implementation. This supports both top-down and bottom-up scheduling.
117///
Nick Lewycky02d5f772009-10-25 06:33:48 +0000118class ScheduleDAGRRList : public ScheduleDAGSDNodes {
Evan Chengd38c22b2006-05-11 23:55:42 +0000119private:
120 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
121 /// it is top-down.
122 bool isBottomUp;
Evan Cheng2c977312008-07-01 18:05:03 +0000123
Evan Chengbdd062d2010-05-20 06:13:19 +0000124 /// NeedLatency - True if the scheduler will make use of latency information.
125 ///
126 bool NeedLatency;
127
Evan Chengd38c22b2006-05-11 23:55:42 +0000128 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +0000129 SchedulingPriorityQueue *AvailableQueue;
130
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000131 /// PendingQueue - This contains all of the instructions whose operands have
132 /// been issued, but their results are not ready yet (due to the latency of
133 /// the operation). Once the operands becomes available, the instruction is
134 /// added to the AvailableQueue.
135 std::vector<SUnit*> PendingQueue;
136
137 /// HazardRec - The hazard recognizer to use.
138 ScheduleHazardRecognizer *HazardRec;
139
Andrew Trick528fad92010-12-23 05:42:20 +0000140 /// CurCycle - The current scheduler state corresponds to this cycle.
141 unsigned CurCycle;
142
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000143 /// MinAvailableCycle - Cycle of the soonest available instruction.
144 unsigned MinAvailableCycle;
145
Andrew Trick641e2d42011-03-05 08:00:22 +0000146 /// IssueCount - Count instructions issued in this cycle
147 /// Currently valid only for bottom-up scheduling.
148 unsigned IssueCount;
149
Dan Gohmanc07f6862008-09-23 18:50:48 +0000150 /// LiveRegDefs - A set of physical registers and their definition
Evan Cheng5924bf72007-09-25 01:54:36 +0000151 /// that are "live". These nodes must be scheduled before any other nodes that
152 /// modifies the registers can be scheduled.
Dan Gohmanc07f6862008-09-23 18:50:48 +0000153 unsigned NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000154 std::vector<SUnit*> LiveRegDefs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000155 std::vector<SUnit*> LiveRegGens;
Evan Cheng5924bf72007-09-25 01:54:36 +0000156
Dan Gohmanad2134d2008-11-25 00:52:40 +0000157 /// Topo - A topological ordering for SUnits which permits fast IsReachable
158 /// and similar queries.
159 ScheduleDAGTopologicalSort Topo;
160
Evan Chengd38c22b2006-05-11 23:55:42 +0000161public:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000162 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
163 SchedulingPriorityQueue *availqueue,
164 CodeGenOpt::Level OptLevel)
165 : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
166 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
167 Topo(SUnits) {
168
169 const TargetMachine &tm = mf.getTarget();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000170 if (DisableSchedCycles || !NeedLatency)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000171 HazardRec = new ScheduleHazardRecognizer();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000172 else
173 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000174 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000175
176 ~ScheduleDAGRRList() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000177 delete HazardRec;
Evan Chengd38c22b2006-05-11 23:55:42 +0000178 delete AvailableQueue;
179 }
180
181 void Schedule();
182
Andrew Trick9ccce772011-01-14 21:11:41 +0000183 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
184
Roman Levenstein733a4d62008-03-26 11:23:38 +0000185 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000186 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
187 return Topo.IsReachable(SU, TargetSU);
188 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000189
Dan Gohman60d68442009-01-29 19:49:27 +0000190 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000191 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000192 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
193 return Topo.WillCreateCycle(SU, TargetSU);
194 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000195
Dan Gohman2d170892008-12-09 22:54:47 +0000196 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000197 /// This returns true if this is a new predecessor.
198 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000199 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000200 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000201 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000202 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000203
Dan Gohman2d170892008-12-09 22:54:47 +0000204 /// RemovePred - removes a predecessor edge from SUnit SU.
205 /// This returns true if an edge was removed.
206 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000207 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000208 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000209 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000210 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000211
Evan Chengd38c22b2006-05-11 23:55:42 +0000212private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000213 bool isReady(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000214 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000215 AvailableQueue->isReady(SU);
216 }
217
Dan Gohman60d68442009-01-29 19:49:27 +0000218 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000219 void ReleasePredecessors(SUnit *SU);
Dan Gohman60d68442009-01-29 19:49:27 +0000220 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
Dan Gohmanb9543432009-02-10 23:27:53 +0000221 void ReleaseSuccessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000222 void ReleasePending();
223 void AdvanceToCycle(unsigned NextCycle);
224 void AdvancePastStalls(SUnit *SU);
225 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000226 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000227 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000228 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000229 void RestoreHazardCheckerBottomUp();
230 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000231 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000232 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
233 const TargetRegisterClass*,
234 const TargetRegisterClass*,
235 SmallVector<SUnit*, 2>&);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000236 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000237
Andrew Trick528fad92010-12-23 05:42:20 +0000238 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000239 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000240
Andrew Trick528fad92010-12-23 05:42:20 +0000241 void ScheduleNodeTopDown(SUnit*);
242 void ListScheduleTopDown();
243
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000244
245 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000246 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000247 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000248 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000249 SUnit *NewNode = NewSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000250 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000251 if (NewNode->NodeNum >= NumSUnits)
252 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000253 return NewNode;
254 }
255
Roman Levenstein733a4d62008-03-26 11:23:38 +0000256 /// CreateClone - Creates a new SUnit from an existing one.
257 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000258 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000259 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000260 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000261 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000262 if (NewNode->NodeNum >= NumSUnits)
263 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000264 return NewNode;
265 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000266
Evan Chengbdd062d2010-05-20 06:13:19 +0000267 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
268 /// need actual latency information but the hybrid scheduler does.
269 bool ForceUnitLatencies() const {
270 return !NeedLatency;
271 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000272};
273} // end anonymous namespace
274
275
276/// Schedule - Schedule the DAG using list scheduling.
277void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000278 DEBUG(dbgs()
279 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000280 << " '" << BB->getName() << "' **********\n");
Andrew Trick641e2d42011-03-05 08:00:22 +0000281#ifndef NDEBUG
282 for (int i = 0; i < NumFactors; ++i) {
283 FactorCount[i] = 0;
284 }
285#endif //!NDEBUG
Evan Cheng5924bf72007-09-25 01:54:36 +0000286
Andrew Trick528fad92010-12-23 05:42:20 +0000287 CurCycle = 0;
Andrew Trick641e2d42011-03-05 08:00:22 +0000288 IssueCount = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000289 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000290 NumLiveRegs = 0;
Andrew Trick2085a962010-12-21 22:25:04 +0000291 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
Andrew Tricka52f3252010-12-23 04:16:14 +0000292 LiveRegGens.resize(TRI->getNumRegs(), NULL);
Evan Cheng5924bf72007-09-25 01:54:36 +0000293
Dan Gohman04543e72008-12-23 18:36:58 +0000294 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000295 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000296
Evan Chengd38c22b2006-05-11 23:55:42 +0000297 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000298 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000299 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000300
Dan Gohman46520a22008-06-21 19:18:17 +0000301 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000302
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000303 HazardRec->Reset();
304
Evan Chengd38c22b2006-05-11 23:55:42 +0000305 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
306 if (isBottomUp)
307 ListScheduleBottomUp();
308 else
309 ListScheduleTopDown();
Andrew Trick2085a962010-12-21 22:25:04 +0000310
Andrew Trick641e2d42011-03-05 08:00:22 +0000311#ifndef NDEBUG
312 for (int i = 0; i < NumFactors; ++i) {
313 DEBUG(dbgs() << FactorName[i] << "\t" << FactorCount[i] << "\n");
314 }
315#endif // !NDEBUG
Evan Chengd38c22b2006-05-11 23:55:42 +0000316 AvailableQueue->releaseState();
Evan Chengafed73e2006-05-12 01:58:24 +0000317}
Evan Chengd38c22b2006-05-11 23:55:42 +0000318
319//===----------------------------------------------------------------------===//
320// Bottom-Up Scheduling
321//===----------------------------------------------------------------------===//
322
Evan Chengd38c22b2006-05-11 23:55:42 +0000323/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000324/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000325void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000326 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000327
Evan Chengd38c22b2006-05-11 23:55:42 +0000328#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000329 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000330 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000331 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000332 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000333 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000334 }
335#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000336 --PredSU->NumSuccsLeft;
337
Evan Chengbdd062d2010-05-20 06:13:19 +0000338 if (!ForceUnitLatencies()) {
339 // Updating predecessor's height. This is now the cycle when the
340 // predecessor can be scheduled without causing a pipeline stall.
341 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
342 }
343
Dan Gohmanb9543432009-02-10 23:27:53 +0000344 // If all the node's successors are scheduled, this node is ready
345 // to be scheduled. Ignore the special EntrySU node.
346 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000347 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000348
349 unsigned Height = PredSU->getHeight();
350 if (Height < MinAvailableCycle)
351 MinAvailableCycle = Height;
352
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000353 if (isReady(PredSU)) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000354 AvailableQueue->push(PredSU);
355 }
356 // CapturePred and others may have left the node in the pending queue, avoid
357 // adding it twice.
358 else if (!PredSU->isPending) {
359 PredSU->isPending = true;
360 PendingQueue.push_back(PredSU);
361 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000362 }
363}
364
Andrew Trick033efdf2010-12-23 03:15:51 +0000365/// Call ReleasePred for each predecessor, then update register live def/gen.
366/// Always update LiveRegDefs for a register dependence even if the current SU
367/// also defines the register. This effectively create one large live range
368/// across a sequence of two-address node. This is important because the
369/// entire chain must be scheduled together. Example:
370///
371/// flags = (3) add
372/// flags = (2) addc flags
373/// flags = (1) addc flags
374///
375/// results in
376///
377/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000378/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000379///
380/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
381/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000382void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000383 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000384 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000385 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000386 ReleasePred(SU, &*I);
387 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000388 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000389 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000390 // clobber the register is scheduled between the predecessor and
391 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000392 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000393 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
394 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000395 LiveRegDefs[I->getReg()] = I->getSUnit();
396 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000397 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000398 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000399 }
400 }
401 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000402}
403
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000404/// Check to see if any of the pending instructions are ready to issue. If
405/// so, add them to the available queue.
406void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000407 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000408 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
409 return;
410 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000411
412 // If the available queue is empty, it is safe to reset MinAvailableCycle.
413 if (AvailableQueue->empty())
414 MinAvailableCycle = UINT_MAX;
415
416 // Check to see if any of the pending instructions are ready to issue. If
417 // so, add them to the available queue.
418 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
419 unsigned ReadyCycle =
420 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
421 if (ReadyCycle < MinAvailableCycle)
422 MinAvailableCycle = ReadyCycle;
423
424 if (PendingQueue[i]->isAvailable) {
425 if (!isReady(PendingQueue[i]))
426 continue;
427 AvailableQueue->push(PendingQueue[i]);
428 }
429 PendingQueue[i]->isPending = false;
430 PendingQueue[i] = PendingQueue.back();
431 PendingQueue.pop_back();
432 --i; --e;
433 }
434}
435
436/// Move the scheduler state forward by the specified number of Cycles.
437void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
438 if (NextCycle <= CurCycle)
439 return;
440
Andrew Trick641e2d42011-03-05 08:00:22 +0000441 IssueCount = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000442 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000443 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000444 // Bypass lots of virtual calls in case of long latency.
445 CurCycle = NextCycle;
446 }
447 else {
448 for (; CurCycle != NextCycle; ++CurCycle) {
449 if (isBottomUp)
450 HazardRec->RecedeCycle();
451 else
452 HazardRec->AdvanceCycle();
453 }
454 }
455 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
456 // available Q to release pending nodes at least once before popping.
457 ReleasePending();
458}
459
460/// Move the scheduler state forward until the specified node's dependents are
461/// ready and can be scheduled with no resource conflicts.
462void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000463 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000464 return;
465
466 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
467
468 // Bump CurCycle to account for latency. We assume the latency of other
469 // available instructions may be hidden by the stall (not a full pipe stall).
470 // This updates the hazard recognizer's cycle before reserving resources for
471 // this instruction.
472 AdvanceToCycle(ReadyCycle);
473
474 // Calls are scheduled in their preceding cycle, so don't conflict with
475 // hazards from instructions after the call. EmitNode will reset the
476 // scoreboard state before emitting the call.
477 if (isBottomUp && SU->isCall)
478 return;
479
480 // FIXME: For resource conflicts in very long non-pipelined stages, we
481 // should probably skip ahead here to avoid useless scoreboard checks.
482 int Stalls = 0;
483 while (true) {
484 ScheduleHazardRecognizer::HazardType HT =
485 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
486
487 if (HT == ScheduleHazardRecognizer::NoHazard)
488 break;
489
490 ++Stalls;
491 }
492 AdvanceToCycle(CurCycle + Stalls);
493}
494
495/// Record this SUnit in the HazardRecognizer.
496/// Does not update CurCycle.
497void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000498 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000499 return;
500
501 // Check for phys reg copy.
502 if (!SU->getNode())
503 return;
504
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000505 switch (SU->getNode()->getOpcode()) {
506 default:
507 assert(SU->getNode()->isMachineOpcode() &&
508 "This target-independent node should not be scheduled.");
509 break;
510 case ISD::MERGE_VALUES:
511 case ISD::TokenFactor:
512 case ISD::CopyToReg:
513 case ISD::CopyFromReg:
514 case ISD::EH_LABEL:
515 // Noops don't affect the scoreboard state. Copies are likely to be
516 // removed.
517 return;
518 case ISD::INLINEASM:
519 // For inline asm, clear the pipeline state.
520 HazardRec->Reset();
521 return;
522 }
523 if (isBottomUp && SU->isCall) {
524 // Calls are scheduled with their preceding instructions. For bottom-up
525 // scheduling, clear the pipeline state before emitting.
526 HazardRec->Reset();
527 }
528
529 HazardRec->EmitInstruction(SU);
530
531 if (!isBottomUp && SU->isCall) {
532 HazardRec->Reset();
533 }
534}
535
Dan Gohmanb9543432009-02-10 23:27:53 +0000536/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
537/// count of its predecessors. If a predecessor pending count is zero, add it to
538/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000539void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Andrew Trick1b60ad62011-04-12 20:14:07 +0000540 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000541 DEBUG(SU->dump(this));
542
Evan Chengbdd062d2010-05-20 06:13:19 +0000543#ifndef NDEBUG
544 if (CurCycle < SU->getHeight())
Andrew Trick1b60ad62011-04-12 20:14:07 +0000545 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
Evan Chengbdd062d2010-05-20 06:13:19 +0000546#endif
547
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000548 // FIXME: Do not modify node height. It may interfere with
549 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
Eric Christopher1b4b1e52011-03-21 18:06:21 +0000550 // node its ready cycle can aid heuristics, and after scheduling it can
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000551 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000552 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000553
554 // Reserve resources for the scheduled intruction.
555 EmitNode(SU);
556
Dan Gohmanb9543432009-02-10 23:27:53 +0000557 Sequence.push_back(SU);
558
Evan Cheng28590382010-07-21 23:53:58 +0000559 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000560
Andrew Trick641e2d42011-03-05 08:00:22 +0000561 // If HazardRec is disabled, and each inst counts as one cycle, then
Andrew Trick1b60ad62011-04-12 20:14:07 +0000562 // advance CurCycle before ReleasePredecessors to avoid useles pushed to
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000563 // PendingQueue for schedulers that implement HasReadyFilter.
Andrew Trick641e2d42011-03-05 08:00:22 +0000564 if (!HazardRec->isEnabled() && AvgIPC < 2)
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000565 AdvanceToCycle(CurCycle + 1);
566
Andrew Trick033efdf2010-12-23 03:15:51 +0000567 // Update liveness of predecessors before successors to avoid treating a
568 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000569 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000570
571 // Release all the implicit physical register defs that are live.
572 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
573 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000574 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
575 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
576 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
577 --NumLiveRegs;
578 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000579 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000580 }
581 }
582
Evan Chengd38c22b2006-05-11 23:55:42 +0000583 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000584
585 // Conditions under which the scheduler should eagerly advance the cycle:
586 // (1) No available instructions
587 // (2) All pipelines full, so available instructions must have hazards.
588 //
Andrew Trick1b60ad62011-04-12 20:14:07 +0000589 // If HazardRec is disabled, the cycle was advanced earlier.
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000590 //
591 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
Andrew Trick1b60ad62011-04-12 20:14:07 +0000592 ++IssueCount;
593 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
594 || (!HazardRec->isEnabled() && AvgIPC > 1 && IssueCount == AvgIPC)
595 || AvailableQueue->empty())
596 AdvanceToCycle(CurCycle + 1);
Evan Chengd38c22b2006-05-11 23:55:42 +0000597}
598
Evan Cheng5924bf72007-09-25 01:54:36 +0000599/// CapturePred - This does the opposite of ReleasePred. Since SU is being
600/// unscheduled, incrcease the succ left count of its predecessors. Remove
601/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000602void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000603 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000604 if (PredSU->isAvailable) {
605 PredSU->isAvailable = false;
606 if (!PredSU->isPending)
607 AvailableQueue->remove(PredSU);
608 }
609
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000610 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000611 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000612}
613
614/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
615/// its predecessor states to reflect the change.
616void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000617 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000618 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000619
Evan Cheng5924bf72007-09-25 01:54:36 +0000620 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
621 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000622 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000623 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000624 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000625 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000626 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000627 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000628 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000629 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000630 }
631 }
632
633 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
634 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000635 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000636 // This becomes the nearest def. Note that an earlier def may still be
637 // pending if this is a two-address node.
638 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000639 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000640 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000641 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000642 if (LiveRegGens[I->getReg()] == NULL ||
643 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
644 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000645 }
646 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000647 if (SU->getHeight() < MinAvailableCycle)
648 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000649
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000650 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000651 SU->isScheduled = false;
652 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000653 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000654 // Don't make available until backtracking is complete.
655 SU->isPending = true;
656 PendingQueue.push_back(SU);
657 }
658 else {
659 AvailableQueue->push(SU);
660 }
Evan Cheng28590382010-07-21 23:53:58 +0000661 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000662}
663
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000664/// After backtracking, the hazard checker needs to be restored to a state
665/// corresponding the the current cycle.
666void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
667 HazardRec->Reset();
668
669 unsigned LookAhead = std::min((unsigned)Sequence.size(),
670 HazardRec->getMaxLookAhead());
671 if (LookAhead == 0)
672 return;
673
674 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
675 unsigned HazardCycle = (*I)->getHeight();
676 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
677 SUnit *SU = *I;
678 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
679 HazardRec->RecedeCycle();
680 }
681 EmitNode(SU);
682 }
683}
684
Evan Cheng8e136a92007-09-26 21:36:17 +0000685/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000686/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000687void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
688 SUnit *OldSU = Sequence.back();
689 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000690 Sequence.pop_back();
691 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000692 // Don't try to remove SU from AvailableQueue.
693 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000694 // FIXME: use ready cycle instead of height
695 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000696 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000697 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000698 if (OldSU == BtSU)
699 break;
700 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000701 }
702
Dan Gohman60d68442009-01-29 19:49:27 +0000703 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000704
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000705 RestoreHazardCheckerBottomUp();
706
Andrew Trick5ce945c2010-12-24 07:10:19 +0000707 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000708
Evan Cheng1ec79b42007-09-27 07:09:03 +0000709 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000710}
711
Evan Cheng3b245872010-02-05 01:27:11 +0000712static bool isOperandOf(const SUnit *SU, SDNode *N) {
713 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000714 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000715 if (SUNode->isOperandOf(N))
716 return true;
717 }
718 return false;
719}
720
Evan Cheng5924bf72007-09-25 01:54:36 +0000721/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
722/// successors to the newly created node.
723SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000724 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000725 if (!N)
726 return NULL;
727
Andrew Trickc9405662010-12-24 06:46:50 +0000728 if (SU->getNode()->getGluedNode())
729 return NULL;
730
Evan Cheng79e97132007-10-05 01:39:18 +0000731 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000732 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000733 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000734 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000735 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000736 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000737 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000738 TryUnfold = true;
739 }
Evan Cheng79e97132007-10-05 01:39:18 +0000740 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000741 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000742 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000743 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000744 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000745 }
746
747 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000748 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000749 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000750 return NULL;
751
Evan Chengbdd062d2010-05-20 06:13:19 +0000752 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000753 assert(NewNodes.size() == 2 && "Expected a load folding node!");
754
755 N = NewNodes[1];
756 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000757 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000758 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000759 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000760 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
761 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000762 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000763
Dan Gohmane52e0892008-11-11 21:34:44 +0000764 // LoadNode may already exist. This can happen when there is another
765 // load from the same location and producing the same type of value
766 // but it has different alignment or volatileness.
767 bool isNewLoad = true;
768 SUnit *LoadSU;
769 if (LoadNode->getNodeId() != -1) {
770 LoadSU = &SUnits[LoadNode->getNodeId()];
771 isNewLoad = false;
772 } else {
773 LoadSU = CreateNewSUnit(LoadNode);
774 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000775
776 InitNumRegDefsLeft(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000777 ComputeLatency(LoadSU);
778 }
779
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000780 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000781 assert(N->getNodeId() == -1 && "Node already inserted!");
782 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000783
Dan Gohman17059682008-07-17 19:10:17 +0000784 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000785 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000786 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000787 NewSU->isTwoAddress = true;
788 break;
789 }
790 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000791 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000792 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +0000793
794 InitNumRegDefsLeft(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000795 ComputeLatency(NewSU);
796
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000797 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000798 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000799 SmallVector<SDep, 4> ChainSuccs;
800 SmallVector<SDep, 4> LoadPreds;
801 SmallVector<SDep, 4> NodePreds;
802 SmallVector<SDep, 4> NodeSuccs;
803 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
804 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000805 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000806 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000807 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000808 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000809 else
Dan Gohman2d170892008-12-09 22:54:47 +0000810 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000811 }
812 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
813 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000814 if (I->isCtrl())
815 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000816 else
Dan Gohman2d170892008-12-09 22:54:47 +0000817 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000818 }
819
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000820 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000821 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
822 const SDep &Pred = ChainPreds[i];
823 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000824 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000825 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000826 }
Evan Cheng79e97132007-10-05 01:39:18 +0000827 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000828 const SDep &Pred = LoadPreds[i];
829 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000830 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000831 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000832 }
833 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000834 const SDep &Pred = NodePreds[i];
835 RemovePred(SU, Pred);
836 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000837 }
838 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000839 SDep D = NodeSuccs[i];
840 SUnit *SuccDep = D.getSUnit();
841 D.setSUnit(SU);
842 RemovePred(SuccDep, D);
843 D.setSUnit(NewSU);
844 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000845 // Balance register pressure.
846 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
847 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
848 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +0000849 }
850 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000851 SDep D = ChainSuccs[i];
852 SUnit *SuccDep = D.getSUnit();
853 D.setSUnit(SU);
854 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000855 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000856 D.setSUnit(LoadSU);
857 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000858 }
Andrew Trick2085a962010-12-21 22:25:04 +0000859 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000860
861 // Add a data dependency to reflect that NewSU reads the value defined
862 // by LoadSU.
863 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000864
Evan Cheng91e0fc92007-12-18 08:42:10 +0000865 if (isNewLoad)
866 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000867 AvailableQueue->addNode(NewSU);
868
869 ++NumUnfolds;
870
871 if (NewSU->NumSuccsLeft == 0) {
872 NewSU->isAvailable = true;
873 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000874 }
875 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000876 }
877
Evan Chengbdd062d2010-05-20 06:13:19 +0000878 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000879 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000880
881 // New SUnit has the exact same predecessors.
882 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
883 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000884 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000885 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000886
887 // Only copy scheduled successors. Cut them from old node's successor
888 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000889 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000890 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
891 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000892 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000893 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000894 SUnit *SuccSU = I->getSUnit();
895 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000896 SDep D = *I;
897 D.setSUnit(NewSU);
898 AddPred(SuccSU, D);
899 D.setSUnit(SU);
900 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000901 }
902 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000903 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000904 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000905
906 AvailableQueue->updateNode(SU);
907 AvailableQueue->addNode(NewSU);
908
Evan Cheng1ec79b42007-09-27 07:09:03 +0000909 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000910 return NewSU;
911}
912
Evan Chengb2c42c62009-01-12 03:19:55 +0000913/// InsertCopiesAndMoveSuccs - Insert register copies and move all
914/// scheduled successors of the given SUnit to the last copy.
915void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
916 const TargetRegisterClass *DestRC,
917 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000918 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000919 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000920 CopyFromSU->CopySrcRC = SrcRC;
921 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000922
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000923 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000924 CopyToSU->CopySrcRC = DestRC;
925 CopyToSU->CopyDstRC = SrcRC;
926
927 // Only copy scheduled successors. Cut them from old node's successor
928 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000929 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000930 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
931 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000932 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000933 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000934 SUnit *SuccSU = I->getSUnit();
935 if (SuccSU->isScheduled) {
936 SDep D = *I;
937 D.setSUnit(CopyToSU);
938 AddPred(SuccSU, D);
939 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000940 }
Andrew Trick13acae02011-03-23 20:42:39 +0000941 else {
942 // Avoid scheduling the def-side copy before other successors. Otherwise
943 // we could introduce another physreg interference on the copy and
944 // continue inserting copies indefinitely.
945 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
946 /*Reg=*/0, /*isNormalMemory=*/false,
947 /*isMustAlias=*/false, /*isArtificial=*/true);
948 AddPred(SuccSU, D);
949 }
Evan Cheng8e136a92007-09-26 21:36:17 +0000950 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000951 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000952 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000953
Dan Gohman2d170892008-12-09 22:54:47 +0000954 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
955 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +0000956
957 AvailableQueue->updateNode(SU);
958 AvailableQueue->addNode(CopyFromSU);
959 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000960 Copies.push_back(CopyFromSU);
961 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000962
Evan Chengb2c42c62009-01-12 03:19:55 +0000963 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000964}
965
966/// getPhysicalRegisterVT - Returns the ValueType of the physical register
967/// definition of the specified node.
968/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +0000969static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +0000970 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +0000971 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000972 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000973 unsigned NumRes = TID.getNumDefs();
974 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000975 if (Reg == *ImpDef)
976 break;
977 ++NumRes;
978 }
979 return N->getValueType(NumRes);
980}
981
Evan Chengb8905c42009-03-04 01:41:49 +0000982/// CheckForLiveRegDef - Return true and update live register vector if the
983/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000984static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +0000985 std::vector<SUnit*> &LiveRegDefs,
986 SmallSet<unsigned, 4> &RegAdded,
987 SmallVector<unsigned, 4> &LRegs,
988 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +0000989 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
990
991 // Check if Ref is live.
992 if (!LiveRegDefs[Reg]) continue;
993
994 // Allow multiple uses of the same def.
995 if (LiveRegDefs[Reg] == SU) continue;
996
997 // Add Reg to the set of interfering live regs.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000998 if (RegAdded.insert(Reg))
Evan Chengb8905c42009-03-04 01:41:49 +0000999 LRegs.push_back(Reg);
Evan Chengb8905c42009-03-04 01:41:49 +00001000 }
Evan Chengb8905c42009-03-04 01:41:49 +00001001}
1002
Evan Cheng5924bf72007-09-25 01:54:36 +00001003/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1004/// scheduling of the given node to satisfy live physical register dependencies.
1005/// If the specific node is the last one that's available to schedule, do
1006/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001007bool ScheduleDAGRRList::
1008DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +00001009 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +00001010 return false;
1011
Evan Chenge6f92252007-09-27 18:46:06 +00001012 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +00001013 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001014 //
1015 // If SU is the currently live definition of the same register that it uses,
1016 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +00001017 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1018 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001019 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +00001020 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1021 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001022 }
1023
Chris Lattner11a33812010-12-23 17:24:32 +00001024 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +00001025 if (Node->getOpcode() == ISD::INLINEASM) {
1026 // Inline asm can clobber physical defs.
1027 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001028 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +00001029 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +00001030
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001031 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +00001032 unsigned Flags =
1033 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001034 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +00001035
1036 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001037 if (InlineAsm::isRegDefKind(Flags) ||
1038 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +00001039 // Check for def of register or earlyclobber register.
1040 for (; NumVals; --NumVals, ++i) {
1041 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1042 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1043 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1044 }
1045 } else
1046 i += NumVals;
1047 }
1048 continue;
1049 }
1050
Dan Gohman072734e2008-11-13 23:24:17 +00001051 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +00001052 continue;
Dan Gohman17059682008-07-17 19:10:17 +00001053 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +00001054 if (!TID.ImplicitDefs)
1055 continue;
Evan Chengb8905c42009-03-04 01:41:49 +00001056 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
1057 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001058 }
Andrew Trick2085a962010-12-21 22:25:04 +00001059
Evan Cheng5924bf72007-09-25 01:54:36 +00001060 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +00001061}
1062
Andrew Trick528fad92010-12-23 05:42:20 +00001063/// Return a node that can be scheduled in this cycle. Requirements:
1064/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001065/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +00001066/// (3) No Interferences: may unschedule to break register interferences.
1067SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1068 SmallVector<SUnit*, 4> Interferences;
1069 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1070
1071 SUnit *CurSU = AvailableQueue->pop();
1072 while (CurSU) {
1073 SmallVector<unsigned, 4> LRegs;
1074 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1075 break;
1076 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1077
1078 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1079 Interferences.push_back(CurSU);
1080 CurSU = AvailableQueue->pop();
1081 }
1082 if (CurSU) {
1083 // Add the nodes that aren't ready back onto the available list.
1084 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1085 Interferences[i]->isPending = false;
1086 assert(Interferences[i]->isAvailable && "must still be available");
1087 AvailableQueue->push(Interferences[i]);
1088 }
1089 return CurSU;
1090 }
1091
1092 // All candidates are delayed due to live physical reg dependencies.
1093 // Try backtracking, code duplication, or inserting cross class copies
1094 // to resolve it.
1095 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1096 SUnit *TrySU = Interferences[i];
1097 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1098
1099 // Try unscheduling up to the point where it's safe to schedule
1100 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001101 SUnit *BtSU = NULL;
1102 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001103 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1104 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001105 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1106 BtSU = LiveRegGens[Reg];
1107 LiveCycle = BtSU->getHeight();
1108 }
Andrew Trick528fad92010-12-23 05:42:20 +00001109 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001110 if (!WillCreateCycle(TrySU, BtSU)) {
1111 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001112
1113 // Force the current node to be scheduled before the node that
1114 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001115 if (BtSU->isAvailable) {
1116 BtSU->isAvailable = false;
1117 if (!BtSU->isPending)
1118 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001119 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001120 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001121 /*Reg=*/0, /*isNormalMemory=*/false,
1122 /*isMustAlias=*/false, /*isArtificial=*/true));
1123
1124 // If one or more successors has been unscheduled, then the current
1125 // node is no longer avaialable. Schedule a successor that's now
1126 // available instead.
1127 if (!TrySU->isAvailable) {
1128 CurSU = AvailableQueue->pop();
1129 }
1130 else {
1131 CurSU = TrySU;
1132 TrySU->isPending = false;
1133 Interferences.erase(Interferences.begin()+i);
1134 }
1135 break;
1136 }
1137 }
1138
1139 if (!CurSU) {
1140 // Can't backtrack. If it's too expensive to copy the value, then try
1141 // duplicate the nodes that produces these "too expensive to copy"
1142 // values to break the dependency. In case even that doesn't work,
1143 // insert cross class copies.
1144 // If it's not too expensive, i.e. cost != -1, issue copies.
1145 SUnit *TrySU = Interferences[0];
1146 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1147 assert(LRegs.size() == 1 && "Can't handle this yet!");
1148 unsigned Reg = LRegs[0];
1149 SUnit *LRDef = LiveRegDefs[Reg];
1150 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1151 const TargetRegisterClass *RC =
1152 TRI->getMinimalPhysRegClass(Reg, VT);
1153 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1154
Evan Chengb4c6a342011-03-10 00:16:32 +00001155 // If cross copy register class is the same as RC, then it must be possible
1156 // copy the value directly. Do not try duplicate the def.
1157 // If cross copy register class is not the same as RC, then it's possible to
1158 // copy the value but it require cross register class copies and it is
1159 // expensive.
1160 // If cross copy register class is null, then it's not possible to copy
1161 // the value at all.
Andrew Trick528fad92010-12-23 05:42:20 +00001162 SUnit *NewDef = 0;
Evan Chengb4c6a342011-03-10 00:16:32 +00001163 if (DestRC != RC) {
Andrew Trick528fad92010-12-23 05:42:20 +00001164 NewDef = CopyAndMoveSuccessors(LRDef);
Evan Chengb4c6a342011-03-10 00:16:32 +00001165 if (!DestRC && !NewDef)
1166 report_fatal_error("Can't handle live physical register dependency!");
1167 }
Andrew Trick528fad92010-12-23 05:42:20 +00001168 if (!NewDef) {
1169 // Issue copies, these can be expensive cross register class copies.
1170 SmallVector<SUnit*, 2> Copies;
1171 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1172 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1173 << " to SU #" << Copies.front()->NodeNum << "\n");
1174 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1175 /*Reg=*/0, /*isNormalMemory=*/false,
1176 /*isMustAlias=*/false,
1177 /*isArtificial=*/true));
1178 NewDef = Copies.back();
1179 }
1180
1181 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1182 << " to SU #" << TrySU->NodeNum << "\n");
1183 LiveRegDefs[Reg] = NewDef;
1184 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1185 /*Reg=*/0, /*isNormalMemory=*/false,
1186 /*isMustAlias=*/false,
1187 /*isArtificial=*/true));
1188 TrySU->isAvailable = false;
1189 CurSU = NewDef;
1190 }
1191
1192 assert(CurSU && "Unable to resolve live physical register dependencies!");
1193
1194 // Add the nodes that aren't ready back onto the available list.
1195 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1196 Interferences[i]->isPending = false;
1197 // May no longer be available due to backtracking.
1198 if (Interferences[i]->isAvailable) {
1199 AvailableQueue->push(Interferences[i]);
1200 }
1201 }
1202 return CurSU;
1203}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001204
Evan Chengd38c22b2006-05-11 23:55:42 +00001205/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1206/// schedulers.
1207void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001208 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001209 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001210
Evan Chengd38c22b2006-05-11 23:55:42 +00001211 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001212 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001213 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001214 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1215 RootSU->isAvailable = true;
1216 AvailableQueue->push(RootSU);
1217 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001218
1219 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001220 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001221 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001222 while (!AvailableQueue->empty()) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00001223 DEBUG(dbgs() << "\n*** Examining Available\n";
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001224 AvailableQueue->dump(this));
1225
Andrew Trick528fad92010-12-23 05:42:20 +00001226 // Pick the best node to schedule taking all constraints into
1227 // consideration.
1228 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001229
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001230 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001231
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001232 ScheduleNodeBottomUp(SU);
1233
1234 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1235 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1236 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1237 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1238 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001239 }
1240
Evan Chengd38c22b2006-05-11 23:55:42 +00001241 // Reverse the order if it is bottom up.
1242 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001243
Evan Chengd38c22b2006-05-11 23:55:42 +00001244#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001245 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001246#endif
1247}
1248
1249//===----------------------------------------------------------------------===//
1250// Top-Down Scheduling
1251//===----------------------------------------------------------------------===//
1252
1253/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001254/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001255void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001256 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001257
Evan Chengd38c22b2006-05-11 23:55:42 +00001258#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001259 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001260 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001261 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001262 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001263 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001264 }
1265#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001266 --SuccSU->NumPredsLeft;
1267
Dan Gohmanb9543432009-02-10 23:27:53 +00001268 // If all the node's predecessors are scheduled, this node is ready
1269 // to be scheduled. Ignore the special ExitSU node.
1270 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001271 SuccSU->isAvailable = true;
1272 AvailableQueue->push(SuccSU);
1273 }
1274}
1275
Dan Gohmanb9543432009-02-10 23:27:53 +00001276void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1277 // Top down: release successors
1278 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1279 I != E; ++I) {
1280 assert(!I->isAssignedRegDep() &&
1281 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1282
1283 ReleaseSucc(SU, &*I);
1284 }
1285}
1286
Evan Chengd38c22b2006-05-11 23:55:42 +00001287/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1288/// count of its successors. If a successor pending count is zero, add it to
1289/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001290void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001291 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001292 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001293
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001294 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1295 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001296 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001297
Dan Gohmanb9543432009-02-10 23:27:53 +00001298 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001299 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001300 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001301}
1302
Dan Gohman54a187e2007-08-20 19:28:38 +00001303/// ListScheduleTopDown - The main loop of list scheduling for top-down
1304/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001305void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001306 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001307
Dan Gohmanb9543432009-02-10 23:27:53 +00001308 // Release any successors of the special Entry node.
1309 ReleaseSuccessors(&EntrySU);
1310
Evan Chengd38c22b2006-05-11 23:55:42 +00001311 // All leaves to Available queue.
1312 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1313 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001314 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001315 AvailableQueue->push(&SUnits[i]);
1316 SUnits[i].isAvailable = true;
1317 }
1318 }
Andrew Trick2085a962010-12-21 22:25:04 +00001319
Evan Chengd38c22b2006-05-11 23:55:42 +00001320 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001321 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001322 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001323 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001324 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001325
Dan Gohmanc602dd42008-11-21 00:10:42 +00001326 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001327 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001328 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001329 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001330 }
Andrew Trick2085a962010-12-21 22:25:04 +00001331
Evan Chengd38c22b2006-05-11 23:55:42 +00001332#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001333 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001334#endif
1335}
1336
1337
Evan Chengd38c22b2006-05-11 23:55:42 +00001338//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001339// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001340//===----------------------------------------------------------------------===//
1341//
1342// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1343// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001344//
Evan Chengd38c22b2006-05-11 23:55:42 +00001345namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001346class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001347
Andrew Trick9ccce772011-01-14 21:11:41 +00001348struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1349 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1350};
1351
1352/// bu_ls_rr_sort - Priority function for bottom up register pressure
1353// reduction scheduler.
1354struct bu_ls_rr_sort : public queue_sort {
1355 enum {
1356 IsBottomUp = true,
1357 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001358 };
1359
Andrew Trick9ccce772011-01-14 21:11:41 +00001360 RegReductionPQBase *SPQ;
1361 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1362 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001363
Andrew Trick9ccce772011-01-14 21:11:41 +00001364 bool operator()(SUnit* left, SUnit* right) const;
1365};
Andrew Trick2085a962010-12-21 22:25:04 +00001366
Andrew Trick9ccce772011-01-14 21:11:41 +00001367// td_ls_rr_sort - Priority function for top down register pressure reduction
1368// scheduler.
1369struct td_ls_rr_sort : public queue_sort {
1370 enum {
1371 IsBottomUp = false,
1372 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001373 };
1374
Andrew Trick9ccce772011-01-14 21:11:41 +00001375 RegReductionPQBase *SPQ;
1376 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1377 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001378
Andrew Trick9ccce772011-01-14 21:11:41 +00001379 bool operator()(const SUnit* left, const SUnit* right) const;
1380};
Andrew Trick2085a962010-12-21 22:25:04 +00001381
Andrew Trick9ccce772011-01-14 21:11:41 +00001382// src_ls_rr_sort - Priority function for source order scheduler.
1383struct src_ls_rr_sort : public queue_sort {
1384 enum {
1385 IsBottomUp = true,
1386 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001387 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001388
Andrew Trick9ccce772011-01-14 21:11:41 +00001389 RegReductionPQBase *SPQ;
1390 src_ls_rr_sort(RegReductionPQBase *spq)
1391 : SPQ(spq) {}
1392 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1393 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001394
Andrew Trick9ccce772011-01-14 21:11:41 +00001395 bool operator()(SUnit* left, SUnit* right) const;
1396};
Andrew Trick2085a962010-12-21 22:25:04 +00001397
Andrew Trick9ccce772011-01-14 21:11:41 +00001398// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1399struct hybrid_ls_rr_sort : public queue_sort {
1400 enum {
1401 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001402 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001403 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001404
Andrew Trick9ccce772011-01-14 21:11:41 +00001405 RegReductionPQBase *SPQ;
1406 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1407 : SPQ(spq) {}
1408 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1409 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001410
Andrew Trick9ccce772011-01-14 21:11:41 +00001411 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001412
Andrew Trick9ccce772011-01-14 21:11:41 +00001413 bool operator()(SUnit* left, SUnit* right) const;
1414};
1415
1416// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1417// scheduler.
1418struct ilp_ls_rr_sort : public queue_sort {
1419 enum {
1420 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001421 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001422 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001423
Andrew Trick9ccce772011-01-14 21:11:41 +00001424 RegReductionPQBase *SPQ;
1425 ilp_ls_rr_sort(RegReductionPQBase *spq)
1426 : SPQ(spq) {}
1427 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1428 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001429
Andrew Trick9ccce772011-01-14 21:11:41 +00001430 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001431
Andrew Trick9ccce772011-01-14 21:11:41 +00001432 bool operator()(SUnit* left, SUnit* right) const;
1433};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001434
Andrew Trick9ccce772011-01-14 21:11:41 +00001435class RegReductionPQBase : public SchedulingPriorityQueue {
1436protected:
1437 std::vector<SUnit*> Queue;
1438 unsigned CurQueueId;
1439 bool TracksRegPressure;
1440
1441 // SUnits - The SUnits for the current graph.
1442 std::vector<SUnit> *SUnits;
1443
1444 MachineFunction &MF;
1445 const TargetInstrInfo *TII;
1446 const TargetRegisterInfo *TRI;
1447 const TargetLowering *TLI;
1448 ScheduleDAGRRList *scheduleDAG;
1449
1450 // SethiUllmanNumbers - The SethiUllman number for each node.
1451 std::vector<unsigned> SethiUllmanNumbers;
1452
1453 /// RegPressure - Tracking current reg pressure per register class.
1454 ///
1455 std::vector<unsigned> RegPressure;
1456
1457 /// RegLimit - Tracking the number of allocatable registers per register
1458 /// class.
1459 std::vector<unsigned> RegLimit;
1460
1461public:
1462 RegReductionPQBase(MachineFunction &mf,
1463 bool hasReadyFilter,
1464 bool tracksrp,
1465 const TargetInstrInfo *tii,
1466 const TargetRegisterInfo *tri,
1467 const TargetLowering *tli)
1468 : SchedulingPriorityQueue(hasReadyFilter),
1469 CurQueueId(0), TracksRegPressure(tracksrp),
1470 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1471 if (TracksRegPressure) {
1472 unsigned NumRC = TRI->getNumRegClasses();
1473 RegLimit.resize(NumRC);
1474 RegPressure.resize(NumRC);
1475 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1476 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1477 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1478 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +00001479 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
Andrew Trick9ccce772011-01-14 21:11:41 +00001480 }
1481 }
1482
1483 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1484 scheduleDAG = scheduleDag;
1485 }
1486
1487 ScheduleHazardRecognizer* getHazardRec() {
1488 return scheduleDAG->getHazardRec();
1489 }
1490
1491 void initNodes(std::vector<SUnit> &sunits);
1492
1493 void addNode(const SUnit *SU);
1494
1495 void updateNode(const SUnit *SU);
1496
1497 void releaseState() {
1498 SUnits = 0;
1499 SethiUllmanNumbers.clear();
1500 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1501 }
1502
1503 unsigned getNodePriority(const SUnit *SU) const;
1504
1505 unsigned getNodeOrdering(const SUnit *SU) const {
Andrew Trick3bd8b7a2011-03-25 06:40:55 +00001506 if (!SU->getNode()) return 0;
1507
Andrew Trick9ccce772011-01-14 21:11:41 +00001508 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1509 }
1510
1511 bool empty() const { return Queue.empty(); }
1512
1513 void push(SUnit *U) {
1514 assert(!U->NodeQueueId && "Node in the queue already");
1515 U->NodeQueueId = ++CurQueueId;
1516 Queue.push_back(U);
1517 }
1518
1519 void remove(SUnit *SU) {
1520 assert(!Queue.empty() && "Queue is empty!");
1521 assert(SU->NodeQueueId != 0 && "Not in queue!");
1522 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1523 SU);
1524 if (I != prior(Queue.end()))
1525 std::swap(*I, Queue.back());
1526 Queue.pop_back();
1527 SU->NodeQueueId = 0;
1528 }
1529
Andrew Trickd0548ae2011-02-04 03:18:17 +00001530 bool tracksRegPressure() const { return TracksRegPressure; }
1531
Andrew Trick9ccce772011-01-14 21:11:41 +00001532 void dumpRegPressure() const;
1533
1534 bool HighRegPressure(const SUnit *SU) const;
1535
Andrew Trick641e2d42011-03-05 08:00:22 +00001536 bool MayReduceRegPressure(SUnit *SU) const;
1537
1538 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
Andrew Trick9ccce772011-01-14 21:11:41 +00001539
1540 void ScheduledNode(SUnit *SU);
1541
1542 void UnscheduledNode(SUnit *SU);
1543
1544protected:
1545 bool canClobber(const SUnit *SU, const SUnit *Op);
1546 void AddPseudoTwoAddrDeps();
1547 void PrescheduleNodesWithMultipleUses();
1548 void CalculateSethiUllmanNumbers();
1549};
1550
1551template<class SF>
1552class RegReductionPriorityQueue : public RegReductionPQBase {
1553 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1554 std::vector<SUnit *>::iterator Best = Q.begin();
1555 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1556 E = Q.end(); I != E; ++I)
1557 if (Picker(*Best, *I))
1558 Best = I;
1559 SUnit *V = *Best;
1560 if (Best != prior(Q.end()))
1561 std::swap(*Best, Q.back());
1562 Q.pop_back();
1563 return V;
1564 }
1565
1566 SF Picker;
1567
1568public:
1569 RegReductionPriorityQueue(MachineFunction &mf,
1570 bool tracksrp,
1571 const TargetInstrInfo *tii,
1572 const TargetRegisterInfo *tri,
1573 const TargetLowering *tli)
1574 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1575 Picker(this) {}
1576
1577 bool isBottomUp() const { return SF::IsBottomUp; }
1578
1579 bool isReady(SUnit *U) const {
1580 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1581 }
1582
1583 SUnit *pop() {
1584 if (Queue.empty()) return NULL;
1585
1586 SUnit *V = popFromQueue(Queue, Picker);
1587 V->NodeQueueId = 0;
1588 return V;
1589 }
1590
1591 void dump(ScheduleDAG *DAG) const {
1592 // Emulate pop() without clobbering NodeQueueIds.
1593 std::vector<SUnit*> DumpQueue = Queue;
1594 SF DumpPicker = Picker;
1595 while (!DumpQueue.empty()) {
1596 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1597 if (isBottomUp())
1598 dbgs() << "Height " << SU->getHeight() << ": ";
1599 else
1600 dbgs() << "Depth " << SU->getDepth() << ": ";
1601 SU->dump(DAG);
1602 }
1603 }
1604};
1605
1606typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1607BURegReductionPriorityQueue;
1608
1609typedef RegReductionPriorityQueue<td_ls_rr_sort>
1610TDRegReductionPriorityQueue;
1611
1612typedef RegReductionPriorityQueue<src_ls_rr_sort>
1613SrcRegReductionPriorityQueue;
1614
1615typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1616HybridBURRPriorityQueue;
1617
1618typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1619ILPBURRPriorityQueue;
1620} // end anonymous namespace
1621
1622//===----------------------------------------------------------------------===//
1623// Static Node Priority for Register Pressure Reduction
1624//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001625
Dan Gohman186f65d2008-11-20 03:30:37 +00001626/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1627/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001628static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001629CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001630 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1631 if (SethiUllmanNumber != 0)
1632 return SethiUllmanNumber;
1633
1634 unsigned Extra = 0;
1635 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1636 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001637 if (I->isCtrl()) continue; // ignore chain preds
1638 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001639 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001640 if (PredSethiUllman > SethiUllmanNumber) {
1641 SethiUllmanNumber = PredSethiUllman;
1642 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001643 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001644 ++Extra;
1645 }
1646
1647 SethiUllmanNumber += Extra;
1648
1649 if (SethiUllmanNumber == 0)
1650 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001651
Evan Cheng7e4abde2008-07-02 09:23:51 +00001652 return SethiUllmanNumber;
1653}
1654
Andrew Trick9ccce772011-01-14 21:11:41 +00001655/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1656/// scheduling units.
1657void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1658 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001659
Andrew Trick9ccce772011-01-14 21:11:41 +00001660 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1661 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001662}
1663
Andrew Trick1b60ad62011-04-12 20:14:07 +00001664void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1665 SUnits = &sunits;
1666 // Add pseudo dependency edges for two-address nodes.
1667 AddPseudoTwoAddrDeps();
1668 // Reroute edges to nodes with multiple uses.
1669 if (!TracksRegPressure)
1670 PrescheduleNodesWithMultipleUses();
1671 // Calculate node priorities.
1672 CalculateSethiUllmanNumbers();
1673}
1674
Andrew Trick9ccce772011-01-14 21:11:41 +00001675void RegReductionPQBase::addNode(const SUnit *SU) {
1676 unsigned SUSize = SethiUllmanNumbers.size();
1677 if (SUnits->size() > SUSize)
1678 SethiUllmanNumbers.resize(SUSize*2, 0);
1679 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1680}
1681
1682void RegReductionPQBase::updateNode(const SUnit *SU) {
1683 SethiUllmanNumbers[SU->NodeNum] = 0;
1684 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1685}
1686
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001687// Lower priority means schedule further down. For bottom-up scheduling, lower
1688// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001689unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1690 assert(SU->NodeNum < SethiUllmanNumbers.size());
1691 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1692 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1693 // CopyToReg should be close to its uses to facilitate coalescing and
1694 // avoid spilling.
1695 return 0;
1696 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1697 Opc == TargetOpcode::SUBREG_TO_REG ||
1698 Opc == TargetOpcode::INSERT_SUBREG)
1699 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1700 // close to their uses to facilitate coalescing.
1701 return 0;
1702 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1703 // If SU does not have a register use, i.e. it doesn't produce a value
1704 // that would be consumed (e.g. store), then it terminates a chain of
1705 // computation. Give it a large SethiUllman number so it will be
1706 // scheduled right before its predecessors that it doesn't lengthen
1707 // their live ranges.
1708 return 0xffff;
1709 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1710 // If SU does not have a register def, schedule it close to its uses
1711 // because it does not lengthen any live ranges.
1712 return 0;
1713 return SethiUllmanNumbers[SU->NodeNum];
1714}
1715
1716//===----------------------------------------------------------------------===//
1717// Register Pressure Tracking
1718//===----------------------------------------------------------------------===//
1719
1720void RegReductionPQBase::dumpRegPressure() const {
1721 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1722 E = TRI->regclass_end(); I != E; ++I) {
1723 const TargetRegisterClass *RC = *I;
1724 unsigned Id = RC->getID();
1725 unsigned RP = RegPressure[Id];
1726 if (!RP) continue;
1727 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1728 << '\n');
1729 }
1730}
1731
1732bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1733 if (!TLI)
1734 return false;
1735
1736 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1737 I != E; ++I) {
1738 if (I->isCtrl())
1739 continue;
1740 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001741 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1742 // to cover the number of registers defined (they are all live).
1743 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001744 continue;
1745 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001746 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1747 RegDefPos.IsValid(); RegDefPos.Advance()) {
1748 EVT VT = RegDefPos.GetValue();
Andrew Trick9ccce772011-01-14 21:11:41 +00001749 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1750 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Andrew Trick9ccce772011-01-14 21:11:41 +00001751 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1752 return true;
1753 }
1754 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001755 return false;
1756}
1757
Andrew Trick641e2d42011-03-05 08:00:22 +00001758bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00001759 const SDNode *N = SU->getNode();
1760
1761 if (!N->isMachineOpcode() || !SU->NumSuccs)
1762 return false;
1763
1764 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1765 for (unsigned i = 0; i != NumDefs; ++i) {
1766 EVT VT = N->getValueType(i);
1767 if (!N->hasAnyUseOfValue(i))
1768 continue;
1769 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1770 if (RegPressure[RCId] >= RegLimit[RCId])
1771 return true;
1772 }
1773 return false;
1774}
1775
Andrew Trick641e2d42011-03-05 08:00:22 +00001776// Compute the register pressure contribution by this instruction by count up
1777// for uses that are not live and down for defs. Only count register classes
1778// that are already under high pressure. As a side effect, compute the number of
1779// uses of registers that are already live.
1780//
1781// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1782// so could probably be factored.
1783int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1784 LiveUses = 0;
1785 int PDiff = 0;
1786 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1787 I != E; ++I) {
1788 if (I->isCtrl())
1789 continue;
1790 SUnit *PredSU = I->getSUnit();
1791 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1792 // to cover the number of registers defined (they are all live).
1793 if (PredSU->NumRegDefsLeft == 0) {
1794 if (PredSU->getNode()->isMachineOpcode())
1795 ++LiveUses;
1796 continue;
1797 }
1798 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1799 RegDefPos.IsValid(); RegDefPos.Advance()) {
1800 EVT VT = RegDefPos.GetValue();
1801 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1802 if (RegPressure[RCId] >= RegLimit[RCId])
1803 ++PDiff;
1804 }
1805 }
1806 const SDNode *N = SU->getNode();
1807
Eric Christopher7238cba2011-03-08 19:35:47 +00001808 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
Andrew Trick641e2d42011-03-05 08:00:22 +00001809 return PDiff;
1810
1811 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1812 for (unsigned i = 0; i != NumDefs; ++i) {
1813 EVT VT = N->getValueType(i);
1814 if (!N->hasAnyUseOfValue(i))
1815 continue;
1816 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1817 if (RegPressure[RCId] >= RegLimit[RCId])
1818 --PDiff;
1819 }
1820 return PDiff;
1821}
1822
Andrew Trick9ccce772011-01-14 21:11:41 +00001823void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1824 if (!TracksRegPressure)
1825 return;
1826
Eric Christopher7238cba2011-03-08 19:35:47 +00001827 if (!SU->getNode())
1828 return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001829
Andrew Trick9ccce772011-01-14 21:11:41 +00001830 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1831 I != E; ++I) {
1832 if (I->isCtrl())
1833 continue;
1834 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001835 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1836 // to cover the number of registers defined (they are all live).
1837 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001838 continue;
1839 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001840 // FIXME: The ScheduleDAG currently loses information about which of a
1841 // node's values is consumed by each dependence. Consequently, if the node
1842 // defines multiple register classes, we don't know which to pressurize
1843 // here. Instead the following loop consumes the register defs in an
1844 // arbitrary order. At least it handles the common case of clustered loads
1845 // to the same class. For precise liveness, each SDep needs to indicate the
1846 // result number. But that tightly couples the ScheduleDAG with the
1847 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1848 // value type or register class to SDep.
1849 //
1850 // The most important aspect of register tracking is balancing the increase
1851 // here with the reduction further below. Note that this SU may use multiple
1852 // defs in PredSU. The can't be determined here, but we've already
1853 // compensated by reducing NumRegDefsLeft in PredSU during
1854 // ScheduleDAGSDNodes::AddSchedEdges.
1855 --PredSU->NumRegDefsLeft;
1856 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1857 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1858 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1859 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00001860 continue;
Andrew Trickd0548ae2011-02-04 03:18:17 +00001861 EVT VT = RegDefPos.GetValue();
Andrew Trick9ccce772011-01-14 21:11:41 +00001862 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1863 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001864 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00001865 }
1866 }
1867
Andrew Trickd0548ae2011-02-04 03:18:17 +00001868 // We should have this assert, but there may be dead SDNodes that never
1869 // materialize as SUnits, so they don't appear to generate liveness.
1870 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1871 int SkipRegDefs = (int)SU->NumRegDefsLeft;
1872 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1873 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1874 if (SkipRegDefs > 0)
1875 continue;
1876 EVT VT = RegDefPos.GetValue();
1877 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1878 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT)) {
1879 // Register pressure tracking is imprecise. This can happen. But we try
1880 // hard not to let it happen because it likely results in poor scheduling.
1881 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
1882 RegPressure[RCId] = 0;
1883 }
1884 else {
1885 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
Andrew Trick9ccce772011-01-14 21:11:41 +00001886 }
1887 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001888 dumpRegPressure();
1889}
1890
1891void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1892 if (!TracksRegPressure)
1893 return;
1894
1895 const SDNode *N = SU->getNode();
Eric Christopher7238cba2011-03-08 19:35:47 +00001896 if (!N) return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001897
Andrew Trick9ccce772011-01-14 21:11:41 +00001898 if (!N->isMachineOpcode()) {
1899 if (N->getOpcode() != ISD::CopyToReg)
1900 return;
1901 } else {
1902 unsigned Opc = N->getMachineOpcode();
1903 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1904 Opc == TargetOpcode::INSERT_SUBREG ||
1905 Opc == TargetOpcode::SUBREG_TO_REG ||
1906 Opc == TargetOpcode::REG_SEQUENCE ||
1907 Opc == TargetOpcode::IMPLICIT_DEF)
1908 return;
1909 }
1910
1911 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1912 I != E; ++I) {
1913 if (I->isCtrl())
1914 continue;
1915 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001916 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1917 // counts data deps.
1918 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00001919 continue;
1920 const SDNode *PN = PredSU->getNode();
1921 if (!PN->isMachineOpcode()) {
1922 if (PN->getOpcode() == ISD::CopyFromReg) {
1923 EVT VT = PN->getValueType(0);
1924 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1925 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1926 }
1927 continue;
1928 }
1929 unsigned POpc = PN->getMachineOpcode();
1930 if (POpc == TargetOpcode::IMPLICIT_DEF)
1931 continue;
1932 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1933 EVT VT = PN->getOperand(0).getValueType();
1934 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1935 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1936 continue;
1937 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1938 POpc == TargetOpcode::SUBREG_TO_REG) {
1939 EVT VT = PN->getValueType(0);
1940 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1941 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1942 continue;
1943 }
1944 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1945 for (unsigned i = 0; i != NumDefs; ++i) {
1946 EVT VT = PN->getValueType(i);
1947 if (!PN->hasAnyUseOfValue(i))
1948 continue;
1949 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1950 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1951 // Register pressure tracking is imprecise. This can happen.
1952 RegPressure[RCId] = 0;
1953 else
1954 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1955 }
1956 }
1957
1958 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1959 // may transfer data dependencies to CopyToReg.
1960 if (SU->NumSuccs && N->isMachineOpcode()) {
1961 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1962 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1963 EVT VT = N->getValueType(i);
1964 if (VT == MVT::Glue || VT == MVT::Other)
1965 continue;
1966 if (!N->hasAnyUseOfValue(i))
1967 continue;
1968 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1969 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1970 }
1971 }
1972
1973 dumpRegPressure();
1974}
1975
1976//===----------------------------------------------------------------------===//
1977// Dynamic Node Priority for Register Pressure Reduction
1978//===----------------------------------------------------------------------===//
1979
Evan Chengb9e3db62007-03-14 22:43:40 +00001980/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00001981/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001982static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001983 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00001984 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001985 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00001986 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001987 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00001988 // If there are bunch of CopyToRegs stacked up, they should be considered
1989 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00001990 if (I->getSUnit()->getNode() &&
1991 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001992 Height = closestSucc(I->getSUnit())+1;
1993 if (Height > MaxHeight)
1994 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00001995 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001996 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00001997}
1998
Evan Cheng61bc51e2007-12-20 02:22:36 +00001999/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00002000/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00002001static unsigned calcMaxScratches(const SUnit *SU) {
2002 unsigned Scratches = 0;
2003 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00002004 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002005 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00002006 Scratches++;
2007 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00002008 return Scratches;
2009}
2010
Andrew Trick1b60ad62011-04-12 20:14:07 +00002011/// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
Evan Cheng6c1414f2010-10-29 18:09:28 +00002012/// CopyToReg to a virtual register. This SU def is probably a liveout and
2013/// it has no other use. It should be scheduled closer to the terminator.
2014static bool hasOnlyLiveOutUses(const SUnit *SU) {
2015 bool RetVal = false;
2016 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2017 I != E; ++I) {
2018 if (I->isCtrl()) continue;
2019 const SUnit *SuccSU = I->getSUnit();
2020 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2021 unsigned Reg =
2022 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2023 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2024 RetVal = true;
2025 continue;
2026 }
2027 }
2028 return false;
2029 }
2030 return RetVal;
2031}
2032
Andrew Trick1b60ad62011-04-12 20:14:07 +00002033/// UnitsSharePred - Return true if the two scheduling units share a common
2034/// data predecessor.
2035static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
2036 SmallSet<const SUnit*, 4> Preds;
2037 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002038 I != E; ++I) {
Andrew Trick2ad0b372011-04-07 19:54:57 +00002039 if (I->isCtrl()) continue; // ignore chain preds
Andrew Trick1b60ad62011-04-12 20:14:07 +00002040 Preds.insert(I->getSUnit());
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002041 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002042 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002043 I != E; ++I) {
2044 if (I->isCtrl()) continue; // ignore chain preds
Andrew Trick1b60ad62011-04-12 20:14:07 +00002045 if (Preds.count(I->getSUnit()))
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002046 return true;
Andrew Trick1b60ad62011-04-12 20:14:07 +00002047 }
2048 return false;
2049}
2050
2051// Return true if the virtual register defined by VRCycleSU may interfere with
2052// VRUseSU.
2053//
2054// Note: We may consider two SU's that use the same value live into a loop as
2055// interferng even though the value is not an induction variable. This is an
2056// unfortunate consequence of scheduling on the selection DAG.
2057static bool checkVRegCycleInterference(const SUnit *VRCycleSU,
2058 const SUnit *VRUseSU) {
2059 for (SUnit::const_pred_iterator I = VRCycleSU->Preds.begin(),
2060 E = VRCycleSU->Preds.end(); I != E; ++I) {
2061 if (I->isCtrl()) continue; // ignore chain preds
2062 SDNode *InNode = I->getSUnit()->getNode();
2063 if (!InNode || InNode->getOpcode() != ISD::CopyFromReg)
2064 continue;
2065 for (SUnit::const_pred_iterator II = VRUseSU->Preds.begin(),
2066 EE = VRUseSU->Preds.end(); II != EE; ++II) {
2067 if (II->getSUnit() == I->getSUnit())
2068 return true;
Andrew Trick2ad0b372011-04-07 19:54:57 +00002069 }
2070 }
2071 return false;
2072}
2073
Andrew Trick1b60ad62011-04-12 20:14:07 +00002074// Compare the VRegCycle properties of the nodes.
2075// Return -1 if left has higher priority, 1 if right has higher priority.
2076// Return 0 if priority is equivalent.
2077static int BUCompareVRegCycle(const SUnit *left, const SUnit *right) {
2078 if (left->isVRegCycle && !right->isVRegCycle) {
2079 if (checkVRegCycleInterference(left, right))
2080 return -1;
2081 }
2082 else if (!left->isVRegCycle && right->isVRegCycle) {
2083 if (checkVRegCycleInterference(right, left))
2084 return 1;
2085 }
2086 return 0;
2087}
2088
Andrew Trick9ccce772011-01-14 21:11:41 +00002089// Check for either a dependence (latency) or resource (hazard) stall.
2090//
2091// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2092static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2093 if ((int)SPQ->getCurCycle() < Height) return true;
2094 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2095 != ScheduleHazardRecognizer::NoHazard)
2096 return true;
2097 return false;
2098}
2099
2100// Return -1 if left has higher priority, 1 if right has higher priority.
2101// Return 0 if latency-based priority is equivalent.
2102static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2103 RegReductionPQBase *SPQ) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002104 // If the two nodes share an operand and one of them has a single
2105 // use that is a live out copy, favor the one that is live out. Otherwise
2106 // it will be difficult to eliminate the copy if the instruction is a
2107 // loop induction variable update. e.g.
2108 // BB:
2109 // sub r1, r3, #1
2110 // str r0, [r2, r3]
2111 // mov r3, r1
2112 // cmp
2113 // bne BB
2114 bool SharePred = UnitsSharePred(left, right);
2115 // FIXME: Only adjust if BB is a loop back edge.
2116 // FIXME: What's the cost of a copy?
2117 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
2118 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
2119 int LHeight = (int)left->getHeight() - LBonus;
2120 int RHeight = (int)right->getHeight() - RBonus;
Andrew Trick9ccce772011-01-14 21:11:41 +00002121
2122 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
2123 BUHasStall(left, LHeight, SPQ);
2124 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2125 BUHasStall(right, RHeight, SPQ);
2126
2127 // If scheduling one of the node will cause a pipeline stall, delay it.
2128 // If scheduling either one of the node will cause a pipeline stall, sort
2129 // them according to their height.
2130 if (LStall) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002131 if (!RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002132 return 1;
Andrew Trick1b60ad62011-04-12 20:14:07 +00002133 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002134 return LHeight > RHeight ? 1 : -1;
Andrew Trick1b60ad62011-04-12 20:14:07 +00002135 } else if (RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002136 return -1;
2137
Andrew Trick47ff14b2011-01-21 05:51:33 +00002138 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002139 // and latency.
2140 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2141 right->SchedulingPref == Sched::Latency)) {
Andrew Trick47ff14b2011-01-21 05:51:33 +00002142 if (DisableSchedCycles) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002143 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002144 return LHeight > RHeight ? 1 : -1;
2145 }
Andrew Trick47ff14b2011-01-21 05:51:33 +00002146 else {
2147 // If neither instruction stalls (!LStall && !RStall) then
Eric Christopher9cb33de2011-03-06 21:13:45 +00002148 // its height is already covered so only its depth matters. We also reach
Andrew Trick47ff14b2011-01-21 05:51:33 +00002149 // this if both stall but have the same height.
Andrew Trick1b60ad62011-04-12 20:14:07 +00002150 unsigned LDepth = left->getDepth();
2151 unsigned RDepth = right->getDepth();
Andrew Trick47ff14b2011-01-21 05:51:33 +00002152 if (LDepth != RDepth) {
2153 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2154 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2155 << ") depth " << RDepth << "\n");
2156 return LDepth < RDepth ? 1 : -1;
2157 }
2158 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002159 if (left->Latency != right->Latency)
Andrew Trick9ccce772011-01-14 21:11:41 +00002160 return left->Latency > right->Latency ? 1 : -1;
2161 }
2162 return 0;
2163}
2164
2165static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Evan Cheng6730f032007-01-08 23:55:53 +00002166 unsigned LPriority = SPQ->getNodePriority(left);
2167 unsigned RPriority = SPQ->getNodePriority(right);
Andrew Trick641e2d42011-03-05 08:00:22 +00002168 if (LPriority != RPriority) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002169 DEBUG(++FactorCount[FactStatic]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002170 return LPriority > RPriority;
Andrew Trick641e2d42011-03-05 08:00:22 +00002171 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002172 DEBUG(++FactorCount[FactOther]);
Andrew Trick52b3e382011-03-08 01:51:56 +00002173
Evan Cheng73bdf042008-03-01 00:39:47 +00002174 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2175 // e.g.
2176 // t1 = op t2, c1
2177 // t3 = op t4, c2
2178 //
2179 // and the following instructions are both ready.
2180 // t2 = op c3
2181 // t4 = op c4
2182 //
2183 // Then schedule t2 = op first.
2184 // i.e.
2185 // t4 = op c4
2186 // t2 = op c3
2187 // t1 = op t2, c1
2188 // t3 = op t4, c2
2189 //
2190 // This creates more short live intervals.
2191 unsigned LDist = closestSucc(left);
2192 unsigned RDist = closestSucc(right);
Andrew Trick1b60ad62011-04-12 20:14:07 +00002193 if (LDist != RDist)
Evan Cheng73bdf042008-03-01 00:39:47 +00002194 return LDist < RDist;
2195
Evan Cheng3a14efa2009-02-12 08:59:45 +00002196 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002197 unsigned LScratch = calcMaxScratches(left);
2198 unsigned RScratch = calcMaxScratches(right);
Andrew Trick1b60ad62011-04-12 20:14:07 +00002199 if (LScratch != RScratch)
Evan Cheng73bdf042008-03-01 00:39:47 +00002200 return LScratch > RScratch;
2201
Andrew Trick47ff14b2011-01-21 05:51:33 +00002202 if (!DisableSchedCycles) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002203 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2204 if (result != 0)
2205 return result > 0;
2206 }
2207 else {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002208 if (left->getHeight() != right->getHeight())
Andrew Trick9ccce772011-01-14 21:11:41 +00002209 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002210
Andrew Trick1b60ad62011-04-12 20:14:07 +00002211 if (left->getDepth() != right->getDepth())
Andrew Trick9ccce772011-01-14 21:11:41 +00002212 return left->getDepth() < right->getDepth();
2213 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002214
Andrew Trick2085a962010-12-21 22:25:04 +00002215 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002216 "NodeQueueId cannot be zero");
2217 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002218}
2219
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002220// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002221bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002222 return BURRSort(left, right, SPQ);
2223}
2224
2225// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002226bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002227 unsigned LOrder = SPQ->getNodeOrdering(left);
2228 unsigned ROrder = SPQ->getNodeOrdering(right);
2229
2230 // Prefer an ordering where the lower the non-zero order number, the higher
2231 // the preference.
2232 if ((LOrder || ROrder) && LOrder != ROrder)
2233 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2234
2235 return BURRSort(left, right, SPQ);
2236}
2237
Andrew Trick9ccce772011-01-14 21:11:41 +00002238// If the time between now and when the instruction will be ready can cover
2239// the spill code, then avoid adding it to the ready queue. This gives long
2240// stalls highest priority and allows hoisting across calls. It should also
2241// speed up processing the available queue.
2242bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2243 static const unsigned ReadyDelay = 3;
2244
2245 if (SPQ->MayReduceRegPressure(SU)) return true;
2246
2247 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2248
2249 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2250 != ScheduleHazardRecognizer::NoHazard)
2251 return false;
2252
2253 return true;
2254}
2255
2256// Return true if right should be scheduled with higher priority than left.
2257bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002258 if (left->isCall || right->isCall)
2259 // No way to compute latency of calls.
2260 return BURRSort(left, right, SPQ);
2261
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002262 bool LHigh = SPQ->HighRegPressure(left);
2263 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002264 // Avoid causing spills. If register pressure is high, schedule for
2265 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002266 if (LHigh && !RHigh) {
2267 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2268 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002269 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002270 }
2271 else if (!LHigh && RHigh) {
2272 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2273 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002274 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002275 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002276 int result = 0;
2277 if (!DisableSchedVRegCycle) {
2278 result = BUCompareVRegCycle(left, right);
Evan Chengcc2efe12010-05-28 23:26:21 +00002279 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002280 if (result == 0 && !LHigh && !RHigh) {
2281 result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2282 }
2283 if (result != 0)
2284 return result > 0;
Evan Chengbdd062d2010-05-20 06:13:19 +00002285 return BURRSort(left, right, SPQ);
2286}
2287
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002288// Schedule as many instructions in each cycle as possible. So don't make an
2289// instruction available unless it is ready in the current cycle.
2290bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002291 if (SU->getHeight() > CurCycle) return false;
2292
2293 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2294 != ScheduleHazardRecognizer::NoHazard)
2295 return false;
2296
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002297 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002298}
2299
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002300static bool canEnableCoalescing(SUnit *SU) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002301 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2302 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2303 // CopyToReg should be close to its uses to facilitate coalescing and
2304 // avoid spilling.
2305 return true;
2306
2307 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2308 Opc == TargetOpcode::SUBREG_TO_REG ||
2309 Opc == TargetOpcode::INSERT_SUBREG)
2310 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2311 // close to their uses to facilitate coalescing.
2312 return true;
2313
2314 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2315 // If SU does not have a register def, schedule it close to its uses
2316 // because it does not lengthen any live ranges.
2317 return true;
2318
2319 return false;
2320}
2321
Andrew Trickb8390b72011-03-05 08:04:11 +00002322// list-ilp is currently an experimental scheduler that allows various
2323// heuristics to be enabled prior to the normal register reduction logic.
Andrew Trick9ccce772011-01-14 21:11:41 +00002324bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002325 if (left->isCall || right->isCall)
2326 // No way to compute latency of calls.
2327 return BURRSort(left, right, SPQ);
2328
Andrew Trick52b3e382011-03-08 01:51:56 +00002329 unsigned LLiveUses = 0, RLiveUses = 0;
2330 int LPDiff = 0, RPDiff = 0;
2331 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2332 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2333 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2334 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002335 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2336 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick52b3e382011-03-08 01:51:56 +00002337 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2338 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002339 return LPDiff > RPDiff;
2340 }
2341
Andrew Trick52b3e382011-03-08 01:51:56 +00002342 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002343 bool LReduce = canEnableCoalescing(left);
2344 bool RReduce = canEnableCoalescing(right);
Andrew Trick52b3e382011-03-08 01:51:56 +00002345 DEBUG(if (LReduce != RReduce) ++FactorCount[FactPressureDiff]);
2346 if (LReduce && !RReduce) return false;
2347 if (RReduce && !LReduce) return true;
2348 }
2349
Andrew Trick1b60ad62011-04-12 20:14:07 +00002350 if (!DisableSchedVRegCycle) {
2351 int result = BUCompareVRegCycle(left, right);
2352 if (result != 0)
2353 return result > 0;
2354 }
2355
Andrew Trick52b3e382011-03-08 01:51:56 +00002356 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2357 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2358 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002359 DEBUG(++FactorCount[FactRegUses]);
2360 return LLiveUses < RLiveUses;
2361 }
2362
Andrew Trick52b3e382011-03-08 01:51:56 +00002363 if (!DisableSchedStalls) {
2364 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2365 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2366 if (LStall != RStall) {
2367 DEBUG(++FactorCount[FactHeight]);
2368 return left->getHeight() > right->getHeight();
2369 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002370 }
2371
Andrew Trick25cedf32011-03-05 10:29:25 +00002372 if (!DisableSchedCriticalPath) {
2373 int spread = (int)left->getDepth() - (int)right->getDepth();
2374 if (std::abs(spread) > MaxReorderWindow) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002375 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2376 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2377 << right->getDepth() << "\n");
Andrew Trick25cedf32011-03-05 10:29:25 +00002378 DEBUG(++FactorCount[FactDepth]);
2379 return left->getDepth() < right->getDepth();
2380 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002381 }
2382
2383 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002384 int spread = (int)left->getHeight() - (int)right->getHeight();
2385 if (std::abs(spread) > MaxReorderWindow) {
2386 DEBUG(++FactorCount[FactHeight]);
2387 return left->getHeight() > right->getHeight();
2388 }
Evan Cheng37b740c2010-07-24 00:39:05 +00002389 }
2390
2391 return BURRSort(left, right, SPQ);
2392}
2393
Andrew Trick9ccce772011-01-14 21:11:41 +00002394//===----------------------------------------------------------------------===//
2395// Preschedule for Register Pressure
2396//===----------------------------------------------------------------------===//
2397
2398bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002399 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002400 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002401 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002402 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002403 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002404 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002405 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002406 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002407 if (DU->getNodeId() != -1 &&
2408 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002409 return true;
2410 }
2411 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002412 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002413 return false;
2414}
2415
Evan Chengf9891412007-12-20 09:25:31 +00002416/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002417/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002418static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002419 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002420 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002421 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002422 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2423 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002424 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002425 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002426 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002427 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002428 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002429 const unsigned *SUImpDefs =
2430 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2431 if (!SUImpDefs)
2432 return false;
2433 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002434 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002435 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002436 continue;
2437 if (!N->hasAnyUseOfValue(i))
2438 continue;
2439 unsigned Reg = ImpDefs[i - NumDefs];
2440 for (;*SUImpDefs; ++SUImpDefs) {
2441 unsigned SUReg = *SUImpDefs;
2442 if (TRI->regsOverlap(Reg, SUReg))
2443 return true;
2444 }
Evan Chengf9891412007-12-20 09:25:31 +00002445 }
2446 }
2447 return false;
2448}
2449
Dan Gohman9a658d72009-03-24 00:49:12 +00002450/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2451/// are not handled well by the general register pressure reduction
2452/// heuristics. When presented with code like this:
2453///
2454/// N
2455/// / |
2456/// / |
2457/// U store
2458/// |
2459/// ...
2460///
2461/// the heuristics tend to push the store up, but since the
2462/// operand of the store has another use (U), this would increase
2463/// the length of that other use (the U->N edge).
2464///
2465/// This function transforms code like the above to route U's
2466/// dependence through the store when possible, like this:
2467///
2468/// N
2469/// ||
2470/// ||
2471/// store
2472/// |
2473/// U
2474/// |
2475/// ...
2476///
2477/// This results in the store being scheduled immediately
2478/// after N, which shortens the U->N live range, reducing
2479/// register pressure.
2480///
Andrew Trick9ccce772011-01-14 21:11:41 +00002481void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002482 // Visit all the nodes in topological order, working top-down.
2483 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2484 SUnit *SU = &(*SUnits)[i];
2485 // For now, only look at nodes with no data successors, such as stores.
2486 // These are especially important, due to the heuristics in
2487 // getNodePriority for nodes with no data successors.
2488 if (SU->NumSuccs != 0)
2489 continue;
2490 // For now, only look at nodes with exactly one data predecessor.
2491 if (SU->NumPreds != 1)
2492 continue;
2493 // Avoid prescheduling copies to virtual registers, which don't behave
2494 // like other nodes from the perspective of scheduling heuristics.
2495 if (SDNode *N = SU->getNode())
2496 if (N->getOpcode() == ISD::CopyToReg &&
2497 TargetRegisterInfo::isVirtualRegister
2498 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2499 continue;
2500
2501 // Locate the single data predecessor.
2502 SUnit *PredSU = 0;
2503 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2504 EE = SU->Preds.end(); II != EE; ++II)
2505 if (!II->isCtrl()) {
2506 PredSU = II->getSUnit();
2507 break;
2508 }
2509 assert(PredSU);
2510
2511 // Don't rewrite edges that carry physregs, because that requires additional
2512 // support infrastructure.
2513 if (PredSU->hasPhysRegDefs)
2514 continue;
2515 // Short-circuit the case where SU is PredSU's only data successor.
2516 if (PredSU->NumSuccs == 1)
2517 continue;
2518 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002519 // like other nodes from the perspective of scheduling heuristics.
Dan Gohman9a658d72009-03-24 00:49:12 +00002520 if (SDNode *N = SU->getNode())
2521 if (N->getOpcode() == ISD::CopyFromReg &&
2522 TargetRegisterInfo::isVirtualRegister
2523 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2524 continue;
2525
2526 // Perform checks on the successors of PredSU.
2527 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2528 EE = PredSU->Succs.end(); II != EE; ++II) {
2529 SUnit *PredSuccSU = II->getSUnit();
2530 if (PredSuccSU == SU) continue;
2531 // If PredSU has another successor with no data successors, for
2532 // now don't attempt to choose either over the other.
2533 if (PredSuccSU->NumSuccs == 0)
2534 goto outer_loop_continue;
2535 // Don't break physical register dependencies.
2536 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2537 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2538 goto outer_loop_continue;
2539 // Don't introduce graph cycles.
2540 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2541 goto outer_loop_continue;
2542 }
2543
2544 // Ok, the transformation is safe and the heuristics suggest it is
2545 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002546 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2547 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002548 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002549 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2550 SDep Edge = PredSU->Succs[i];
2551 assert(!Edge.isAssignedRegDep());
2552 SUnit *SuccSU = Edge.getSUnit();
2553 if (SuccSU != SU) {
2554 Edge.setSUnit(PredSU);
2555 scheduleDAG->RemovePred(SuccSU, Edge);
2556 scheduleDAG->AddPred(SU, Edge);
2557 Edge.setSUnit(SU);
2558 scheduleDAG->AddPred(SuccSU, Edge);
2559 --i;
2560 }
2561 }
2562 outer_loop_continue:;
2563 }
2564}
2565
Evan Chengd38c22b2006-05-11 23:55:42 +00002566/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2567/// it as a def&use operand. Add a pseudo control edge from it to the other
2568/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002569/// first (lower in the schedule). If both nodes are two-address, favor the
2570/// one that has a CopyToReg use (more likely to be a loop induction update).
2571/// If both are two-address, but one is commutable while the other is not
2572/// commutable, favor the one that's not commutable.
Andrew Trick9ccce772011-01-14 21:11:41 +00002573void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002574 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002575 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002576 if (!SU->isTwoAddress)
2577 continue;
2578
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002579 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002580 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002581 continue;
2582
Evan Cheng6c1414f2010-10-29 18:09:28 +00002583 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002584 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002585 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002586 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002587 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002588 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002589 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2590 continue;
2591 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2592 if (DU->getNodeId() == -1)
2593 continue;
2594 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2595 if (!DUSU) continue;
2596 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2597 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002598 if (I->isCtrl()) continue;
2599 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002600 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002601 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002602 // Be conservative. Ignore if nodes aren't at roughly the same
2603 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002604 if (SuccSU->getHeight() < SU->getHeight() &&
2605 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002606 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002607 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2608 // constrains whatever is using the copy, instead of the copy
2609 // itself. In the case that the copy is coalesced, this
2610 // preserves the intent of the pseudo two-address heurietics.
2611 while (SuccSU->Succs.size() == 1 &&
2612 SuccSU->getNode()->isMachineOpcode() &&
2613 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002614 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002615 SuccSU = SuccSU->Succs.front().getSUnit();
2616 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002617 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2618 continue;
2619 // Don't constrain nodes with physical register defs if the
2620 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002621 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002622 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002623 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002624 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002625 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2626 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002627 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002628 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2629 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2630 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002631 continue;
2632 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002633 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002634 (!SU->isCommutable && SuccSU->isCommutable)) &&
2635 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002636 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002637 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002638 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002639 /*Reg=*/0, /*isNormalMemory=*/false,
2640 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002641 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002642 }
2643 }
2644 }
2645 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002646}
2647
Roman Levenstein30d09512008-03-27 09:44:37 +00002648/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002649/// predecessors of the successors of the SUnit SU. Stop when the provided
2650/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002651static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002652 unsigned Limit) {
2653 unsigned Sum = 0;
2654 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2655 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002656 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002657 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2658 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002659 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002660 if (!PredSU->isScheduled)
2661 if (++Sum > Limit)
2662 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002663 }
2664 }
2665 return Sum;
2666}
2667
Evan Chengd38c22b2006-05-11 23:55:42 +00002668
2669// Top down
2670bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00002671 unsigned LPriority = SPQ->getNodePriority(left);
2672 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002673 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2674 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002675 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2676 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002677 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2678 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002679
2680 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2681 return false;
2682 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2683 return true;
2684
Evan Chengd38c22b2006-05-11 23:55:42 +00002685 if (LIsFloater)
2686 LBonus -= 2;
2687 if (RIsFloater)
2688 RBonus -= 2;
2689 if (left->NumSuccs == 1)
2690 LBonus += 2;
2691 if (right->NumSuccs == 1)
2692 RBonus += 2;
2693
Evan Cheng73bdf042008-03-01 00:39:47 +00002694 if (LPriority+LBonus != RPriority+RBonus)
2695 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002696
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002697 if (left->getDepth() != right->getDepth())
2698 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002699
2700 if (left->NumSuccsLeft != right->NumSuccsLeft)
2701 return left->NumSuccsLeft > right->NumSuccsLeft;
2702
Andrew Trick2085a962010-12-21 22:25:04 +00002703 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002704 "NodeQueueId cannot be zero");
2705 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002706}
2707
Evan Chengd38c22b2006-05-11 23:55:42 +00002708//===----------------------------------------------------------------------===//
2709// Public Constructor Functions
2710//===----------------------------------------------------------------------===//
2711
Dan Gohmandfaf6462009-02-11 04:27:20 +00002712llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002713llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2714 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002715 const TargetMachine &TM = IS->TM;
2716 const TargetInstrInfo *TII = TM.getInstrInfo();
2717 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002718
Evan Chenga77f3d32010-07-21 06:09:07 +00002719 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002720 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002721 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002722 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002723 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002724}
2725
Dan Gohmandfaf6462009-02-11 04:27:20 +00002726llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002727llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2728 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002729 const TargetMachine &TM = IS->TM;
2730 const TargetInstrInfo *TII = TM.getInstrInfo();
2731 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002732
Evan Chenga77f3d32010-07-21 06:09:07 +00002733 TDRegReductionPriorityQueue *PQ =
2734 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002735 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002736 PQ->setScheduleDAG(SD);
2737 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002738}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002739
2740llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002741llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2742 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002743 const TargetMachine &TM = IS->TM;
2744 const TargetInstrInfo *TII = TM.getInstrInfo();
2745 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002746
Evan Chenga77f3d32010-07-21 06:09:07 +00002747 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002748 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002749 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002750 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002751 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002752}
2753
2754llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002755llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2756 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002757 const TargetMachine &TM = IS->TM;
2758 const TargetInstrInfo *TII = TM.getInstrInfo();
2759 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002760 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002761
Evan Chenga77f3d32010-07-21 06:09:07 +00002762 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002763 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002764
2765 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002766 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002767 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002768}
Evan Cheng37b740c2010-07-24 00:39:05 +00002769
2770llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002771llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2772 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002773 const TargetMachine &TM = IS->TM;
2774 const TargetInstrInfo *TII = TM.getInstrInfo();
2775 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2776 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002777
Evan Cheng37b740c2010-07-24 00:39:05 +00002778 ILPBURRPriorityQueue *PQ =
2779 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002780 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002781 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002782 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002783}