blob: ac2f3d5c8510871b4d786574ffe446ff64680956 [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 Trickb53a00d2011-04-13 00:38:32 +0000105 enum { FactPressureDiff, FactRegUses, FactStall, FactHeight, FactDepth,
106 FactStatic, FactOther, NumFactors };
Andrew Trick641e2d42011-03-05 08:00:22 +0000107}
108static const char *FactorName[NumFactors] =
Andrew Trickb53a00d2011-04-13 00:38:32 +0000109{"PressureDiff", "RegUses", "Stall", "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
Andrew Trickb53a00d2011-04-13 00:38:32 +0000466 // FIXME: Nodes such as CopyFromReg probably should not advance the current
467 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
468 // has predecessors the cycle will be advanced when they are scheduled.
469 // But given the crude nature of modeling latency though such nodes, we
470 // currently need to treat these nodes like real instructions.
471 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
472
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000473 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
474
475 // Bump CurCycle to account for latency. We assume the latency of other
476 // available instructions may be hidden by the stall (not a full pipe stall).
477 // This updates the hazard recognizer's cycle before reserving resources for
478 // this instruction.
479 AdvanceToCycle(ReadyCycle);
480
481 // Calls are scheduled in their preceding cycle, so don't conflict with
482 // hazards from instructions after the call. EmitNode will reset the
483 // scoreboard state before emitting the call.
484 if (isBottomUp && SU->isCall)
485 return;
486
487 // FIXME: For resource conflicts in very long non-pipelined stages, we
488 // should probably skip ahead here to avoid useless scoreboard checks.
489 int Stalls = 0;
490 while (true) {
491 ScheduleHazardRecognizer::HazardType HT =
492 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
493
494 if (HT == ScheduleHazardRecognizer::NoHazard)
495 break;
496
497 ++Stalls;
498 }
499 AdvanceToCycle(CurCycle + Stalls);
500}
501
502/// Record this SUnit in the HazardRecognizer.
503/// Does not update CurCycle.
504void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000505 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000506 return;
507
508 // Check for phys reg copy.
509 if (!SU->getNode())
510 return;
511
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000512 switch (SU->getNode()->getOpcode()) {
513 default:
514 assert(SU->getNode()->isMachineOpcode() &&
515 "This target-independent node should not be scheduled.");
516 break;
517 case ISD::MERGE_VALUES:
518 case ISD::TokenFactor:
519 case ISD::CopyToReg:
520 case ISD::CopyFromReg:
521 case ISD::EH_LABEL:
522 // Noops don't affect the scoreboard state. Copies are likely to be
523 // removed.
524 return;
525 case ISD::INLINEASM:
526 // For inline asm, clear the pipeline state.
527 HazardRec->Reset();
528 return;
529 }
530 if (isBottomUp && SU->isCall) {
531 // Calls are scheduled with their preceding instructions. For bottom-up
532 // scheduling, clear the pipeline state before emitting.
533 HazardRec->Reset();
534 }
535
536 HazardRec->EmitInstruction(SU);
537
538 if (!isBottomUp && SU->isCall) {
539 HazardRec->Reset();
540 }
541}
542
Andrew Trickb53a00d2011-04-13 00:38:32 +0000543static void resetVRegCycle(SUnit *SU);
544
Dan Gohmanb9543432009-02-10 23:27:53 +0000545/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
546/// count of its predecessors. If a predecessor pending count is zero, add it to
547/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000548void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Andrew Trick1b60ad62011-04-12 20:14:07 +0000549 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000550 DEBUG(SU->dump(this));
551
Evan Chengbdd062d2010-05-20 06:13:19 +0000552#ifndef NDEBUG
553 if (CurCycle < SU->getHeight())
Andrew Trickb53a00d2011-04-13 00:38:32 +0000554 DEBUG(dbgs() << " Height [" << SU->getHeight()
555 << "] pipeline stall!\n");
Evan Chengbdd062d2010-05-20 06:13:19 +0000556#endif
557
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000558 // FIXME: Do not modify node height. It may interfere with
559 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
Eric Christopher1b4b1e52011-03-21 18:06:21 +0000560 // node its ready cycle can aid heuristics, and after scheduling it can
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000561 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000562 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000563
564 // Reserve resources for the scheduled intruction.
565 EmitNode(SU);
566
Dan Gohmanb9543432009-02-10 23:27:53 +0000567 Sequence.push_back(SU);
568
Evan Cheng28590382010-07-21 23:53:58 +0000569 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000570
Andrew Trick641e2d42011-03-05 08:00:22 +0000571 // If HazardRec is disabled, and each inst counts as one cycle, then
Andrew Trickb53a00d2011-04-13 00:38:32 +0000572 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000573 // PendingQueue for schedulers that implement HasReadyFilter.
Andrew Trick641e2d42011-03-05 08:00:22 +0000574 if (!HazardRec->isEnabled() && AvgIPC < 2)
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000575 AdvanceToCycle(CurCycle + 1);
576
Andrew Trick033efdf2010-12-23 03:15:51 +0000577 // Update liveness of predecessors before successors to avoid treating a
578 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000579 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000580
581 // Release all the implicit physical register defs that are live.
582 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
583 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000584 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
585 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
586 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
587 --NumLiveRegs;
588 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000589 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000590 }
591 }
592
Andrew Trickb53a00d2011-04-13 00:38:32 +0000593 resetVRegCycle(SU);
594
Evan Chengd38c22b2006-05-11 23:55:42 +0000595 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000596
597 // Conditions under which the scheduler should eagerly advance the cycle:
598 // (1) No available instructions
599 // (2) All pipelines full, so available instructions must have hazards.
600 //
Andrew Trickb53a00d2011-04-13 00:38:32 +0000601 // If HazardRec is disabled, the cycle was pre-advanced before calling
602 // ReleasePredecessors. In that case, IssueCount should remain 0.
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000603 //
604 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
Andrew Trickb53a00d2011-04-13 00:38:32 +0000605 if (HazardRec->isEnabled() || AvgIPC > 1) {
606 if (SU->getNode() && SU->getNode()->isMachineOpcode())
607 ++IssueCount;
608 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
609 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
610 AdvanceToCycle(CurCycle + 1);
611 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000612}
613
Evan Cheng5924bf72007-09-25 01:54:36 +0000614/// CapturePred - This does the opposite of ReleasePred. Since SU is being
615/// unscheduled, incrcease the succ left count of its predecessors. Remove
616/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000617void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000618 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000619 if (PredSU->isAvailable) {
620 PredSU->isAvailable = false;
621 if (!PredSU->isPending)
622 AvailableQueue->remove(PredSU);
623 }
624
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000625 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000626 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000627}
628
629/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
630/// its predecessor states to reflect the change.
631void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000632 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000633 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000634
Evan Cheng5924bf72007-09-25 01:54:36 +0000635 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
636 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000637 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000638 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000639 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000640 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000641 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000642 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000643 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000644 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000645 }
646 }
647
648 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
649 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000650 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000651 // This becomes the nearest def. Note that an earlier def may still be
652 // pending if this is a two-address node.
653 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000654 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000655 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000656 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000657 if (LiveRegGens[I->getReg()] == NULL ||
658 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
659 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000660 }
661 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000662 if (SU->getHeight() < MinAvailableCycle)
663 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000664
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000665 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000666 SU->isScheduled = false;
667 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000668 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000669 // Don't make available until backtracking is complete.
670 SU->isPending = true;
671 PendingQueue.push_back(SU);
672 }
673 else {
674 AvailableQueue->push(SU);
675 }
Evan Cheng28590382010-07-21 23:53:58 +0000676 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000677}
678
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000679/// After backtracking, the hazard checker needs to be restored to a state
680/// corresponding the the current cycle.
681void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
682 HazardRec->Reset();
683
684 unsigned LookAhead = std::min((unsigned)Sequence.size(),
685 HazardRec->getMaxLookAhead());
686 if (LookAhead == 0)
687 return;
688
689 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
690 unsigned HazardCycle = (*I)->getHeight();
691 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
692 SUnit *SU = *I;
693 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
694 HazardRec->RecedeCycle();
695 }
696 EmitNode(SU);
697 }
698}
699
Evan Cheng8e136a92007-09-26 21:36:17 +0000700/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000701/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000702void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
703 SUnit *OldSU = Sequence.back();
704 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000705 Sequence.pop_back();
706 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000707 // Don't try to remove SU from AvailableQueue.
708 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000709 // FIXME: use ready cycle instead of height
710 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000711 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000712 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000713 if (OldSU == BtSU)
714 break;
715 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000716 }
717
Dan Gohman60d68442009-01-29 19:49:27 +0000718 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000719
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000720 RestoreHazardCheckerBottomUp();
721
Andrew Trick5ce945c2010-12-24 07:10:19 +0000722 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000723
Evan Cheng1ec79b42007-09-27 07:09:03 +0000724 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000725}
726
Evan Cheng3b245872010-02-05 01:27:11 +0000727static bool isOperandOf(const SUnit *SU, SDNode *N) {
728 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000729 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000730 if (SUNode->isOperandOf(N))
731 return true;
732 }
733 return false;
734}
735
Evan Cheng5924bf72007-09-25 01:54:36 +0000736/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
737/// successors to the newly created node.
738SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000739 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000740 if (!N)
741 return NULL;
742
Andrew Trickc9405662010-12-24 06:46:50 +0000743 if (SU->getNode()->getGluedNode())
744 return NULL;
745
Evan Cheng79e97132007-10-05 01:39:18 +0000746 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000747 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000748 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000749 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000750 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000751 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000752 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000753 TryUnfold = true;
754 }
Evan Cheng79e97132007-10-05 01:39:18 +0000755 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000756 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000757 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000758 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000759 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000760 }
761
762 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000763 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000764 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000765 return NULL;
766
Evan Chengbdd062d2010-05-20 06:13:19 +0000767 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000768 assert(NewNodes.size() == 2 && "Expected a load folding node!");
769
770 N = NewNodes[1];
771 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000772 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000773 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000774 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000775 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
776 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000777 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000778
Dan Gohmane52e0892008-11-11 21:34:44 +0000779 // LoadNode may already exist. This can happen when there is another
780 // load from the same location and producing the same type of value
781 // but it has different alignment or volatileness.
782 bool isNewLoad = true;
783 SUnit *LoadSU;
784 if (LoadNode->getNodeId() != -1) {
785 LoadSU = &SUnits[LoadNode->getNodeId()];
786 isNewLoad = false;
787 } else {
788 LoadSU = CreateNewSUnit(LoadNode);
789 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000790
791 InitNumRegDefsLeft(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000792 ComputeLatency(LoadSU);
793 }
794
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000795 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000796 assert(N->getNodeId() == -1 && "Node already inserted!");
797 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000798
Dan Gohman17059682008-07-17 19:10:17 +0000799 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000800 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000801 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000802 NewSU->isTwoAddress = true;
803 break;
804 }
805 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000806 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000807 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +0000808
809 InitNumRegDefsLeft(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000810 ComputeLatency(NewSU);
811
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000812 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000813 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000814 SmallVector<SDep, 4> ChainSuccs;
815 SmallVector<SDep, 4> LoadPreds;
816 SmallVector<SDep, 4> NodePreds;
817 SmallVector<SDep, 4> NodeSuccs;
818 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
819 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000820 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000821 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000822 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000823 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000824 else
Dan Gohman2d170892008-12-09 22:54:47 +0000825 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000826 }
827 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
828 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000829 if (I->isCtrl())
830 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000831 else
Dan Gohman2d170892008-12-09 22:54:47 +0000832 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000833 }
834
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000835 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000836 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
837 const SDep &Pred = ChainPreds[i];
838 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000839 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000840 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000841 }
Evan Cheng79e97132007-10-05 01:39:18 +0000842 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000843 const SDep &Pred = LoadPreds[i];
844 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000845 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000846 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000847 }
848 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000849 const SDep &Pred = NodePreds[i];
850 RemovePred(SU, Pred);
851 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000852 }
853 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000854 SDep D = NodeSuccs[i];
855 SUnit *SuccDep = D.getSUnit();
856 D.setSUnit(SU);
857 RemovePred(SuccDep, D);
858 D.setSUnit(NewSU);
859 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000860 // Balance register pressure.
861 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
862 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
863 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +0000864 }
865 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000866 SDep D = ChainSuccs[i];
867 SUnit *SuccDep = D.getSUnit();
868 D.setSUnit(SU);
869 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000870 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000871 D.setSUnit(LoadSU);
872 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000873 }
Andrew Trick2085a962010-12-21 22:25:04 +0000874 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000875
876 // Add a data dependency to reflect that NewSU reads the value defined
877 // by LoadSU.
878 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000879
Evan Cheng91e0fc92007-12-18 08:42:10 +0000880 if (isNewLoad)
881 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000882 AvailableQueue->addNode(NewSU);
883
884 ++NumUnfolds;
885
886 if (NewSU->NumSuccsLeft == 0) {
887 NewSU->isAvailable = true;
888 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000889 }
890 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000891 }
892
Evan Chengbdd062d2010-05-20 06:13:19 +0000893 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000894 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000895
896 // New SUnit has the exact same predecessors.
897 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
898 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000899 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000900 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000901
902 // Only copy scheduled successors. Cut them from old node's successor
903 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000904 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000905 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
906 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000907 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000908 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000909 SUnit *SuccSU = I->getSUnit();
910 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000911 SDep D = *I;
912 D.setSUnit(NewSU);
913 AddPred(SuccSU, D);
914 D.setSUnit(SU);
915 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000916 }
917 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000918 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000919 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000920
921 AvailableQueue->updateNode(SU);
922 AvailableQueue->addNode(NewSU);
923
Evan Cheng1ec79b42007-09-27 07:09:03 +0000924 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000925 return NewSU;
926}
927
Evan Chengb2c42c62009-01-12 03:19:55 +0000928/// InsertCopiesAndMoveSuccs - Insert register copies and move all
929/// scheduled successors of the given SUnit to the last copy.
930void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
931 const TargetRegisterClass *DestRC,
932 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000933 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000934 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000935 CopyFromSU->CopySrcRC = SrcRC;
936 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000937
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000938 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000939 CopyToSU->CopySrcRC = DestRC;
940 CopyToSU->CopyDstRC = SrcRC;
941
942 // Only copy scheduled successors. Cut them from old node's successor
943 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000944 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000945 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
946 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000947 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000948 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000949 SUnit *SuccSU = I->getSUnit();
950 if (SuccSU->isScheduled) {
951 SDep D = *I;
952 D.setSUnit(CopyToSU);
953 AddPred(SuccSU, D);
954 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000955 }
Andrew Trick13acae02011-03-23 20:42:39 +0000956 else {
957 // Avoid scheduling the def-side copy before other successors. Otherwise
958 // we could introduce another physreg interference on the copy and
959 // continue inserting copies indefinitely.
960 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
961 /*Reg=*/0, /*isNormalMemory=*/false,
962 /*isMustAlias=*/false, /*isArtificial=*/true);
963 AddPred(SuccSU, D);
964 }
Evan Cheng8e136a92007-09-26 21:36:17 +0000965 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000966 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000967 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000968
Dan Gohman2d170892008-12-09 22:54:47 +0000969 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
970 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +0000971
972 AvailableQueue->updateNode(SU);
973 AvailableQueue->addNode(CopyFromSU);
974 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000975 Copies.push_back(CopyFromSU);
976 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000977
Evan Chengb2c42c62009-01-12 03:19:55 +0000978 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000979}
980
981/// getPhysicalRegisterVT - Returns the ValueType of the physical register
982/// definition of the specified node.
983/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +0000984static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +0000985 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +0000986 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000987 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000988 unsigned NumRes = TID.getNumDefs();
989 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000990 if (Reg == *ImpDef)
991 break;
992 ++NumRes;
993 }
994 return N->getValueType(NumRes);
995}
996
Evan Chengb8905c42009-03-04 01:41:49 +0000997/// CheckForLiveRegDef - Return true and update live register vector if the
998/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000999static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +00001000 std::vector<SUnit*> &LiveRegDefs,
1001 SmallSet<unsigned, 4> &RegAdded,
1002 SmallVector<unsigned, 4> &LRegs,
1003 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +00001004 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
1005
1006 // Check if Ref is live.
1007 if (!LiveRegDefs[Reg]) continue;
1008
1009 // Allow multiple uses of the same def.
1010 if (LiveRegDefs[Reg] == SU) continue;
1011
1012 // Add Reg to the set of interfering live regs.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001013 if (RegAdded.insert(Reg))
Evan Chengb8905c42009-03-04 01:41:49 +00001014 LRegs.push_back(Reg);
Evan Chengb8905c42009-03-04 01:41:49 +00001015 }
Evan Chengb8905c42009-03-04 01:41:49 +00001016}
1017
Evan Cheng5924bf72007-09-25 01:54:36 +00001018/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1019/// scheduling of the given node to satisfy live physical register dependencies.
1020/// If the specific node is the last one that's available to schedule, do
1021/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001022bool ScheduleDAGRRList::
1023DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +00001024 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +00001025 return false;
1026
Evan Chenge6f92252007-09-27 18:46:06 +00001027 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +00001028 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001029 //
1030 // If SU is the currently live definition of the same register that it uses,
1031 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +00001032 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1033 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001034 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +00001035 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1036 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001037 }
1038
Chris Lattner11a33812010-12-23 17:24:32 +00001039 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +00001040 if (Node->getOpcode() == ISD::INLINEASM) {
1041 // Inline asm can clobber physical defs.
1042 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001043 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +00001044 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +00001045
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001046 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +00001047 unsigned Flags =
1048 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001049 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +00001050
1051 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001052 if (InlineAsm::isRegDefKind(Flags) ||
1053 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +00001054 // Check for def of register or earlyclobber register.
1055 for (; NumVals; --NumVals, ++i) {
1056 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1057 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1058 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1059 }
1060 } else
1061 i += NumVals;
1062 }
1063 continue;
1064 }
1065
Dan Gohman072734e2008-11-13 23:24:17 +00001066 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +00001067 continue;
Dan Gohman17059682008-07-17 19:10:17 +00001068 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +00001069 if (!TID.ImplicitDefs)
1070 continue;
Evan Chengb8905c42009-03-04 01:41:49 +00001071 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
1072 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001073 }
Andrew Trick2085a962010-12-21 22:25:04 +00001074
Evan Cheng5924bf72007-09-25 01:54:36 +00001075 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +00001076}
1077
Andrew Trick528fad92010-12-23 05:42:20 +00001078/// Return a node that can be scheduled in this cycle. Requirements:
1079/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001080/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +00001081/// (3) No Interferences: may unschedule to break register interferences.
1082SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1083 SmallVector<SUnit*, 4> Interferences;
1084 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1085
1086 SUnit *CurSU = AvailableQueue->pop();
1087 while (CurSU) {
1088 SmallVector<unsigned, 4> LRegs;
1089 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1090 break;
1091 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1092
1093 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1094 Interferences.push_back(CurSU);
1095 CurSU = AvailableQueue->pop();
1096 }
1097 if (CurSU) {
1098 // Add the nodes that aren't ready back onto the available list.
1099 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1100 Interferences[i]->isPending = false;
1101 assert(Interferences[i]->isAvailable && "must still be available");
1102 AvailableQueue->push(Interferences[i]);
1103 }
1104 return CurSU;
1105 }
1106
1107 // All candidates are delayed due to live physical reg dependencies.
1108 // Try backtracking, code duplication, or inserting cross class copies
1109 // to resolve it.
1110 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1111 SUnit *TrySU = Interferences[i];
1112 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1113
1114 // Try unscheduling up to the point where it's safe to schedule
1115 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001116 SUnit *BtSU = NULL;
1117 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001118 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1119 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001120 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1121 BtSU = LiveRegGens[Reg];
1122 LiveCycle = BtSU->getHeight();
1123 }
Andrew Trick528fad92010-12-23 05:42:20 +00001124 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001125 if (!WillCreateCycle(TrySU, BtSU)) {
1126 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001127
1128 // Force the current node to be scheduled before the node that
1129 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001130 if (BtSU->isAvailable) {
1131 BtSU->isAvailable = false;
1132 if (!BtSU->isPending)
1133 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001134 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001135 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001136 /*Reg=*/0, /*isNormalMemory=*/false,
1137 /*isMustAlias=*/false, /*isArtificial=*/true));
1138
1139 // If one or more successors has been unscheduled, then the current
1140 // node is no longer avaialable. Schedule a successor that's now
1141 // available instead.
1142 if (!TrySU->isAvailable) {
1143 CurSU = AvailableQueue->pop();
1144 }
1145 else {
1146 CurSU = TrySU;
1147 TrySU->isPending = false;
1148 Interferences.erase(Interferences.begin()+i);
1149 }
1150 break;
1151 }
1152 }
1153
1154 if (!CurSU) {
1155 // Can't backtrack. If it's too expensive to copy the value, then try
1156 // duplicate the nodes that produces these "too expensive to copy"
1157 // values to break the dependency. In case even that doesn't work,
1158 // insert cross class copies.
1159 // If it's not too expensive, i.e. cost != -1, issue copies.
1160 SUnit *TrySU = Interferences[0];
1161 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1162 assert(LRegs.size() == 1 && "Can't handle this yet!");
1163 unsigned Reg = LRegs[0];
1164 SUnit *LRDef = LiveRegDefs[Reg];
1165 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1166 const TargetRegisterClass *RC =
1167 TRI->getMinimalPhysRegClass(Reg, VT);
1168 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1169
Evan Chengb4c6a342011-03-10 00:16:32 +00001170 // If cross copy register class is the same as RC, then it must be possible
1171 // copy the value directly. Do not try duplicate the def.
1172 // If cross copy register class is not the same as RC, then it's possible to
1173 // copy the value but it require cross register class copies and it is
1174 // expensive.
1175 // If cross copy register class is null, then it's not possible to copy
1176 // the value at all.
Andrew Trick528fad92010-12-23 05:42:20 +00001177 SUnit *NewDef = 0;
Evan Chengb4c6a342011-03-10 00:16:32 +00001178 if (DestRC != RC) {
Andrew Trick528fad92010-12-23 05:42:20 +00001179 NewDef = CopyAndMoveSuccessors(LRDef);
Evan Chengb4c6a342011-03-10 00:16:32 +00001180 if (!DestRC && !NewDef)
1181 report_fatal_error("Can't handle live physical register dependency!");
1182 }
Andrew Trick528fad92010-12-23 05:42:20 +00001183 if (!NewDef) {
1184 // Issue copies, these can be expensive cross register class copies.
1185 SmallVector<SUnit*, 2> Copies;
1186 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1187 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1188 << " to SU #" << Copies.front()->NodeNum << "\n");
1189 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1190 /*Reg=*/0, /*isNormalMemory=*/false,
1191 /*isMustAlias=*/false,
1192 /*isArtificial=*/true));
1193 NewDef = Copies.back();
1194 }
1195
1196 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1197 << " to SU #" << TrySU->NodeNum << "\n");
1198 LiveRegDefs[Reg] = NewDef;
1199 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1200 /*Reg=*/0, /*isNormalMemory=*/false,
1201 /*isMustAlias=*/false,
1202 /*isArtificial=*/true));
1203 TrySU->isAvailable = false;
1204 CurSU = NewDef;
1205 }
1206
1207 assert(CurSU && "Unable to resolve live physical register dependencies!");
1208
1209 // Add the nodes that aren't ready back onto the available list.
1210 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1211 Interferences[i]->isPending = false;
1212 // May no longer be available due to backtracking.
1213 if (Interferences[i]->isAvailable) {
1214 AvailableQueue->push(Interferences[i]);
1215 }
1216 }
1217 return CurSU;
1218}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001219
Evan Chengd38c22b2006-05-11 23:55:42 +00001220/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1221/// schedulers.
1222void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001223 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001224 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001225
Evan Chengd38c22b2006-05-11 23:55:42 +00001226 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001227 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001228 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001229 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1230 RootSU->isAvailable = true;
1231 AvailableQueue->push(RootSU);
1232 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001233
1234 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001235 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001236 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001237 while (!AvailableQueue->empty()) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00001238 DEBUG(dbgs() << "\nExamining Available:\n";
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001239 AvailableQueue->dump(this));
1240
Andrew Trick528fad92010-12-23 05:42:20 +00001241 // Pick the best node to schedule taking all constraints into
1242 // consideration.
1243 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001244
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001245 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001246
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001247 ScheduleNodeBottomUp(SU);
1248
1249 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1250 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1251 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1252 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1253 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001254 }
1255
Evan Chengd38c22b2006-05-11 23:55:42 +00001256 // Reverse the order if it is bottom up.
1257 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001258
Evan Chengd38c22b2006-05-11 23:55:42 +00001259#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001260 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001261#endif
1262}
1263
1264//===----------------------------------------------------------------------===//
1265// Top-Down Scheduling
1266//===----------------------------------------------------------------------===//
1267
1268/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001269/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001270void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001271 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001272
Evan Chengd38c22b2006-05-11 23:55:42 +00001273#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001274 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001275 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001276 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001277 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001278 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001279 }
1280#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001281 --SuccSU->NumPredsLeft;
1282
Dan Gohmanb9543432009-02-10 23:27:53 +00001283 // If all the node's predecessors are scheduled, this node is ready
1284 // to be scheduled. Ignore the special ExitSU node.
1285 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001286 SuccSU->isAvailable = true;
1287 AvailableQueue->push(SuccSU);
1288 }
1289}
1290
Dan Gohmanb9543432009-02-10 23:27:53 +00001291void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1292 // Top down: release successors
1293 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1294 I != E; ++I) {
1295 assert(!I->isAssignedRegDep() &&
1296 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1297
1298 ReleaseSucc(SU, &*I);
1299 }
1300}
1301
Evan Chengd38c22b2006-05-11 23:55:42 +00001302/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1303/// count of its successors. If a successor pending count is zero, add it to
1304/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001305void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001306 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001307 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001308
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001309 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1310 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001311 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001312
Dan Gohmanb9543432009-02-10 23:27:53 +00001313 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001314 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001315 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001316}
1317
Dan Gohman54a187e2007-08-20 19:28:38 +00001318/// ListScheduleTopDown - The main loop of list scheduling for top-down
1319/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001320void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001321 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001322
Dan Gohmanb9543432009-02-10 23:27:53 +00001323 // Release any successors of the special Entry node.
1324 ReleaseSuccessors(&EntrySU);
1325
Evan Chengd38c22b2006-05-11 23:55:42 +00001326 // All leaves to Available queue.
1327 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1328 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001329 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001330 AvailableQueue->push(&SUnits[i]);
1331 SUnits[i].isAvailable = true;
1332 }
1333 }
Andrew Trick2085a962010-12-21 22:25:04 +00001334
Evan Chengd38c22b2006-05-11 23:55:42 +00001335 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001336 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001337 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001338 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001339 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001340
Dan Gohmanc602dd42008-11-21 00:10:42 +00001341 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001342 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001343 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001344 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001345 }
Andrew Trick2085a962010-12-21 22:25:04 +00001346
Evan Chengd38c22b2006-05-11 23:55:42 +00001347#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001348 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001349#endif
1350}
1351
1352
Evan Chengd38c22b2006-05-11 23:55:42 +00001353//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001354// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001355//===----------------------------------------------------------------------===//
1356//
1357// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1358// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001359//
Evan Chengd38c22b2006-05-11 23:55:42 +00001360namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001361class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001362
Andrew Trick9ccce772011-01-14 21:11:41 +00001363struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1364 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1365};
1366
1367/// bu_ls_rr_sort - Priority function for bottom up register pressure
1368// reduction scheduler.
1369struct bu_ls_rr_sort : public queue_sort {
1370 enum {
1371 IsBottomUp = true,
1372 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001373 };
1374
Andrew Trick9ccce772011-01-14 21:11:41 +00001375 RegReductionPQBase *SPQ;
1376 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1377 bu_ls_rr_sort(const bu_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()(SUnit* left, SUnit* right) const;
1380};
Andrew Trick2085a962010-12-21 22:25:04 +00001381
Andrew Trick9ccce772011-01-14 21:11:41 +00001382// td_ls_rr_sort - Priority function for top down register pressure reduction
1383// scheduler.
1384struct td_ls_rr_sort : public queue_sort {
1385 enum {
1386 IsBottomUp = false,
1387 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001388 };
1389
Andrew Trick9ccce772011-01-14 21:11:41 +00001390 RegReductionPQBase *SPQ;
1391 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1392 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001393
Andrew Trick9ccce772011-01-14 21:11:41 +00001394 bool operator()(const SUnit* left, const SUnit* right) const;
1395};
Andrew Trick2085a962010-12-21 22:25:04 +00001396
Andrew Trick9ccce772011-01-14 21:11:41 +00001397// src_ls_rr_sort - Priority function for source order scheduler.
1398struct src_ls_rr_sort : public queue_sort {
1399 enum {
1400 IsBottomUp = true,
1401 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001402 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001403
Andrew Trick9ccce772011-01-14 21:11:41 +00001404 RegReductionPQBase *SPQ;
1405 src_ls_rr_sort(RegReductionPQBase *spq)
1406 : SPQ(spq) {}
1407 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1408 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001409
Andrew Trick9ccce772011-01-14 21:11:41 +00001410 bool operator()(SUnit* left, SUnit* right) const;
1411};
Andrew Trick2085a962010-12-21 22:25:04 +00001412
Andrew Trick9ccce772011-01-14 21:11:41 +00001413// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1414struct hybrid_ls_rr_sort : public queue_sort {
1415 enum {
1416 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001417 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001418 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001419
Andrew Trick9ccce772011-01-14 21:11:41 +00001420 RegReductionPQBase *SPQ;
1421 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1422 : SPQ(spq) {}
1423 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1424 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001425
Andrew Trick9ccce772011-01-14 21:11:41 +00001426 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001427
Andrew Trick9ccce772011-01-14 21:11:41 +00001428 bool operator()(SUnit* left, SUnit* right) const;
1429};
1430
1431// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1432// scheduler.
1433struct ilp_ls_rr_sort : public queue_sort {
1434 enum {
1435 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001436 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001437 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001438
Andrew Trick9ccce772011-01-14 21:11:41 +00001439 RegReductionPQBase *SPQ;
1440 ilp_ls_rr_sort(RegReductionPQBase *spq)
1441 : SPQ(spq) {}
1442 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1443 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001444
Andrew Trick9ccce772011-01-14 21:11:41 +00001445 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001446
Andrew Trick9ccce772011-01-14 21:11:41 +00001447 bool operator()(SUnit* left, SUnit* right) const;
1448};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001449
Andrew Trick9ccce772011-01-14 21:11:41 +00001450class RegReductionPQBase : public SchedulingPriorityQueue {
1451protected:
1452 std::vector<SUnit*> Queue;
1453 unsigned CurQueueId;
1454 bool TracksRegPressure;
1455
1456 // SUnits - The SUnits for the current graph.
1457 std::vector<SUnit> *SUnits;
1458
1459 MachineFunction &MF;
1460 const TargetInstrInfo *TII;
1461 const TargetRegisterInfo *TRI;
1462 const TargetLowering *TLI;
1463 ScheduleDAGRRList *scheduleDAG;
1464
1465 // SethiUllmanNumbers - The SethiUllman number for each node.
1466 std::vector<unsigned> SethiUllmanNumbers;
1467
1468 /// RegPressure - Tracking current reg pressure per register class.
1469 ///
1470 std::vector<unsigned> RegPressure;
1471
1472 /// RegLimit - Tracking the number of allocatable registers per register
1473 /// class.
1474 std::vector<unsigned> RegLimit;
1475
1476public:
1477 RegReductionPQBase(MachineFunction &mf,
1478 bool hasReadyFilter,
1479 bool tracksrp,
1480 const TargetInstrInfo *tii,
1481 const TargetRegisterInfo *tri,
1482 const TargetLowering *tli)
1483 : SchedulingPriorityQueue(hasReadyFilter),
1484 CurQueueId(0), TracksRegPressure(tracksrp),
1485 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1486 if (TracksRegPressure) {
1487 unsigned NumRC = TRI->getNumRegClasses();
1488 RegLimit.resize(NumRC);
1489 RegPressure.resize(NumRC);
1490 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1491 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1492 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1493 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +00001494 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
Andrew Trick9ccce772011-01-14 21:11:41 +00001495 }
1496 }
1497
1498 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1499 scheduleDAG = scheduleDag;
1500 }
1501
1502 ScheduleHazardRecognizer* getHazardRec() {
1503 return scheduleDAG->getHazardRec();
1504 }
1505
1506 void initNodes(std::vector<SUnit> &sunits);
1507
1508 void addNode(const SUnit *SU);
1509
1510 void updateNode(const SUnit *SU);
1511
1512 void releaseState() {
1513 SUnits = 0;
1514 SethiUllmanNumbers.clear();
1515 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1516 }
1517
1518 unsigned getNodePriority(const SUnit *SU) const;
1519
1520 unsigned getNodeOrdering(const SUnit *SU) const {
Andrew Trick3bd8b7a2011-03-25 06:40:55 +00001521 if (!SU->getNode()) return 0;
1522
Andrew Trick9ccce772011-01-14 21:11:41 +00001523 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1524 }
1525
1526 bool empty() const { return Queue.empty(); }
1527
1528 void push(SUnit *U) {
1529 assert(!U->NodeQueueId && "Node in the queue already");
1530 U->NodeQueueId = ++CurQueueId;
1531 Queue.push_back(U);
1532 }
1533
1534 void remove(SUnit *SU) {
1535 assert(!Queue.empty() && "Queue is empty!");
1536 assert(SU->NodeQueueId != 0 && "Not in queue!");
1537 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1538 SU);
1539 if (I != prior(Queue.end()))
1540 std::swap(*I, Queue.back());
1541 Queue.pop_back();
1542 SU->NodeQueueId = 0;
1543 }
1544
Andrew Trickd0548ae2011-02-04 03:18:17 +00001545 bool tracksRegPressure() const { return TracksRegPressure; }
1546
Andrew Trick9ccce772011-01-14 21:11:41 +00001547 void dumpRegPressure() const;
1548
1549 bool HighRegPressure(const SUnit *SU) const;
1550
Andrew Trick641e2d42011-03-05 08:00:22 +00001551 bool MayReduceRegPressure(SUnit *SU) const;
1552
1553 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
Andrew Trick9ccce772011-01-14 21:11:41 +00001554
1555 void ScheduledNode(SUnit *SU);
1556
1557 void UnscheduledNode(SUnit *SU);
1558
1559protected:
1560 bool canClobber(const SUnit *SU, const SUnit *Op);
1561 void AddPseudoTwoAddrDeps();
1562 void PrescheduleNodesWithMultipleUses();
1563 void CalculateSethiUllmanNumbers();
1564};
1565
1566template<class SF>
1567class RegReductionPriorityQueue : public RegReductionPQBase {
1568 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1569 std::vector<SUnit *>::iterator Best = Q.begin();
1570 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1571 E = Q.end(); I != E; ++I)
1572 if (Picker(*Best, *I))
1573 Best = I;
1574 SUnit *V = *Best;
1575 if (Best != prior(Q.end()))
1576 std::swap(*Best, Q.back());
1577 Q.pop_back();
1578 return V;
1579 }
1580
1581 SF Picker;
1582
1583public:
1584 RegReductionPriorityQueue(MachineFunction &mf,
1585 bool tracksrp,
1586 const TargetInstrInfo *tii,
1587 const TargetRegisterInfo *tri,
1588 const TargetLowering *tli)
1589 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1590 Picker(this) {}
1591
1592 bool isBottomUp() const { return SF::IsBottomUp; }
1593
1594 bool isReady(SUnit *U) const {
1595 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1596 }
1597
1598 SUnit *pop() {
1599 if (Queue.empty()) return NULL;
1600
1601 SUnit *V = popFromQueue(Queue, Picker);
1602 V->NodeQueueId = 0;
1603 return V;
1604 }
1605
1606 void dump(ScheduleDAG *DAG) const {
1607 // Emulate pop() without clobbering NodeQueueIds.
1608 std::vector<SUnit*> DumpQueue = Queue;
1609 SF DumpPicker = Picker;
1610 while (!DumpQueue.empty()) {
1611 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1612 if (isBottomUp())
1613 dbgs() << "Height " << SU->getHeight() << ": ";
1614 else
1615 dbgs() << "Depth " << SU->getDepth() << ": ";
1616 SU->dump(DAG);
1617 }
1618 }
1619};
1620
1621typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1622BURegReductionPriorityQueue;
1623
1624typedef RegReductionPriorityQueue<td_ls_rr_sort>
1625TDRegReductionPriorityQueue;
1626
1627typedef RegReductionPriorityQueue<src_ls_rr_sort>
1628SrcRegReductionPriorityQueue;
1629
1630typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1631HybridBURRPriorityQueue;
1632
1633typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1634ILPBURRPriorityQueue;
1635} // end anonymous namespace
1636
1637//===----------------------------------------------------------------------===//
1638// Static Node Priority for Register Pressure Reduction
1639//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001640
Dan Gohman186f65d2008-11-20 03:30:37 +00001641/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1642/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001643static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001644CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001645 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1646 if (SethiUllmanNumber != 0)
1647 return SethiUllmanNumber;
1648
1649 unsigned Extra = 0;
1650 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1651 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001652 if (I->isCtrl()) continue; // ignore chain preds
1653 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001654 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001655 if (PredSethiUllman > SethiUllmanNumber) {
1656 SethiUllmanNumber = PredSethiUllman;
1657 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001658 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001659 ++Extra;
1660 }
1661
1662 SethiUllmanNumber += Extra;
1663
1664 if (SethiUllmanNumber == 0)
1665 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001666
Evan Cheng7e4abde2008-07-02 09:23:51 +00001667 return SethiUllmanNumber;
1668}
1669
Andrew Trick9ccce772011-01-14 21:11:41 +00001670/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1671/// scheduling units.
1672void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1673 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001674
Andrew Trick9ccce772011-01-14 21:11:41 +00001675 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1676 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001677}
1678
Andrew Trick9ccce772011-01-14 21:11:41 +00001679void RegReductionPQBase::addNode(const SUnit *SU) {
1680 unsigned SUSize = SethiUllmanNumbers.size();
1681 if (SUnits->size() > SUSize)
1682 SethiUllmanNumbers.resize(SUSize*2, 0);
1683 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1684}
1685
1686void RegReductionPQBase::updateNode(const SUnit *SU) {
1687 SethiUllmanNumbers[SU->NodeNum] = 0;
1688 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1689}
1690
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001691// Lower priority means schedule further down. For bottom-up scheduling, lower
1692// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001693unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1694 assert(SU->NodeNum < SethiUllmanNumbers.size());
1695 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1696 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1697 // CopyToReg should be close to its uses to facilitate coalescing and
1698 // avoid spilling.
1699 return 0;
1700 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1701 Opc == TargetOpcode::SUBREG_TO_REG ||
1702 Opc == TargetOpcode::INSERT_SUBREG)
1703 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1704 // close to their uses to facilitate coalescing.
1705 return 0;
1706 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1707 // If SU does not have a register use, i.e. it doesn't produce a value
1708 // that would be consumed (e.g. store), then it terminates a chain of
1709 // computation. Give it a large SethiUllman number so it will be
1710 // scheduled right before its predecessors that it doesn't lengthen
1711 // their live ranges.
1712 return 0xffff;
1713 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1714 // If SU does not have a register def, schedule it close to its uses
1715 // because it does not lengthen any live ranges.
1716 return 0;
1717 return SethiUllmanNumbers[SU->NodeNum];
1718}
1719
1720//===----------------------------------------------------------------------===//
1721// Register Pressure Tracking
1722//===----------------------------------------------------------------------===//
1723
1724void RegReductionPQBase::dumpRegPressure() const {
1725 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1726 E = TRI->regclass_end(); I != E; ++I) {
1727 const TargetRegisterClass *RC = *I;
1728 unsigned Id = RC->getID();
1729 unsigned RP = RegPressure[Id];
1730 if (!RP) continue;
1731 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1732 << '\n');
1733 }
1734}
1735
1736bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1737 if (!TLI)
1738 return false;
1739
1740 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1741 I != E; ++I) {
1742 if (I->isCtrl())
1743 continue;
1744 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001745 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1746 // to cover the number of registers defined (they are all live).
1747 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001748 continue;
1749 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001750 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1751 RegDefPos.IsValid(); RegDefPos.Advance()) {
1752 EVT VT = RegDefPos.GetValue();
Andrew Trick9ccce772011-01-14 21:11:41 +00001753 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1754 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Andrew Trick9ccce772011-01-14 21:11:41 +00001755 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1756 return true;
1757 }
1758 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001759 return false;
1760}
1761
Andrew Trick641e2d42011-03-05 08:00:22 +00001762bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00001763 const SDNode *N = SU->getNode();
1764
1765 if (!N->isMachineOpcode() || !SU->NumSuccs)
1766 return false;
1767
1768 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1769 for (unsigned i = 0; i != NumDefs; ++i) {
1770 EVT VT = N->getValueType(i);
1771 if (!N->hasAnyUseOfValue(i))
1772 continue;
1773 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1774 if (RegPressure[RCId] >= RegLimit[RCId])
1775 return true;
1776 }
1777 return false;
1778}
1779
Andrew Trick641e2d42011-03-05 08:00:22 +00001780// Compute the register pressure contribution by this instruction by count up
1781// for uses that are not live and down for defs. Only count register classes
1782// that are already under high pressure. As a side effect, compute the number of
1783// uses of registers that are already live.
1784//
1785// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1786// so could probably be factored.
1787int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1788 LiveUses = 0;
1789 int PDiff = 0;
1790 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1791 I != E; ++I) {
1792 if (I->isCtrl())
1793 continue;
1794 SUnit *PredSU = I->getSUnit();
1795 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1796 // to cover the number of registers defined (they are all live).
1797 if (PredSU->NumRegDefsLeft == 0) {
1798 if (PredSU->getNode()->isMachineOpcode())
1799 ++LiveUses;
1800 continue;
1801 }
1802 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1803 RegDefPos.IsValid(); RegDefPos.Advance()) {
1804 EVT VT = RegDefPos.GetValue();
1805 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1806 if (RegPressure[RCId] >= RegLimit[RCId])
1807 ++PDiff;
1808 }
1809 }
1810 const SDNode *N = SU->getNode();
1811
Eric Christopher7238cba2011-03-08 19:35:47 +00001812 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
Andrew Trick641e2d42011-03-05 08:00:22 +00001813 return PDiff;
1814
1815 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1816 for (unsigned i = 0; i != NumDefs; ++i) {
1817 EVT VT = N->getValueType(i);
1818 if (!N->hasAnyUseOfValue(i))
1819 continue;
1820 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1821 if (RegPressure[RCId] >= RegLimit[RCId])
1822 --PDiff;
1823 }
1824 return PDiff;
1825}
1826
Andrew Trick9ccce772011-01-14 21:11:41 +00001827void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1828 if (!TracksRegPressure)
1829 return;
1830
Eric Christopher7238cba2011-03-08 19:35:47 +00001831 if (!SU->getNode())
1832 return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001833
Andrew Trick9ccce772011-01-14 21:11:41 +00001834 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1835 I != E; ++I) {
1836 if (I->isCtrl())
1837 continue;
1838 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001839 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1840 // to cover the number of registers defined (they are all live).
1841 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001842 continue;
1843 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001844 // FIXME: The ScheduleDAG currently loses information about which of a
1845 // node's values is consumed by each dependence. Consequently, if the node
1846 // defines multiple register classes, we don't know which to pressurize
1847 // here. Instead the following loop consumes the register defs in an
1848 // arbitrary order. At least it handles the common case of clustered loads
1849 // to the same class. For precise liveness, each SDep needs to indicate the
1850 // result number. But that tightly couples the ScheduleDAG with the
1851 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1852 // value type or register class to SDep.
1853 //
1854 // The most important aspect of register tracking is balancing the increase
1855 // here with the reduction further below. Note that this SU may use multiple
1856 // defs in PredSU. The can't be determined here, but we've already
1857 // compensated by reducing NumRegDefsLeft in PredSU during
1858 // ScheduleDAGSDNodes::AddSchedEdges.
1859 --PredSU->NumRegDefsLeft;
1860 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1861 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1862 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1863 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00001864 continue;
Andrew Trickd0548ae2011-02-04 03:18:17 +00001865 EVT VT = RegDefPos.GetValue();
Andrew Trick9ccce772011-01-14 21:11:41 +00001866 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1867 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001868 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00001869 }
1870 }
1871
Andrew Trickd0548ae2011-02-04 03:18:17 +00001872 // We should have this assert, but there may be dead SDNodes that never
1873 // materialize as SUnits, so they don't appear to generate liveness.
1874 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1875 int SkipRegDefs = (int)SU->NumRegDefsLeft;
1876 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1877 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1878 if (SkipRegDefs > 0)
1879 continue;
1880 EVT VT = RegDefPos.GetValue();
1881 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1882 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT)) {
1883 // Register pressure tracking is imprecise. This can happen. But we try
1884 // hard not to let it happen because it likely results in poor scheduling.
1885 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
1886 RegPressure[RCId] = 0;
1887 }
1888 else {
1889 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
Andrew Trick9ccce772011-01-14 21:11:41 +00001890 }
1891 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001892 dumpRegPressure();
1893}
1894
1895void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1896 if (!TracksRegPressure)
1897 return;
1898
1899 const SDNode *N = SU->getNode();
Eric Christopher7238cba2011-03-08 19:35:47 +00001900 if (!N) return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001901
Andrew Trick9ccce772011-01-14 21:11:41 +00001902 if (!N->isMachineOpcode()) {
1903 if (N->getOpcode() != ISD::CopyToReg)
1904 return;
1905 } else {
1906 unsigned Opc = N->getMachineOpcode();
1907 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1908 Opc == TargetOpcode::INSERT_SUBREG ||
1909 Opc == TargetOpcode::SUBREG_TO_REG ||
1910 Opc == TargetOpcode::REG_SEQUENCE ||
1911 Opc == TargetOpcode::IMPLICIT_DEF)
1912 return;
1913 }
1914
1915 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1916 I != E; ++I) {
1917 if (I->isCtrl())
1918 continue;
1919 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001920 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1921 // counts data deps.
1922 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00001923 continue;
1924 const SDNode *PN = PredSU->getNode();
1925 if (!PN->isMachineOpcode()) {
1926 if (PN->getOpcode() == ISD::CopyFromReg) {
1927 EVT VT = PN->getValueType(0);
1928 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1929 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1930 }
1931 continue;
1932 }
1933 unsigned POpc = PN->getMachineOpcode();
1934 if (POpc == TargetOpcode::IMPLICIT_DEF)
1935 continue;
1936 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1937 EVT VT = PN->getOperand(0).getValueType();
1938 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1939 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1940 continue;
1941 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1942 POpc == TargetOpcode::SUBREG_TO_REG) {
1943 EVT VT = PN->getValueType(0);
1944 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1945 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1946 continue;
1947 }
1948 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1949 for (unsigned i = 0; i != NumDefs; ++i) {
1950 EVT VT = PN->getValueType(i);
1951 if (!PN->hasAnyUseOfValue(i))
1952 continue;
1953 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1954 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1955 // Register pressure tracking is imprecise. This can happen.
1956 RegPressure[RCId] = 0;
1957 else
1958 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1959 }
1960 }
1961
1962 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1963 // may transfer data dependencies to CopyToReg.
1964 if (SU->NumSuccs && N->isMachineOpcode()) {
1965 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1966 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1967 EVT VT = N->getValueType(i);
1968 if (VT == MVT::Glue || VT == MVT::Other)
1969 continue;
1970 if (!N->hasAnyUseOfValue(i))
1971 continue;
1972 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1973 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1974 }
1975 }
1976
1977 dumpRegPressure();
1978}
1979
1980//===----------------------------------------------------------------------===//
1981// Dynamic Node Priority for Register Pressure Reduction
1982//===----------------------------------------------------------------------===//
1983
Evan Chengb9e3db62007-03-14 22:43:40 +00001984/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00001985/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001986static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001987 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00001988 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001989 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00001990 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001991 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00001992 // If there are bunch of CopyToRegs stacked up, they should be considered
1993 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00001994 if (I->getSUnit()->getNode() &&
1995 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001996 Height = closestSucc(I->getSUnit())+1;
1997 if (Height > MaxHeight)
1998 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00001999 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002000 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00002001}
2002
Evan Cheng61bc51e2007-12-20 02:22:36 +00002003/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00002004/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00002005static unsigned calcMaxScratches(const SUnit *SU) {
2006 unsigned Scratches = 0;
2007 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00002008 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002009 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00002010 Scratches++;
2011 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00002012 return Scratches;
2013}
2014
Andrew Trickb53a00d2011-04-13 00:38:32 +00002015/// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2016/// CopyFromReg from a virtual register.
2017static bool hasOnlyLiveInOpers(const SUnit *SU) {
2018 bool RetVal = false;
2019 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2020 I != E; ++I) {
2021 if (I->isCtrl()) continue;
2022 const SUnit *PredSU = I->getSUnit();
2023 if (PredSU->getNode() &&
2024 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2025 unsigned Reg =
2026 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2027 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2028 RetVal = true;
2029 continue;
2030 }
2031 }
2032 return false;
2033 }
2034 return RetVal;
2035}
2036
2037/// hasOnlyLiveOutUses - Return true if SU has only value successors that are
Evan Cheng6c1414f2010-10-29 18:09:28 +00002038/// CopyToReg to a virtual register. This SU def is probably a liveout and
2039/// it has no other use. It should be scheduled closer to the terminator.
2040static bool hasOnlyLiveOutUses(const SUnit *SU) {
2041 bool RetVal = false;
2042 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2043 I != E; ++I) {
2044 if (I->isCtrl()) continue;
2045 const SUnit *SuccSU = I->getSUnit();
2046 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2047 unsigned Reg =
2048 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2049 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2050 RetVal = true;
2051 continue;
2052 }
2053 }
2054 return false;
2055 }
2056 return RetVal;
2057}
2058
Andrew Trickb53a00d2011-04-13 00:38:32 +00002059// Set isVRegCycle for a node with only live in opers and live out uses. Also
2060// set isVRegCycle for its CopyFromReg operands.
2061//
2062// This is only relevant for single-block loops, in which case the VRegCycle
2063// node is likely an induction variable in which the operand and target virtual
2064// registers should be coalesced (e.g. pre/post increment values). Setting the
2065// isVRegCycle flag helps the scheduler prioritize other uses of the same
2066// CopyFromReg so that this node becomes the virtual register "kill". This
2067// avoids interference between the values live in and out of the block and
2068// eliminates a copy inside the loop.
2069static void initVRegCycle(SUnit *SU) {
2070 if (DisableSchedVRegCycle)
2071 return;
2072
2073 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2074 return;
2075
2076 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2077
2078 SU->isVRegCycle = true;
2079
2080 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002081 I != E; ++I) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002082 if (I->isCtrl()) continue;
2083 I->getSUnit()->isVRegCycle = true;
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002084 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002085}
2086
Andrew Trickb53a00d2011-04-13 00:38:32 +00002087// After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2088// CopyFromReg operands. We should no longer penalize other uses of this VReg.
2089static void resetVRegCycle(SUnit *SU) {
2090 if (!SU->isVRegCycle)
2091 return;
2092
2093 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2094 I != E; ++I) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002095 if (I->isCtrl()) continue; // ignore chain preds
Andrew Trickb53a00d2011-04-13 00:38:32 +00002096 SUnit *PredSU = I->getSUnit();
2097 if (PredSU->isVRegCycle) {
2098 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2099 "VRegCycle def must be CopyFromReg");
2100 I->getSUnit()->isVRegCycle = 0;
2101 }
2102 }
2103}
2104
2105// Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2106// means a node that defines the VRegCycle has not been scheduled yet.
2107static bool hasVRegCycleUse(const SUnit *SU) {
2108 // If this SU also defines the VReg, don't hoist it as a "use".
2109 if (SU->isVRegCycle)
2110 return false;
2111
2112 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2113 I != E; ++I) {
2114 if (I->isCtrl()) continue; // ignore chain preds
2115 if (I->getSUnit()->isVRegCycle &&
2116 I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2117 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2118 return true;
Andrew Trick2ad0b372011-04-07 19:54:57 +00002119 }
2120 }
2121 return false;
2122}
2123
Andrew Trick9ccce772011-01-14 21:11:41 +00002124// Check for either a dependence (latency) or resource (hazard) stall.
2125//
2126// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2127static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2128 if ((int)SPQ->getCurCycle() < Height) return true;
2129 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2130 != ScheduleHazardRecognizer::NoHazard)
2131 return true;
2132 return false;
2133}
2134
2135// Return -1 if left has higher priority, 1 if right has higher priority.
2136// Return 0 if latency-based priority is equivalent.
2137static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2138 RegReductionPQBase *SPQ) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002139 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2140 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2141 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2142 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2143 int LHeight = (int)left->getHeight() + LPenalty;
2144 int RHeight = (int)right->getHeight() + RPenalty;
Andrew Trick9ccce772011-01-14 21:11:41 +00002145
2146 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
2147 BUHasStall(left, LHeight, SPQ);
2148 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2149 BUHasStall(right, RHeight, SPQ);
2150
2151 // If scheduling one of the node will cause a pipeline stall, delay it.
2152 // If scheduling either one of the node will cause a pipeline stall, sort
2153 // them according to their height.
2154 if (LStall) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002155 if (!RStall) {
2156 DEBUG(++FactorCount[FactStall]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002157 return 1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002158 }
2159 if (LHeight != RHeight) {
2160 DEBUG(++FactorCount[FactStall]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002161 return LHeight > RHeight ? 1 : -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002162 }
2163 } else if (RStall) {
2164 DEBUG(++FactorCount[FactStall]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002165 return -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002166 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002167
Andrew Trick47ff14b2011-01-21 05:51:33 +00002168 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002169 // and latency.
2170 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2171 right->SchedulingPref == Sched::Latency)) {
Andrew Trick47ff14b2011-01-21 05:51:33 +00002172 if (DisableSchedCycles) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002173 if (LHeight != RHeight) {
2174 DEBUG(++FactorCount[FactHeight]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002175 return LHeight > RHeight ? 1 : -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002176 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002177 }
Andrew Trick47ff14b2011-01-21 05:51:33 +00002178 else {
2179 // If neither instruction stalls (!LStall && !RStall) then
Eric Christopher9cb33de2011-03-06 21:13:45 +00002180 // its height is already covered so only its depth matters. We also reach
Andrew Trick47ff14b2011-01-21 05:51:33 +00002181 // this if both stall but have the same height.
Andrew Trickb53a00d2011-04-13 00:38:32 +00002182 int LDepth = left->getDepth() - LPenalty;
2183 int RDepth = right->getDepth() - RPenalty;
Andrew Trick47ff14b2011-01-21 05:51:33 +00002184 if (LDepth != RDepth) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002185 DEBUG(++FactorCount[FactDepth]);
Andrew Trick47ff14b2011-01-21 05:51:33 +00002186 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2187 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2188 << ") depth " << RDepth << "\n");
2189 return LDepth < RDepth ? 1 : -1;
2190 }
2191 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002192 if (left->Latency != right->Latency) {
2193 DEBUG(++FactorCount[FactOther]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002194 return left->Latency > right->Latency ? 1 : -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002195 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002196 }
2197 return 0;
2198}
2199
2200static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Evan Cheng6730f032007-01-08 23:55:53 +00002201 unsigned LPriority = SPQ->getNodePriority(left);
2202 unsigned RPriority = SPQ->getNodePriority(right);
Andrew Trick641e2d42011-03-05 08:00:22 +00002203 if (LPriority != RPriority) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002204 DEBUG(++FactorCount[FactStatic]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002205 return LPriority > RPriority;
Andrew Trick641e2d42011-03-05 08:00:22 +00002206 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002207 else if(LPriority == 0) {
2208 // Schedule zero-latency TokenFactor below any other special
2209 // nodes. The alternative may be to avoid artificially boosting the
2210 // TokenFactor's height when it is scheduled, but we currently rely on an
2211 // instruction's final height to equal the cycle in which it is scheduled,
2212 // so heights are monotonically increasing.
2213 unsigned LOpc = left->getNode() ? left->getNode()->getOpcode() : 0;
2214 unsigned ROpc = right->getNode() ? right->getNode()->getOpcode() : 0;
2215 if (LOpc == ISD::TokenFactor)
2216 return false;
2217 if (ROpc == ISD::TokenFactor)
2218 return true;
2219 }
Andrew Trick52b3e382011-03-08 01:51:56 +00002220
Evan Cheng73bdf042008-03-01 00:39:47 +00002221 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2222 // e.g.
2223 // t1 = op t2, c1
2224 // t3 = op t4, c2
2225 //
2226 // and the following instructions are both ready.
2227 // t2 = op c3
2228 // t4 = op c4
2229 //
2230 // Then schedule t2 = op first.
2231 // i.e.
2232 // t4 = op c4
2233 // t2 = op c3
2234 // t1 = op t2, c1
2235 // t3 = op t4, c2
2236 //
2237 // This creates more short live intervals.
2238 unsigned LDist = closestSucc(left);
2239 unsigned RDist = closestSucc(right);
Andrew Trickb53a00d2011-04-13 00:38:32 +00002240 if (LDist != RDist) {
2241 DEBUG(++FactorCount[FactOther]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002242 return LDist < RDist;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002243 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002244
Evan Cheng3a14efa2009-02-12 08:59:45 +00002245 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002246 unsigned LScratch = calcMaxScratches(left);
2247 unsigned RScratch = calcMaxScratches(right);
Andrew Trickb53a00d2011-04-13 00:38:32 +00002248 if (LScratch != RScratch) {
2249 DEBUG(++FactorCount[FactOther]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002250 return LScratch > RScratch;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002251 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002252
Andrew Trick47ff14b2011-01-21 05:51:33 +00002253 if (!DisableSchedCycles) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002254 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2255 if (result != 0)
2256 return result > 0;
2257 }
2258 else {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002259 if (left->getHeight() != right->getHeight()) {
2260 DEBUG(++FactorCount[FactHeight]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002261 return left->getHeight() > right->getHeight();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002262 }
Andrew Trick2085a962010-12-21 22:25:04 +00002263
Andrew Trickb53a00d2011-04-13 00:38:32 +00002264 if (left->getDepth() != right->getDepth()) {
2265 DEBUG(++FactorCount[FactDepth]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002266 return left->getDepth() < right->getDepth();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002267 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002268 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002269
Andrew Trick2085a962010-12-21 22:25:04 +00002270 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002271 "NodeQueueId cannot be zero");
Andrew Trickb53a00d2011-04-13 00:38:32 +00002272 DEBUG(++FactorCount[FactOther]);
Roman Levenstein6b371142008-04-29 09:07:59 +00002273 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002274}
2275
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002276// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002277bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002278 return BURRSort(left, right, SPQ);
2279}
2280
2281// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002282bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002283 unsigned LOrder = SPQ->getNodeOrdering(left);
2284 unsigned ROrder = SPQ->getNodeOrdering(right);
2285
2286 // Prefer an ordering where the lower the non-zero order number, the higher
2287 // the preference.
2288 if ((LOrder || ROrder) && LOrder != ROrder)
2289 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2290
2291 return BURRSort(left, right, SPQ);
2292}
2293
Andrew Trick9ccce772011-01-14 21:11:41 +00002294// If the time between now and when the instruction will be ready can cover
2295// the spill code, then avoid adding it to the ready queue. This gives long
2296// stalls highest priority and allows hoisting across calls. It should also
2297// speed up processing the available queue.
2298bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2299 static const unsigned ReadyDelay = 3;
2300
2301 if (SPQ->MayReduceRegPressure(SU)) return true;
2302
2303 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2304
2305 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2306 != ScheduleHazardRecognizer::NoHazard)
2307 return false;
2308
2309 return true;
2310}
2311
2312// Return true if right should be scheduled with higher priority than left.
2313bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002314 if (left->isCall || right->isCall)
2315 // No way to compute latency of calls.
2316 return BURRSort(left, right, SPQ);
2317
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002318 bool LHigh = SPQ->HighRegPressure(left);
2319 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002320 // Avoid causing spills. If register pressure is high, schedule for
2321 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002322 if (LHigh && !RHigh) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002323 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002324 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2325 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002326 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002327 }
2328 else if (!LHigh && RHigh) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002329 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002330 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2331 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002332 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002333 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002334 if (!LHigh && !RHigh) {
2335 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2336 if (result != 0)
2337 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002338 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002339 return BURRSort(left, right, SPQ);
2340}
2341
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002342// Schedule as many instructions in each cycle as possible. So don't make an
2343// instruction available unless it is ready in the current cycle.
2344bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002345 if (SU->getHeight() > CurCycle) return false;
2346
2347 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2348 != ScheduleHazardRecognizer::NoHazard)
2349 return false;
2350
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002351 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002352}
2353
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002354static bool canEnableCoalescing(SUnit *SU) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002355 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2356 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2357 // CopyToReg should be close to its uses to facilitate coalescing and
2358 // avoid spilling.
2359 return true;
2360
2361 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2362 Opc == TargetOpcode::SUBREG_TO_REG ||
2363 Opc == TargetOpcode::INSERT_SUBREG)
2364 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2365 // close to their uses to facilitate coalescing.
2366 return true;
2367
2368 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2369 // If SU does not have a register def, schedule it close to its uses
2370 // because it does not lengthen any live ranges.
2371 return true;
2372
2373 return false;
2374}
2375
Andrew Trickb8390b72011-03-05 08:04:11 +00002376// list-ilp is currently an experimental scheduler that allows various
2377// heuristics to be enabled prior to the normal register reduction logic.
Andrew Trick9ccce772011-01-14 21:11:41 +00002378bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002379 if (left->isCall || right->isCall)
2380 // No way to compute latency of calls.
2381 return BURRSort(left, right, SPQ);
2382
Andrew Trick52b3e382011-03-08 01:51:56 +00002383 unsigned LLiveUses = 0, RLiveUses = 0;
2384 int LPDiff = 0, RPDiff = 0;
2385 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2386 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2387 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2388 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002389 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2390 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick52b3e382011-03-08 01:51:56 +00002391 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2392 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002393 return LPDiff > RPDiff;
2394 }
2395
Andrew Trick52b3e382011-03-08 01:51:56 +00002396 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002397 bool LReduce = canEnableCoalescing(left);
2398 bool RReduce = canEnableCoalescing(right);
Andrew Trick52b3e382011-03-08 01:51:56 +00002399 DEBUG(if (LReduce != RReduce) ++FactorCount[FactPressureDiff]);
2400 if (LReduce && !RReduce) return false;
2401 if (RReduce && !LReduce) return true;
2402 }
2403
2404 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2405 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2406 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002407 DEBUG(++FactorCount[FactRegUses]);
2408 return LLiveUses < RLiveUses;
2409 }
2410
Andrew Trick52b3e382011-03-08 01:51:56 +00002411 if (!DisableSchedStalls) {
2412 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2413 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2414 if (LStall != RStall) {
2415 DEBUG(++FactorCount[FactHeight]);
2416 return left->getHeight() > right->getHeight();
2417 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002418 }
2419
Andrew Trick25cedf32011-03-05 10:29:25 +00002420 if (!DisableSchedCriticalPath) {
2421 int spread = (int)left->getDepth() - (int)right->getDepth();
2422 if (std::abs(spread) > MaxReorderWindow) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002423 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2424 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2425 << right->getDepth() << "\n");
Andrew Trick25cedf32011-03-05 10:29:25 +00002426 DEBUG(++FactorCount[FactDepth]);
2427 return left->getDepth() < right->getDepth();
2428 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002429 }
2430
2431 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002432 int spread = (int)left->getHeight() - (int)right->getHeight();
2433 if (std::abs(spread) > MaxReorderWindow) {
2434 DEBUG(++FactorCount[FactHeight]);
2435 return left->getHeight() > right->getHeight();
2436 }
Evan Cheng37b740c2010-07-24 00:39:05 +00002437 }
2438
2439 return BURRSort(left, right, SPQ);
2440}
2441
Andrew Trickb53a00d2011-04-13 00:38:32 +00002442void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2443 SUnits = &sunits;
2444 // Add pseudo dependency edges for two-address nodes.
2445 AddPseudoTwoAddrDeps();
2446 // Reroute edges to nodes with multiple uses.
2447 if (!TracksRegPressure)
2448 PrescheduleNodesWithMultipleUses();
2449 // Calculate node priorities.
2450 CalculateSethiUllmanNumbers();
2451
2452 // For single block loops, mark nodes that look like canonical IV increments.
2453 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2454 for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2455 initVRegCycle(&sunits[i]);
2456 }
2457 }
2458}
2459
Andrew Trick9ccce772011-01-14 21:11:41 +00002460//===----------------------------------------------------------------------===//
2461// Preschedule for Register Pressure
2462//===----------------------------------------------------------------------===//
2463
2464bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002465 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002466 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002467 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002468 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002469 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002470 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002471 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002472 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002473 if (DU->getNodeId() != -1 &&
2474 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002475 return true;
2476 }
2477 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002478 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002479 return false;
2480}
2481
Evan Chengf9891412007-12-20 09:25:31 +00002482/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002483/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002484static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002485 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002486 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002487 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002488 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2489 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002490 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002491 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002492 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002493 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002494 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002495 const unsigned *SUImpDefs =
2496 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2497 if (!SUImpDefs)
2498 return false;
2499 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002500 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002501 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002502 continue;
2503 if (!N->hasAnyUseOfValue(i))
2504 continue;
2505 unsigned Reg = ImpDefs[i - NumDefs];
2506 for (;*SUImpDefs; ++SUImpDefs) {
2507 unsigned SUReg = *SUImpDefs;
2508 if (TRI->regsOverlap(Reg, SUReg))
2509 return true;
2510 }
Evan Chengf9891412007-12-20 09:25:31 +00002511 }
2512 }
2513 return false;
2514}
2515
Dan Gohman9a658d72009-03-24 00:49:12 +00002516/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2517/// are not handled well by the general register pressure reduction
2518/// heuristics. When presented with code like this:
2519///
2520/// N
2521/// / |
2522/// / |
2523/// U store
2524/// |
2525/// ...
2526///
2527/// the heuristics tend to push the store up, but since the
2528/// operand of the store has another use (U), this would increase
2529/// the length of that other use (the U->N edge).
2530///
2531/// This function transforms code like the above to route U's
2532/// dependence through the store when possible, like this:
2533///
2534/// N
2535/// ||
2536/// ||
2537/// store
2538/// |
2539/// U
2540/// |
2541/// ...
2542///
2543/// This results in the store being scheduled immediately
2544/// after N, which shortens the U->N live range, reducing
2545/// register pressure.
2546///
Andrew Trick9ccce772011-01-14 21:11:41 +00002547void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002548 // Visit all the nodes in topological order, working top-down.
2549 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2550 SUnit *SU = &(*SUnits)[i];
2551 // For now, only look at nodes with no data successors, such as stores.
2552 // These are especially important, due to the heuristics in
2553 // getNodePriority for nodes with no data successors.
2554 if (SU->NumSuccs != 0)
2555 continue;
2556 // For now, only look at nodes with exactly one data predecessor.
2557 if (SU->NumPreds != 1)
2558 continue;
2559 // Avoid prescheduling copies to virtual registers, which don't behave
2560 // like other nodes from the perspective of scheduling heuristics.
2561 if (SDNode *N = SU->getNode())
2562 if (N->getOpcode() == ISD::CopyToReg &&
2563 TargetRegisterInfo::isVirtualRegister
2564 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2565 continue;
2566
2567 // Locate the single data predecessor.
2568 SUnit *PredSU = 0;
2569 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2570 EE = SU->Preds.end(); II != EE; ++II)
2571 if (!II->isCtrl()) {
2572 PredSU = II->getSUnit();
2573 break;
2574 }
2575 assert(PredSU);
2576
2577 // Don't rewrite edges that carry physregs, because that requires additional
2578 // support infrastructure.
2579 if (PredSU->hasPhysRegDefs)
2580 continue;
2581 // Short-circuit the case where SU is PredSU's only data successor.
2582 if (PredSU->NumSuccs == 1)
2583 continue;
2584 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002585 // like other nodes from the perspective of scheduling heuristics.
Dan Gohman9a658d72009-03-24 00:49:12 +00002586 if (SDNode *N = SU->getNode())
2587 if (N->getOpcode() == ISD::CopyFromReg &&
2588 TargetRegisterInfo::isVirtualRegister
2589 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2590 continue;
2591
2592 // Perform checks on the successors of PredSU.
2593 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2594 EE = PredSU->Succs.end(); II != EE; ++II) {
2595 SUnit *PredSuccSU = II->getSUnit();
2596 if (PredSuccSU == SU) continue;
2597 // If PredSU has another successor with no data successors, for
2598 // now don't attempt to choose either over the other.
2599 if (PredSuccSU->NumSuccs == 0)
2600 goto outer_loop_continue;
2601 // Don't break physical register dependencies.
2602 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2603 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2604 goto outer_loop_continue;
2605 // Don't introduce graph cycles.
2606 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2607 goto outer_loop_continue;
2608 }
2609
2610 // Ok, the transformation is safe and the heuristics suggest it is
2611 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002612 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2613 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002614 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002615 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2616 SDep Edge = PredSU->Succs[i];
2617 assert(!Edge.isAssignedRegDep());
2618 SUnit *SuccSU = Edge.getSUnit();
2619 if (SuccSU != SU) {
2620 Edge.setSUnit(PredSU);
2621 scheduleDAG->RemovePred(SuccSU, Edge);
2622 scheduleDAG->AddPred(SU, Edge);
2623 Edge.setSUnit(SU);
2624 scheduleDAG->AddPred(SuccSU, Edge);
2625 --i;
2626 }
2627 }
2628 outer_loop_continue:;
2629 }
2630}
2631
Evan Chengd38c22b2006-05-11 23:55:42 +00002632/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2633/// it as a def&use operand. Add a pseudo control edge from it to the other
2634/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002635/// first (lower in the schedule). If both nodes are two-address, favor the
2636/// one that has a CopyToReg use (more likely to be a loop induction update).
2637/// If both are two-address, but one is commutable while the other is not
2638/// commutable, favor the one that's not commutable.
Andrew Trick9ccce772011-01-14 21:11:41 +00002639void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002640 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002641 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002642 if (!SU->isTwoAddress)
2643 continue;
2644
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002645 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002646 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002647 continue;
2648
Evan Cheng6c1414f2010-10-29 18:09:28 +00002649 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002650 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002651 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002652 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002653 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002654 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002655 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2656 continue;
2657 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2658 if (DU->getNodeId() == -1)
2659 continue;
2660 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2661 if (!DUSU) continue;
2662 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2663 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002664 if (I->isCtrl()) continue;
2665 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002666 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002667 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002668 // Be conservative. Ignore if nodes aren't at roughly the same
2669 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002670 if (SuccSU->getHeight() < SU->getHeight() &&
2671 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002672 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002673 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2674 // constrains whatever is using the copy, instead of the copy
2675 // itself. In the case that the copy is coalesced, this
2676 // preserves the intent of the pseudo two-address heurietics.
2677 while (SuccSU->Succs.size() == 1 &&
2678 SuccSU->getNode()->isMachineOpcode() &&
2679 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002680 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002681 SuccSU = SuccSU->Succs.front().getSUnit();
2682 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002683 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2684 continue;
2685 // Don't constrain nodes with physical register defs if the
2686 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002687 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002688 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002689 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002690 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002691 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2692 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002693 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002694 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2695 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2696 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002697 continue;
2698 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002699 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002700 (!SU->isCommutable && SuccSU->isCommutable)) &&
2701 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002702 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002703 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002704 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002705 /*Reg=*/0, /*isNormalMemory=*/false,
2706 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002707 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002708 }
2709 }
2710 }
2711 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002712}
2713
Roman Levenstein30d09512008-03-27 09:44:37 +00002714/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002715/// predecessors of the successors of the SUnit SU. Stop when the provided
2716/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002717static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002718 unsigned Limit) {
2719 unsigned Sum = 0;
2720 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2721 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002722 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002723 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2724 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002725 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002726 if (!PredSU->isScheduled)
2727 if (++Sum > Limit)
2728 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002729 }
2730 }
2731 return Sum;
2732}
2733
Evan Chengd38c22b2006-05-11 23:55:42 +00002734
2735// Top down
2736bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00002737 unsigned LPriority = SPQ->getNodePriority(left);
2738 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002739 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2740 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002741 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2742 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002743 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2744 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002745
2746 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2747 return false;
2748 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2749 return true;
2750
Evan Chengd38c22b2006-05-11 23:55:42 +00002751 if (LIsFloater)
2752 LBonus -= 2;
2753 if (RIsFloater)
2754 RBonus -= 2;
2755 if (left->NumSuccs == 1)
2756 LBonus += 2;
2757 if (right->NumSuccs == 1)
2758 RBonus += 2;
2759
Evan Cheng73bdf042008-03-01 00:39:47 +00002760 if (LPriority+LBonus != RPriority+RBonus)
2761 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002762
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002763 if (left->getDepth() != right->getDepth())
2764 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002765
2766 if (left->NumSuccsLeft != right->NumSuccsLeft)
2767 return left->NumSuccsLeft > right->NumSuccsLeft;
2768
Andrew Trick2085a962010-12-21 22:25:04 +00002769 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002770 "NodeQueueId cannot be zero");
2771 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002772}
2773
Evan Chengd38c22b2006-05-11 23:55:42 +00002774//===----------------------------------------------------------------------===//
2775// Public Constructor Functions
2776//===----------------------------------------------------------------------===//
2777
Dan Gohmandfaf6462009-02-11 04:27:20 +00002778llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002779llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2780 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002781 const TargetMachine &TM = IS->TM;
2782 const TargetInstrInfo *TII = TM.getInstrInfo();
2783 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002784
Evan Chenga77f3d32010-07-21 06:09:07 +00002785 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002786 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002787 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002788 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002789 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002790}
2791
Dan Gohmandfaf6462009-02-11 04:27:20 +00002792llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002793llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2794 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002795 const TargetMachine &TM = IS->TM;
2796 const TargetInstrInfo *TII = TM.getInstrInfo();
2797 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002798
Evan Chenga77f3d32010-07-21 06:09:07 +00002799 TDRegReductionPriorityQueue *PQ =
2800 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002801 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002802 PQ->setScheduleDAG(SD);
2803 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002804}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002805
2806llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002807llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2808 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002809 const TargetMachine &TM = IS->TM;
2810 const TargetInstrInfo *TII = TM.getInstrInfo();
2811 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002812
Evan Chenga77f3d32010-07-21 06:09:07 +00002813 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002814 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002815 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002816 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002817 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002818}
2819
2820llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002821llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2822 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002823 const TargetMachine &TM = IS->TM;
2824 const TargetInstrInfo *TII = TM.getInstrInfo();
2825 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002826 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002827
Evan Chenga77f3d32010-07-21 06:09:07 +00002828 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002829 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002830
2831 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002832 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002833 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002834}
Evan Cheng37b740c2010-07-24 00:39:05 +00002835
2836llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002837llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2838 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002839 const TargetMachine &TM = IS->TM;
2840 const TargetInstrInfo *TII = TM.getInstrInfo();
2841 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2842 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002843
Evan Cheng37b740c2010-07-24 00:39:05 +00002844 ILPBURRPriorityQueue *PQ =
2845 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002846 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002847 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002848 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002849}