blob: d253b3148bd6988f0ddb05c3d53caa34a365bb46 [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
Evan Chengd38c22b2006-05-11 23:55:42 +000073namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +000074//===----------------------------------------------------------------------===//
75/// ScheduleDAGRRList - The actual register reduction list scheduler
76/// implementation. This supports both top-down and bottom-up scheduling.
77///
Nick Lewycky02d5f772009-10-25 06:33:48 +000078class ScheduleDAGRRList : public ScheduleDAGSDNodes {
Evan Chengd38c22b2006-05-11 23:55:42 +000079private:
80 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
81 /// it is top-down.
82 bool isBottomUp;
Evan Cheng2c977312008-07-01 18:05:03 +000083
Evan Chengbdd062d2010-05-20 06:13:19 +000084 /// NeedLatency - True if the scheduler will make use of latency information.
85 ///
86 bool NeedLatency;
87
Evan Chengd38c22b2006-05-11 23:55:42 +000088 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +000089 SchedulingPriorityQueue *AvailableQueue;
90
Andrew Trick10ffc2b2010-12-24 05:03:26 +000091 /// PendingQueue - This contains all of the instructions whose operands have
92 /// been issued, but their results are not ready yet (due to the latency of
93 /// the operation). Once the operands becomes available, the instruction is
94 /// added to the AvailableQueue.
95 std::vector<SUnit*> PendingQueue;
96
97 /// HazardRec - The hazard recognizer to use.
98 ScheduleHazardRecognizer *HazardRec;
99
Andrew Trick528fad92010-12-23 05:42:20 +0000100 /// CurCycle - The current scheduler state corresponds to this cycle.
101 unsigned CurCycle;
102
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000103 /// MinAvailableCycle - Cycle of the soonest available instruction.
104 unsigned MinAvailableCycle;
105
Dan Gohmanc07f6862008-09-23 18:50:48 +0000106 /// LiveRegDefs - A set of physical registers and their definition
Evan Cheng5924bf72007-09-25 01:54:36 +0000107 /// that are "live". These nodes must be scheduled before any other nodes that
108 /// modifies the registers can be scheduled.
Dan Gohmanc07f6862008-09-23 18:50:48 +0000109 unsigned NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000110 std::vector<SUnit*> LiveRegDefs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000111 std::vector<SUnit*> LiveRegGens;
Evan Cheng5924bf72007-09-25 01:54:36 +0000112
Dan Gohmanad2134d2008-11-25 00:52:40 +0000113 /// Topo - A topological ordering for SUnits which permits fast IsReachable
114 /// and similar queries.
115 ScheduleDAGTopologicalSort Topo;
116
Evan Chengd38c22b2006-05-11 23:55:42 +0000117public:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000118 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
119 SchedulingPriorityQueue *availqueue,
120 CodeGenOpt::Level OptLevel)
121 : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
122 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
123 Topo(SUnits) {
124
125 const TargetMachine &tm = mf.getTarget();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000126 if (DisableSchedCycles || !NeedLatency)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000127 HazardRec = new ScheduleHazardRecognizer();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000128 else
129 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000130 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000131
132 ~ScheduleDAGRRList() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000133 delete HazardRec;
Evan Chengd38c22b2006-05-11 23:55:42 +0000134 delete AvailableQueue;
135 }
136
137 void Schedule();
138
Andrew Trick9ccce772011-01-14 21:11:41 +0000139 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
140
Roman Levenstein733a4d62008-03-26 11:23:38 +0000141 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000142 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
143 return Topo.IsReachable(SU, TargetSU);
144 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000145
Dan Gohman60d68442009-01-29 19:49:27 +0000146 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000147 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000148 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
149 return Topo.WillCreateCycle(SU, TargetSU);
150 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000151
Dan Gohman2d170892008-12-09 22:54:47 +0000152 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000153 /// This returns true if this is a new predecessor.
154 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000155 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000156 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000157 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000158 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000159
Dan Gohman2d170892008-12-09 22:54:47 +0000160 /// RemovePred - removes a predecessor edge from SUnit SU.
161 /// This returns true if an edge was removed.
162 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000163 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000164 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000165 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000166 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000167
Evan Chengd38c22b2006-05-11 23:55:42 +0000168private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000169 bool isReady(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000170 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000171 AvailableQueue->isReady(SU);
172 }
173
Dan Gohman60d68442009-01-29 19:49:27 +0000174 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000175 void ReleasePredecessors(SUnit *SU);
Dan Gohman60d68442009-01-29 19:49:27 +0000176 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
Dan Gohmanb9543432009-02-10 23:27:53 +0000177 void ReleaseSuccessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000178 void ReleasePending();
179 void AdvanceToCycle(unsigned NextCycle);
180 void AdvancePastStalls(SUnit *SU);
181 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000182 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000183 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000184 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000185 void RestoreHazardCheckerBottomUp();
186 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000187 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000188 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
189 const TargetRegisterClass*,
190 const TargetRegisterClass*,
191 SmallVector<SUnit*, 2>&);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000192 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000193
Andrew Trick528fad92010-12-23 05:42:20 +0000194 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000195 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000196
Andrew Trick528fad92010-12-23 05:42:20 +0000197 void ScheduleNodeTopDown(SUnit*);
198 void ListScheduleTopDown();
199
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000200
201 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000202 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000203 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000204 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000205 SUnit *NewNode = NewSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000206 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000207 if (NewNode->NodeNum >= NumSUnits)
208 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000209 return NewNode;
210 }
211
Roman Levenstein733a4d62008-03-26 11:23:38 +0000212 /// CreateClone - Creates a new SUnit from an existing one.
213 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000214 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000215 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000216 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000217 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000218 if (NewNode->NodeNum >= NumSUnits)
219 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000220 return NewNode;
221 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000222
Evan Chengbdd062d2010-05-20 06:13:19 +0000223 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
224 /// need actual latency information but the hybrid scheduler does.
225 bool ForceUnitLatencies() const {
226 return !NeedLatency;
227 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000228};
229} // end anonymous namespace
230
231
232/// Schedule - Schedule the DAG using list scheduling.
233void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000234 DEBUG(dbgs()
235 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000236 << " '" << BB->getName() << "' **********\n");
Evan Cheng5924bf72007-09-25 01:54:36 +0000237
Andrew Trick528fad92010-12-23 05:42:20 +0000238 CurCycle = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000239 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000240 NumLiveRegs = 0;
Andrew Trick2085a962010-12-21 22:25:04 +0000241 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
Andrew Tricka52f3252010-12-23 04:16:14 +0000242 LiveRegGens.resize(TRI->getNumRegs(), NULL);
Evan Cheng5924bf72007-09-25 01:54:36 +0000243
Dan Gohman04543e72008-12-23 18:36:58 +0000244 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000245 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000246
Evan Chengd38c22b2006-05-11 23:55:42 +0000247 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000248 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000249 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000250
Dan Gohman46520a22008-06-21 19:18:17 +0000251 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000252
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000253 HazardRec->Reset();
254
Evan Chengd38c22b2006-05-11 23:55:42 +0000255 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
256 if (isBottomUp)
257 ListScheduleBottomUp();
258 else
259 ListScheduleTopDown();
Andrew Trick2085a962010-12-21 22:25:04 +0000260
Evan Chengd38c22b2006-05-11 23:55:42 +0000261 AvailableQueue->releaseState();
Evan Chengafed73e2006-05-12 01:58:24 +0000262}
Evan Chengd38c22b2006-05-11 23:55:42 +0000263
264//===----------------------------------------------------------------------===//
265// Bottom-Up Scheduling
266//===----------------------------------------------------------------------===//
267
Evan Chengd38c22b2006-05-11 23:55:42 +0000268/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000269/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000270void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000271 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000272
Evan Chengd38c22b2006-05-11 23:55:42 +0000273#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000274 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000275 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000276 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000277 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000278 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000279 }
280#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000281 --PredSU->NumSuccsLeft;
282
Evan Chengbdd062d2010-05-20 06:13:19 +0000283 if (!ForceUnitLatencies()) {
284 // Updating predecessor's height. This is now the cycle when the
285 // predecessor can be scheduled without causing a pipeline stall.
286 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
287 }
288
Dan Gohmanb9543432009-02-10 23:27:53 +0000289 // If all the node's successors are scheduled, this node is ready
290 // to be scheduled. Ignore the special EntrySU node.
291 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000292 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000293
294 unsigned Height = PredSU->getHeight();
295 if (Height < MinAvailableCycle)
296 MinAvailableCycle = Height;
297
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000298 if (isReady(PredSU)) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000299 AvailableQueue->push(PredSU);
300 }
301 // CapturePred and others may have left the node in the pending queue, avoid
302 // adding it twice.
303 else if (!PredSU->isPending) {
304 PredSU->isPending = true;
305 PendingQueue.push_back(PredSU);
306 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000307 }
308}
309
Andrew Trick033efdf2010-12-23 03:15:51 +0000310/// Call ReleasePred for each predecessor, then update register live def/gen.
311/// Always update LiveRegDefs for a register dependence even if the current SU
312/// also defines the register. This effectively create one large live range
313/// across a sequence of two-address node. This is important because the
314/// entire chain must be scheduled together. Example:
315///
316/// flags = (3) add
317/// flags = (2) addc flags
318/// flags = (1) addc flags
319///
320/// results in
321///
322/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000323/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000324///
325/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
326/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000327void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000328 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000329 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000330 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000331 ReleasePred(SU, &*I);
332 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000333 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000334 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000335 // clobber the register is scheduled between the predecessor and
336 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000337 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000338 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
339 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000340 LiveRegDefs[I->getReg()] = I->getSUnit();
341 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000342 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000343 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000344 }
345 }
346 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000347}
348
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000349/// Check to see if any of the pending instructions are ready to issue. If
350/// so, add them to the available queue.
351void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000352 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000353 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
354 return;
355 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000356
357 // If the available queue is empty, it is safe to reset MinAvailableCycle.
358 if (AvailableQueue->empty())
359 MinAvailableCycle = UINT_MAX;
360
361 // Check to see if any of the pending instructions are ready to issue. If
362 // so, add them to the available queue.
363 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
364 unsigned ReadyCycle =
365 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
366 if (ReadyCycle < MinAvailableCycle)
367 MinAvailableCycle = ReadyCycle;
368
369 if (PendingQueue[i]->isAvailable) {
370 if (!isReady(PendingQueue[i]))
371 continue;
372 AvailableQueue->push(PendingQueue[i]);
373 }
374 PendingQueue[i]->isPending = false;
375 PendingQueue[i] = PendingQueue.back();
376 PendingQueue.pop_back();
377 --i; --e;
378 }
379}
380
381/// Move the scheduler state forward by the specified number of Cycles.
382void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
383 if (NextCycle <= CurCycle)
384 return;
385
386 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000387 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000388 // Bypass lots of virtual calls in case of long latency.
389 CurCycle = NextCycle;
390 }
391 else {
392 for (; CurCycle != NextCycle; ++CurCycle) {
393 if (isBottomUp)
394 HazardRec->RecedeCycle();
395 else
396 HazardRec->AdvanceCycle();
397 }
398 }
399 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
400 // available Q to release pending nodes at least once before popping.
401 ReleasePending();
402}
403
404/// Move the scheduler state forward until the specified node's dependents are
405/// ready and can be scheduled with no resource conflicts.
406void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000407 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000408 return;
409
410 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
411
412 // Bump CurCycle to account for latency. We assume the latency of other
413 // available instructions may be hidden by the stall (not a full pipe stall).
414 // This updates the hazard recognizer's cycle before reserving resources for
415 // this instruction.
416 AdvanceToCycle(ReadyCycle);
417
418 // Calls are scheduled in their preceding cycle, so don't conflict with
419 // hazards from instructions after the call. EmitNode will reset the
420 // scoreboard state before emitting the call.
421 if (isBottomUp && SU->isCall)
422 return;
423
424 // FIXME: For resource conflicts in very long non-pipelined stages, we
425 // should probably skip ahead here to avoid useless scoreboard checks.
426 int Stalls = 0;
427 while (true) {
428 ScheduleHazardRecognizer::HazardType HT =
429 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
430
431 if (HT == ScheduleHazardRecognizer::NoHazard)
432 break;
433
434 ++Stalls;
435 }
436 AdvanceToCycle(CurCycle + Stalls);
437}
438
439/// Record this SUnit in the HazardRecognizer.
440/// Does not update CurCycle.
441void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000442 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000443 return;
444
445 // Check for phys reg copy.
446 if (!SU->getNode())
447 return;
448
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000449 switch (SU->getNode()->getOpcode()) {
450 default:
451 assert(SU->getNode()->isMachineOpcode() &&
452 "This target-independent node should not be scheduled.");
453 break;
454 case ISD::MERGE_VALUES:
455 case ISD::TokenFactor:
456 case ISD::CopyToReg:
457 case ISD::CopyFromReg:
458 case ISD::EH_LABEL:
459 // Noops don't affect the scoreboard state. Copies are likely to be
460 // removed.
461 return;
462 case ISD::INLINEASM:
463 // For inline asm, clear the pipeline state.
464 HazardRec->Reset();
465 return;
466 }
467 if (isBottomUp && SU->isCall) {
468 // Calls are scheduled with their preceding instructions. For bottom-up
469 // scheduling, clear the pipeline state before emitting.
470 HazardRec->Reset();
471 }
472
473 HazardRec->EmitInstruction(SU);
474
475 if (!isBottomUp && SU->isCall) {
476 HazardRec->Reset();
477 }
478}
479
Dan Gohmanb9543432009-02-10 23:27:53 +0000480/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
481/// count of its predecessors. If a predecessor pending count is zero, add it to
482/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000483void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000484 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000485 DEBUG(SU->dump(this));
486
Evan Chengbdd062d2010-05-20 06:13:19 +0000487#ifndef NDEBUG
488 if (CurCycle < SU->getHeight())
489 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
490#endif
491
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000492 // FIXME: Do not modify node height. It may interfere with
493 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
494 // node it's ready cycle can aid heuristics, and after scheduling it can
495 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000496 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000497
498 // Reserve resources for the scheduled intruction.
499 EmitNode(SU);
500
Dan Gohmanb9543432009-02-10 23:27:53 +0000501 Sequence.push_back(SU);
502
Evan Cheng28590382010-07-21 23:53:58 +0000503 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000504
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000505 // If HazardRec is disabled, count each inst as one cycle.
506 // Advance CurCycle before ReleasePredecessors to avoid useles pushed to
507 // PendingQueue for schedulers that implement HasReadyFilter.
508 if (!HazardRec->isEnabled())
509 AdvanceToCycle(CurCycle + 1);
510
Andrew Trick033efdf2010-12-23 03:15:51 +0000511 // Update liveness of predecessors before successors to avoid treating a
512 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000513 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000514
515 // Release all the implicit physical register defs that are live.
516 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
517 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000518 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
519 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
520 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
521 --NumLiveRegs;
522 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000523 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000524 }
525 }
526
Evan Chengd38c22b2006-05-11 23:55:42 +0000527 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000528
529 // Conditions under which the scheduler should eagerly advance the cycle:
530 // (1) No available instructions
531 // (2) All pipelines full, so available instructions must have hazards.
532 //
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000533 // If HazardRec is disabled, the cycle was advanced earlier.
534 //
535 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
536 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
Andrew Trick47ff14b2011-01-21 05:51:33 +0000537 || AvailableQueue->empty())
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000538 AdvanceToCycle(CurCycle + 1);
Evan Chengd38c22b2006-05-11 23:55:42 +0000539}
540
Evan Cheng5924bf72007-09-25 01:54:36 +0000541/// CapturePred - This does the opposite of ReleasePred. Since SU is being
542/// unscheduled, incrcease the succ left count of its predecessors. Remove
543/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000544void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000545 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000546 if (PredSU->isAvailable) {
547 PredSU->isAvailable = false;
548 if (!PredSU->isPending)
549 AvailableQueue->remove(PredSU);
550 }
551
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000552 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000553 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000554}
555
556/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
557/// its predecessor states to reflect the change.
558void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000559 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000560 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000561
Evan Cheng5924bf72007-09-25 01:54:36 +0000562 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
563 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000564 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000565 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000566 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000567 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000568 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000569 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000570 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000571 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000572 }
573 }
574
575 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
576 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000577 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000578 // This becomes the nearest def. Note that an earlier def may still be
579 // pending if this is a two-address node.
580 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000581 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000582 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000583 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000584 if (LiveRegGens[I->getReg()] == NULL ||
585 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
586 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000587 }
588 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000589 if (SU->getHeight() < MinAvailableCycle)
590 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000591
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000592 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000593 SU->isScheduled = false;
594 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000595 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000596 // Don't make available until backtracking is complete.
597 SU->isPending = true;
598 PendingQueue.push_back(SU);
599 }
600 else {
601 AvailableQueue->push(SU);
602 }
Evan Cheng28590382010-07-21 23:53:58 +0000603 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000604}
605
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000606/// After backtracking, the hazard checker needs to be restored to a state
607/// corresponding the the current cycle.
608void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
609 HazardRec->Reset();
610
611 unsigned LookAhead = std::min((unsigned)Sequence.size(),
612 HazardRec->getMaxLookAhead());
613 if (LookAhead == 0)
614 return;
615
616 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
617 unsigned HazardCycle = (*I)->getHeight();
618 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
619 SUnit *SU = *I;
620 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
621 HazardRec->RecedeCycle();
622 }
623 EmitNode(SU);
624 }
625}
626
Evan Cheng8e136a92007-09-26 21:36:17 +0000627/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000628/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000629void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
630 SUnit *OldSU = Sequence.back();
631 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000632 Sequence.pop_back();
633 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000634 // Don't try to remove SU from AvailableQueue.
635 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000636 // FIXME: use ready cycle instead of height
637 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000638 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000639 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000640 if (OldSU == BtSU)
641 break;
642 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000643 }
644
Dan Gohman60d68442009-01-29 19:49:27 +0000645 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000646
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000647 RestoreHazardCheckerBottomUp();
648
Andrew Trick5ce945c2010-12-24 07:10:19 +0000649 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000650
Evan Cheng1ec79b42007-09-27 07:09:03 +0000651 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000652}
653
Evan Cheng3b245872010-02-05 01:27:11 +0000654static bool isOperandOf(const SUnit *SU, SDNode *N) {
655 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000656 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000657 if (SUNode->isOperandOf(N))
658 return true;
659 }
660 return false;
661}
662
Evan Cheng5924bf72007-09-25 01:54:36 +0000663/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
664/// successors to the newly created node.
665SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000666 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000667 if (!N)
668 return NULL;
669
Andrew Trickc9405662010-12-24 06:46:50 +0000670 if (SU->getNode()->getGluedNode())
671 return NULL;
672
Evan Cheng79e97132007-10-05 01:39:18 +0000673 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000674 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000675 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000676 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000677 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000678 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000679 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000680 TryUnfold = true;
681 }
Evan Cheng79e97132007-10-05 01:39:18 +0000682 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000683 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000684 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000685 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000686 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000687 }
688
689 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000690 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000691 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000692 return NULL;
693
Evan Chengbdd062d2010-05-20 06:13:19 +0000694 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000695 assert(NewNodes.size() == 2 && "Expected a load folding node!");
696
697 N = NewNodes[1];
698 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000699 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000700 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000701 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000702 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
703 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000704 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000705
Dan Gohmane52e0892008-11-11 21:34:44 +0000706 // LoadNode may already exist. This can happen when there is another
707 // load from the same location and producing the same type of value
708 // but it has different alignment or volatileness.
709 bool isNewLoad = true;
710 SUnit *LoadSU;
711 if (LoadNode->getNodeId() != -1) {
712 LoadSU = &SUnits[LoadNode->getNodeId()];
713 isNewLoad = false;
714 } else {
715 LoadSU = CreateNewSUnit(LoadNode);
716 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000717
718 InitNumRegDefsLeft(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000719 ComputeLatency(LoadSU);
720 }
721
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000722 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000723 assert(N->getNodeId() == -1 && "Node already inserted!");
724 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000725
Dan Gohman17059682008-07-17 19:10:17 +0000726 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000727 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000728 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000729 NewSU->isTwoAddress = true;
730 break;
731 }
732 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000733 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000734 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +0000735
736 InitNumRegDefsLeft(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000737 ComputeLatency(NewSU);
738
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000739 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000740 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000741 SmallVector<SDep, 4> ChainSuccs;
742 SmallVector<SDep, 4> LoadPreds;
743 SmallVector<SDep, 4> NodePreds;
744 SmallVector<SDep, 4> NodeSuccs;
745 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
746 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000747 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000748 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000749 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000750 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000751 else
Dan Gohman2d170892008-12-09 22:54:47 +0000752 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000753 }
754 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
755 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000756 if (I->isCtrl())
757 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000758 else
Dan Gohman2d170892008-12-09 22:54:47 +0000759 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000760 }
761
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000762 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000763 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
764 const SDep &Pred = ChainPreds[i];
765 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000766 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000767 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000768 }
Evan Cheng79e97132007-10-05 01:39:18 +0000769 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000770 const SDep &Pred = LoadPreds[i];
771 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000772 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000773 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000774 }
775 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000776 const SDep &Pred = NodePreds[i];
777 RemovePred(SU, Pred);
778 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000779 }
780 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000781 SDep D = NodeSuccs[i];
782 SUnit *SuccDep = D.getSUnit();
783 D.setSUnit(SU);
784 RemovePred(SuccDep, D);
785 D.setSUnit(NewSU);
786 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000787 // Balance register pressure.
788 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
789 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
790 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +0000791 }
792 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000793 SDep D = ChainSuccs[i];
794 SUnit *SuccDep = D.getSUnit();
795 D.setSUnit(SU);
796 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000797 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000798 D.setSUnit(LoadSU);
799 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000800 }
Andrew Trick2085a962010-12-21 22:25:04 +0000801 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000802
803 // Add a data dependency to reflect that NewSU reads the value defined
804 // by LoadSU.
805 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000806
Evan Cheng91e0fc92007-12-18 08:42:10 +0000807 if (isNewLoad)
808 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000809 AvailableQueue->addNode(NewSU);
810
811 ++NumUnfolds;
812
813 if (NewSU->NumSuccsLeft == 0) {
814 NewSU->isAvailable = true;
815 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000816 }
817 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000818 }
819
Evan Chengbdd062d2010-05-20 06:13:19 +0000820 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000821 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000822
823 // New SUnit has the exact same predecessors.
824 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
825 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000826 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000827 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000828
829 // Only copy scheduled successors. Cut them from old node's successor
830 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000831 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000832 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
833 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000834 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000835 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000836 SUnit *SuccSU = I->getSUnit();
837 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000838 SDep D = *I;
839 D.setSUnit(NewSU);
840 AddPred(SuccSU, D);
841 D.setSUnit(SU);
842 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000843 }
844 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000845 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000846 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000847
848 AvailableQueue->updateNode(SU);
849 AvailableQueue->addNode(NewSU);
850
Evan Cheng1ec79b42007-09-27 07:09:03 +0000851 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000852 return NewSU;
853}
854
Evan Chengb2c42c62009-01-12 03:19:55 +0000855/// InsertCopiesAndMoveSuccs - Insert register copies and move all
856/// scheduled successors of the given SUnit to the last copy.
857void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
858 const TargetRegisterClass *DestRC,
859 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000860 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000861 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000862 CopyFromSU->CopySrcRC = SrcRC;
863 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000864
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000865 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000866 CopyToSU->CopySrcRC = DestRC;
867 CopyToSU->CopyDstRC = SrcRC;
868
869 // Only copy scheduled successors. Cut them from old node's successor
870 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000871 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000872 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
873 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000874 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000875 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000876 SUnit *SuccSU = I->getSUnit();
877 if (SuccSU->isScheduled) {
878 SDep D = *I;
879 D.setSUnit(CopyToSU);
880 AddPred(SuccSU, D);
881 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000882 }
883 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000884 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000885 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000886
Dan Gohman2d170892008-12-09 22:54:47 +0000887 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
888 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +0000889
890 AvailableQueue->updateNode(SU);
891 AvailableQueue->addNode(CopyFromSU);
892 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000893 Copies.push_back(CopyFromSU);
894 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000895
Evan Chengb2c42c62009-01-12 03:19:55 +0000896 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000897}
898
899/// getPhysicalRegisterVT - Returns the ValueType of the physical register
900/// definition of the specified node.
901/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +0000902static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +0000903 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +0000904 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000905 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000906 unsigned NumRes = TID.getNumDefs();
907 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000908 if (Reg == *ImpDef)
909 break;
910 ++NumRes;
911 }
912 return N->getValueType(NumRes);
913}
914
Evan Chengb8905c42009-03-04 01:41:49 +0000915/// CheckForLiveRegDef - Return true and update live register vector if the
916/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000917static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +0000918 std::vector<SUnit*> &LiveRegDefs,
919 SmallSet<unsigned, 4> &RegAdded,
920 SmallVector<unsigned, 4> &LRegs,
921 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +0000922 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
923
924 // Check if Ref is live.
925 if (!LiveRegDefs[Reg]) continue;
926
927 // Allow multiple uses of the same def.
928 if (LiveRegDefs[Reg] == SU) continue;
929
930 // Add Reg to the set of interfering live regs.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000931 if (RegAdded.insert(Reg))
Evan Chengb8905c42009-03-04 01:41:49 +0000932 LRegs.push_back(Reg);
Evan Chengb8905c42009-03-04 01:41:49 +0000933 }
Evan Chengb8905c42009-03-04 01:41:49 +0000934}
935
Evan Cheng5924bf72007-09-25 01:54:36 +0000936/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
937/// scheduling of the given node to satisfy live physical register dependencies.
938/// If the specific node is the last one that's available to schedule, do
939/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000940bool ScheduleDAGRRList::
941DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000942 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +0000943 return false;
944
Evan Chenge6f92252007-09-27 18:46:06 +0000945 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000946 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000947 //
948 // If SU is the currently live definition of the same register that it uses,
949 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +0000950 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
951 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000952 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +0000953 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
954 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000955 }
956
Chris Lattner11a33812010-12-23 17:24:32 +0000957 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +0000958 if (Node->getOpcode() == ISD::INLINEASM) {
959 // Inline asm can clobber physical defs.
960 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000961 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +0000962 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +0000963
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000964 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +0000965 unsigned Flags =
966 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000967 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +0000968
969 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000970 if (InlineAsm::isRegDefKind(Flags) ||
971 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +0000972 // Check for def of register or earlyclobber register.
973 for (; NumVals; --NumVals, ++i) {
974 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
975 if (TargetRegisterInfo::isPhysicalRegister(Reg))
976 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
977 }
978 } else
979 i += NumVals;
980 }
981 continue;
982 }
983
Dan Gohman072734e2008-11-13 23:24:17 +0000984 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000985 continue;
Dan Gohman17059682008-07-17 19:10:17 +0000986 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +0000987 if (!TID.ImplicitDefs)
988 continue;
Evan Chengb8905c42009-03-04 01:41:49 +0000989 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
990 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000991 }
Andrew Trick2085a962010-12-21 22:25:04 +0000992
Evan Cheng5924bf72007-09-25 01:54:36 +0000993 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000994}
995
Andrew Trick528fad92010-12-23 05:42:20 +0000996/// Return a node that can be scheduled in this cycle. Requirements:
997/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000998/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +0000999/// (3) No Interferences: may unschedule to break register interferences.
1000SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1001 SmallVector<SUnit*, 4> Interferences;
1002 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1003
1004 SUnit *CurSU = AvailableQueue->pop();
1005 while (CurSU) {
1006 SmallVector<unsigned, 4> LRegs;
1007 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1008 break;
1009 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1010
1011 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1012 Interferences.push_back(CurSU);
1013 CurSU = AvailableQueue->pop();
1014 }
1015 if (CurSU) {
1016 // Add the nodes that aren't ready back onto the available list.
1017 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1018 Interferences[i]->isPending = false;
1019 assert(Interferences[i]->isAvailable && "must still be available");
1020 AvailableQueue->push(Interferences[i]);
1021 }
1022 return CurSU;
1023 }
1024
1025 // All candidates are delayed due to live physical reg dependencies.
1026 // Try backtracking, code duplication, or inserting cross class copies
1027 // to resolve it.
1028 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1029 SUnit *TrySU = Interferences[i];
1030 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1031
1032 // Try unscheduling up to the point where it's safe to schedule
1033 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001034 SUnit *BtSU = NULL;
1035 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001036 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1037 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001038 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1039 BtSU = LiveRegGens[Reg];
1040 LiveCycle = BtSU->getHeight();
1041 }
Andrew Trick528fad92010-12-23 05:42:20 +00001042 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001043 if (!WillCreateCycle(TrySU, BtSU)) {
1044 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001045
1046 // Force the current node to be scheduled before the node that
1047 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001048 if (BtSU->isAvailable) {
1049 BtSU->isAvailable = false;
1050 if (!BtSU->isPending)
1051 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001052 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001053 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001054 /*Reg=*/0, /*isNormalMemory=*/false,
1055 /*isMustAlias=*/false, /*isArtificial=*/true));
1056
1057 // If one or more successors has been unscheduled, then the current
1058 // node is no longer avaialable. Schedule a successor that's now
1059 // available instead.
1060 if (!TrySU->isAvailable) {
1061 CurSU = AvailableQueue->pop();
1062 }
1063 else {
1064 CurSU = TrySU;
1065 TrySU->isPending = false;
1066 Interferences.erase(Interferences.begin()+i);
1067 }
1068 break;
1069 }
1070 }
1071
1072 if (!CurSU) {
1073 // Can't backtrack. If it's too expensive to copy the value, then try
1074 // duplicate the nodes that produces these "too expensive to copy"
1075 // values to break the dependency. In case even that doesn't work,
1076 // insert cross class copies.
1077 // If it's not too expensive, i.e. cost != -1, issue copies.
1078 SUnit *TrySU = Interferences[0];
1079 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1080 assert(LRegs.size() == 1 && "Can't handle this yet!");
1081 unsigned Reg = LRegs[0];
1082 SUnit *LRDef = LiveRegDefs[Reg];
1083 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1084 const TargetRegisterClass *RC =
1085 TRI->getMinimalPhysRegClass(Reg, VT);
1086 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1087
1088 // If cross copy register class is null, then it must be possible copy
1089 // the value directly. Do not try duplicate the def.
1090 SUnit *NewDef = 0;
1091 if (DestRC)
1092 NewDef = CopyAndMoveSuccessors(LRDef);
1093 else
1094 DestRC = RC;
1095 if (!NewDef) {
1096 // Issue copies, these can be expensive cross register class copies.
1097 SmallVector<SUnit*, 2> Copies;
1098 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1099 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1100 << " to SU #" << Copies.front()->NodeNum << "\n");
1101 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1102 /*Reg=*/0, /*isNormalMemory=*/false,
1103 /*isMustAlias=*/false,
1104 /*isArtificial=*/true));
1105 NewDef = Copies.back();
1106 }
1107
1108 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1109 << " to SU #" << TrySU->NodeNum << "\n");
1110 LiveRegDefs[Reg] = NewDef;
1111 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1112 /*Reg=*/0, /*isNormalMemory=*/false,
1113 /*isMustAlias=*/false,
1114 /*isArtificial=*/true));
1115 TrySU->isAvailable = false;
1116 CurSU = NewDef;
1117 }
1118
1119 assert(CurSU && "Unable to resolve live physical register dependencies!");
1120
1121 // Add the nodes that aren't ready back onto the available list.
1122 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1123 Interferences[i]->isPending = false;
1124 // May no longer be available due to backtracking.
1125 if (Interferences[i]->isAvailable) {
1126 AvailableQueue->push(Interferences[i]);
1127 }
1128 }
1129 return CurSU;
1130}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001131
Evan Chengd38c22b2006-05-11 23:55:42 +00001132/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1133/// schedulers.
1134void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001135 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001136 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001137
Evan Chengd38c22b2006-05-11 23:55:42 +00001138 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001139 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001140 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001141 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1142 RootSU->isAvailable = true;
1143 AvailableQueue->push(RootSU);
1144 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001145
1146 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001147 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001148 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001149 while (!AvailableQueue->empty()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001150 DEBUG(dbgs() << "\n*** Examining Available\n";
1151 AvailableQueue->dump(this));
1152
Andrew Trick528fad92010-12-23 05:42:20 +00001153 // Pick the best node to schedule taking all constraints into
1154 // consideration.
1155 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001156
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001157 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001158
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001159 ScheduleNodeBottomUp(SU);
1160
1161 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1162 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1163 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1164 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1165 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001166 }
1167
Evan Chengd38c22b2006-05-11 23:55:42 +00001168 // Reverse the order if it is bottom up.
1169 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001170
Evan Chengd38c22b2006-05-11 23:55:42 +00001171#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001172 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001173#endif
1174}
1175
1176//===----------------------------------------------------------------------===//
1177// Top-Down Scheduling
1178//===----------------------------------------------------------------------===//
1179
1180/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001181/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001182void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001183 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001184
Evan Chengd38c22b2006-05-11 23:55:42 +00001185#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001186 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001187 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001188 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001189 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001190 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001191 }
1192#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001193 --SuccSU->NumPredsLeft;
1194
Dan Gohmanb9543432009-02-10 23:27:53 +00001195 // If all the node's predecessors are scheduled, this node is ready
1196 // to be scheduled. Ignore the special ExitSU node.
1197 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001198 SuccSU->isAvailable = true;
1199 AvailableQueue->push(SuccSU);
1200 }
1201}
1202
Dan Gohmanb9543432009-02-10 23:27:53 +00001203void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1204 // Top down: release successors
1205 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1206 I != E; ++I) {
1207 assert(!I->isAssignedRegDep() &&
1208 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1209
1210 ReleaseSucc(SU, &*I);
1211 }
1212}
1213
Evan Chengd38c22b2006-05-11 23:55:42 +00001214/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1215/// count of its successors. If a successor pending count is zero, add it to
1216/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001217void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001218 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001219 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001220
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001221 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1222 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001223 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001224
Dan Gohmanb9543432009-02-10 23:27:53 +00001225 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001226 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001227 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001228}
1229
Dan Gohman54a187e2007-08-20 19:28:38 +00001230/// ListScheduleTopDown - The main loop of list scheduling for top-down
1231/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001232void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001233 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001234
Dan Gohmanb9543432009-02-10 23:27:53 +00001235 // Release any successors of the special Entry node.
1236 ReleaseSuccessors(&EntrySU);
1237
Evan Chengd38c22b2006-05-11 23:55:42 +00001238 // All leaves to Available queue.
1239 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1240 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001241 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001242 AvailableQueue->push(&SUnits[i]);
1243 SUnits[i].isAvailable = true;
1244 }
1245 }
Andrew Trick2085a962010-12-21 22:25:04 +00001246
Evan Chengd38c22b2006-05-11 23:55:42 +00001247 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001248 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001249 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001250 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001251 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001252
Dan Gohmanc602dd42008-11-21 00:10:42 +00001253 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001254 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001255 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001256 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001257 }
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
Evan Chengd38c22b2006-05-11 23:55:42 +00001265//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001266// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001267//===----------------------------------------------------------------------===//
1268//
1269// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1270// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001271//
Evan Chengd38c22b2006-05-11 23:55:42 +00001272namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001273class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001274
Andrew Trick9ccce772011-01-14 21:11:41 +00001275struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1276 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1277};
1278
1279/// bu_ls_rr_sort - Priority function for bottom up register pressure
1280// reduction scheduler.
1281struct bu_ls_rr_sort : public queue_sort {
1282 enum {
1283 IsBottomUp = true,
1284 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001285 };
1286
Andrew Trick9ccce772011-01-14 21:11:41 +00001287 RegReductionPQBase *SPQ;
1288 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1289 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001290
Andrew Trick9ccce772011-01-14 21:11:41 +00001291 bool operator()(SUnit* left, SUnit* right) const;
1292};
Andrew Trick2085a962010-12-21 22:25:04 +00001293
Andrew Trick9ccce772011-01-14 21:11:41 +00001294// td_ls_rr_sort - Priority function for top down register pressure reduction
1295// scheduler.
1296struct td_ls_rr_sort : public queue_sort {
1297 enum {
1298 IsBottomUp = false,
1299 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001300 };
1301
Andrew Trick9ccce772011-01-14 21:11:41 +00001302 RegReductionPQBase *SPQ;
1303 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1304 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001305
Andrew Trick9ccce772011-01-14 21:11:41 +00001306 bool operator()(const SUnit* left, const SUnit* right) const;
1307};
Andrew Trick2085a962010-12-21 22:25:04 +00001308
Andrew Trick9ccce772011-01-14 21:11:41 +00001309// src_ls_rr_sort - Priority function for source order scheduler.
1310struct src_ls_rr_sort : public queue_sort {
1311 enum {
1312 IsBottomUp = true,
1313 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001314 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001315
Andrew Trick9ccce772011-01-14 21:11:41 +00001316 RegReductionPQBase *SPQ;
1317 src_ls_rr_sort(RegReductionPQBase *spq)
1318 : SPQ(spq) {}
1319 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1320 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001321
Andrew Trick9ccce772011-01-14 21:11:41 +00001322 bool operator()(SUnit* left, SUnit* right) const;
1323};
Andrew Trick2085a962010-12-21 22:25:04 +00001324
Andrew Trick9ccce772011-01-14 21:11:41 +00001325// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1326struct hybrid_ls_rr_sort : public queue_sort {
1327 enum {
1328 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001329 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001330 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001331
Andrew Trick9ccce772011-01-14 21:11:41 +00001332 RegReductionPQBase *SPQ;
1333 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1334 : SPQ(spq) {}
1335 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1336 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001337
Andrew Trick9ccce772011-01-14 21:11:41 +00001338 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001339
Andrew Trick9ccce772011-01-14 21:11:41 +00001340 bool operator()(SUnit* left, SUnit* right) const;
1341};
1342
1343// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1344// scheduler.
1345struct ilp_ls_rr_sort : public queue_sort {
1346 enum {
1347 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001348 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001349 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001350
Andrew Trick9ccce772011-01-14 21:11:41 +00001351 RegReductionPQBase *SPQ;
1352 ilp_ls_rr_sort(RegReductionPQBase *spq)
1353 : SPQ(spq) {}
1354 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1355 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001356
Andrew Trick9ccce772011-01-14 21:11:41 +00001357 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001358
Andrew Trick9ccce772011-01-14 21:11:41 +00001359 bool operator()(SUnit* left, SUnit* right) const;
1360};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001361
Andrew Trick9ccce772011-01-14 21:11:41 +00001362class RegReductionPQBase : public SchedulingPriorityQueue {
1363protected:
1364 std::vector<SUnit*> Queue;
1365 unsigned CurQueueId;
1366 bool TracksRegPressure;
1367
1368 // SUnits - The SUnits for the current graph.
1369 std::vector<SUnit> *SUnits;
1370
1371 MachineFunction &MF;
1372 const TargetInstrInfo *TII;
1373 const TargetRegisterInfo *TRI;
1374 const TargetLowering *TLI;
1375 ScheduleDAGRRList *scheduleDAG;
1376
1377 // SethiUllmanNumbers - The SethiUllman number for each node.
1378 std::vector<unsigned> SethiUllmanNumbers;
1379
1380 /// RegPressure - Tracking current reg pressure per register class.
1381 ///
1382 std::vector<unsigned> RegPressure;
1383
1384 /// RegLimit - Tracking the number of allocatable registers per register
1385 /// class.
1386 std::vector<unsigned> RegLimit;
1387
1388public:
1389 RegReductionPQBase(MachineFunction &mf,
1390 bool hasReadyFilter,
1391 bool tracksrp,
1392 const TargetInstrInfo *tii,
1393 const TargetRegisterInfo *tri,
1394 const TargetLowering *tli)
1395 : SchedulingPriorityQueue(hasReadyFilter),
1396 CurQueueId(0), TracksRegPressure(tracksrp),
1397 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1398 if (TracksRegPressure) {
1399 unsigned NumRC = TRI->getNumRegClasses();
1400 RegLimit.resize(NumRC);
1401 RegPressure.resize(NumRC);
1402 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1403 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1404 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1405 E = TRI->regclass_end(); I != E; ++I)
1406 RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
1407 }
1408 }
1409
1410 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1411 scheduleDAG = scheduleDag;
1412 }
1413
1414 ScheduleHazardRecognizer* getHazardRec() {
1415 return scheduleDAG->getHazardRec();
1416 }
1417
1418 void initNodes(std::vector<SUnit> &sunits);
1419
1420 void addNode(const SUnit *SU);
1421
1422 void updateNode(const SUnit *SU);
1423
1424 void releaseState() {
1425 SUnits = 0;
1426 SethiUllmanNumbers.clear();
1427 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1428 }
1429
1430 unsigned getNodePriority(const SUnit *SU) const;
1431
1432 unsigned getNodeOrdering(const SUnit *SU) const {
1433 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1434 }
1435
1436 bool empty() const { return Queue.empty(); }
1437
1438 void push(SUnit *U) {
1439 assert(!U->NodeQueueId && "Node in the queue already");
1440 U->NodeQueueId = ++CurQueueId;
1441 Queue.push_back(U);
1442 }
1443
1444 void remove(SUnit *SU) {
1445 assert(!Queue.empty() && "Queue is empty!");
1446 assert(SU->NodeQueueId != 0 && "Not in queue!");
1447 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1448 SU);
1449 if (I != prior(Queue.end()))
1450 std::swap(*I, Queue.back());
1451 Queue.pop_back();
1452 SU->NodeQueueId = 0;
1453 }
1454
Andrew Trickd0548ae2011-02-04 03:18:17 +00001455 bool tracksRegPressure() const { return TracksRegPressure; }
1456
Andrew Trick9ccce772011-01-14 21:11:41 +00001457 void dumpRegPressure() const;
1458
1459 bool HighRegPressure(const SUnit *SU) const;
1460
1461 bool MayReduceRegPressure(SUnit *SU);
1462
1463 void ScheduledNode(SUnit *SU);
1464
1465 void UnscheduledNode(SUnit *SU);
1466
1467protected:
1468 bool canClobber(const SUnit *SU, const SUnit *Op);
1469 void AddPseudoTwoAddrDeps();
1470 void PrescheduleNodesWithMultipleUses();
1471 void CalculateSethiUllmanNumbers();
1472};
1473
1474template<class SF>
1475class RegReductionPriorityQueue : public RegReductionPQBase {
1476 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1477 std::vector<SUnit *>::iterator Best = Q.begin();
1478 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1479 E = Q.end(); I != E; ++I)
1480 if (Picker(*Best, *I))
1481 Best = I;
1482 SUnit *V = *Best;
1483 if (Best != prior(Q.end()))
1484 std::swap(*Best, Q.back());
1485 Q.pop_back();
1486 return V;
1487 }
1488
1489 SF Picker;
1490
1491public:
1492 RegReductionPriorityQueue(MachineFunction &mf,
1493 bool tracksrp,
1494 const TargetInstrInfo *tii,
1495 const TargetRegisterInfo *tri,
1496 const TargetLowering *tli)
1497 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1498 Picker(this) {}
1499
1500 bool isBottomUp() const { return SF::IsBottomUp; }
1501
1502 bool isReady(SUnit *U) const {
1503 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1504 }
1505
1506 SUnit *pop() {
1507 if (Queue.empty()) return NULL;
1508
1509 SUnit *V = popFromQueue(Queue, Picker);
1510 V->NodeQueueId = 0;
1511 return V;
1512 }
1513
1514 void dump(ScheduleDAG *DAG) const {
1515 // Emulate pop() without clobbering NodeQueueIds.
1516 std::vector<SUnit*> DumpQueue = Queue;
1517 SF DumpPicker = Picker;
1518 while (!DumpQueue.empty()) {
1519 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1520 if (isBottomUp())
1521 dbgs() << "Height " << SU->getHeight() << ": ";
1522 else
1523 dbgs() << "Depth " << SU->getDepth() << ": ";
1524 SU->dump(DAG);
1525 }
1526 }
1527};
1528
1529typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1530BURegReductionPriorityQueue;
1531
1532typedef RegReductionPriorityQueue<td_ls_rr_sort>
1533TDRegReductionPriorityQueue;
1534
1535typedef RegReductionPriorityQueue<src_ls_rr_sort>
1536SrcRegReductionPriorityQueue;
1537
1538typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1539HybridBURRPriorityQueue;
1540
1541typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1542ILPBURRPriorityQueue;
1543} // end anonymous namespace
1544
1545//===----------------------------------------------------------------------===//
1546// Static Node Priority for Register Pressure Reduction
1547//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001548
Dan Gohman186f65d2008-11-20 03:30:37 +00001549/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1550/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001551static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001552CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001553 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1554 if (SethiUllmanNumber != 0)
1555 return SethiUllmanNumber;
1556
1557 unsigned Extra = 0;
1558 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1559 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001560 if (I->isCtrl()) continue; // ignore chain preds
1561 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001562 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001563 if (PredSethiUllman > SethiUllmanNumber) {
1564 SethiUllmanNumber = PredSethiUllman;
1565 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001566 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001567 ++Extra;
1568 }
1569
1570 SethiUllmanNumber += Extra;
1571
1572 if (SethiUllmanNumber == 0)
1573 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001574
Evan Cheng7e4abde2008-07-02 09:23:51 +00001575 return SethiUllmanNumber;
1576}
1577
Andrew Trick9ccce772011-01-14 21:11:41 +00001578/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1579/// scheduling units.
1580void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1581 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001582
Andrew Trick9ccce772011-01-14 21:11:41 +00001583 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1584 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001585}
1586
Andrew Trick9ccce772011-01-14 21:11:41 +00001587void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1588 SUnits = &sunits;
1589 // Add pseudo dependency edges for two-address nodes.
1590 AddPseudoTwoAddrDeps();
1591 // Reroute edges to nodes with multiple uses.
Andrew Trickd0548ae2011-02-04 03:18:17 +00001592 if (!TracksRegPressure)
1593 PrescheduleNodesWithMultipleUses();
Andrew Trick9ccce772011-01-14 21:11:41 +00001594 // Calculate node priorities.
1595 CalculateSethiUllmanNumbers();
1596}
1597
1598void RegReductionPQBase::addNode(const SUnit *SU) {
1599 unsigned SUSize = SethiUllmanNumbers.size();
1600 if (SUnits->size() > SUSize)
1601 SethiUllmanNumbers.resize(SUSize*2, 0);
1602 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1603}
1604
1605void RegReductionPQBase::updateNode(const SUnit *SU) {
1606 SethiUllmanNumbers[SU->NodeNum] = 0;
1607 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1608}
1609
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001610// Lower priority means schedule further down. For bottom-up scheduling, lower
1611// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001612unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1613 assert(SU->NodeNum < SethiUllmanNumbers.size());
1614 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1615 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1616 // CopyToReg should be close to its uses to facilitate coalescing and
1617 // avoid spilling.
1618 return 0;
1619 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1620 Opc == TargetOpcode::SUBREG_TO_REG ||
1621 Opc == TargetOpcode::INSERT_SUBREG)
1622 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1623 // close to their uses to facilitate coalescing.
1624 return 0;
1625 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1626 // If SU does not have a register use, i.e. it doesn't produce a value
1627 // that would be consumed (e.g. store), then it terminates a chain of
1628 // computation. Give it a large SethiUllman number so it will be
1629 // scheduled right before its predecessors that it doesn't lengthen
1630 // their live ranges.
1631 return 0xffff;
1632 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1633 // If SU does not have a register def, schedule it close to its uses
1634 // because it does not lengthen any live ranges.
1635 return 0;
1636 return SethiUllmanNumbers[SU->NodeNum];
1637}
1638
1639//===----------------------------------------------------------------------===//
1640// Register Pressure Tracking
1641//===----------------------------------------------------------------------===//
1642
1643void RegReductionPQBase::dumpRegPressure() const {
1644 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1645 E = TRI->regclass_end(); I != E; ++I) {
1646 const TargetRegisterClass *RC = *I;
1647 unsigned Id = RC->getID();
1648 unsigned RP = RegPressure[Id];
1649 if (!RP) continue;
1650 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1651 << '\n');
1652 }
1653}
1654
1655bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1656 if (!TLI)
1657 return false;
1658
1659 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1660 I != E; ++I) {
1661 if (I->isCtrl())
1662 continue;
1663 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001664 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1665 // to cover the number of registers defined (they are all live).
1666 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001667 continue;
1668 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001669 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1670 RegDefPos.IsValid(); RegDefPos.Advance()) {
1671 EVT VT = RegDefPos.GetValue();
Andrew Trick9ccce772011-01-14 21:11:41 +00001672 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1673 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Andrew Trick9ccce772011-01-14 21:11:41 +00001674 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1675 return true;
1676 }
1677 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001678 return false;
1679}
1680
1681bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) {
1682 const SDNode *N = SU->getNode();
1683
1684 if (!N->isMachineOpcode() || !SU->NumSuccs)
1685 return false;
1686
1687 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1688 for (unsigned i = 0; i != NumDefs; ++i) {
1689 EVT VT = N->getValueType(i);
1690 if (!N->hasAnyUseOfValue(i))
1691 continue;
1692 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1693 if (RegPressure[RCId] >= RegLimit[RCId])
1694 return true;
1695 }
1696 return false;
1697}
1698
1699void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1700 if (!TracksRegPressure)
1701 return;
1702
Andrew Trick9ccce772011-01-14 21:11:41 +00001703 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1704 I != E; ++I) {
1705 if (I->isCtrl())
1706 continue;
1707 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001708 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1709 // to cover the number of registers defined (they are all live).
1710 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001711 continue;
1712 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001713 // FIXME: The ScheduleDAG currently loses information about which of a
1714 // node's values is consumed by each dependence. Consequently, if the node
1715 // defines multiple register classes, we don't know which to pressurize
1716 // here. Instead the following loop consumes the register defs in an
1717 // arbitrary order. At least it handles the common case of clustered loads
1718 // to the same class. For precise liveness, each SDep needs to indicate the
1719 // result number. But that tightly couples the ScheduleDAG with the
1720 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1721 // value type or register class to SDep.
1722 //
1723 // The most important aspect of register tracking is balancing the increase
1724 // here with the reduction further below. Note that this SU may use multiple
1725 // defs in PredSU. The can't be determined here, but we've already
1726 // compensated by reducing NumRegDefsLeft in PredSU during
1727 // ScheduleDAGSDNodes::AddSchedEdges.
1728 --PredSU->NumRegDefsLeft;
1729 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1730 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1731 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1732 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00001733 continue;
Andrew Trickd0548ae2011-02-04 03:18:17 +00001734 EVT VT = RegDefPos.GetValue();
Andrew Trick9ccce772011-01-14 21:11:41 +00001735 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1736 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001737 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00001738 }
1739 }
1740
Andrew Trickd0548ae2011-02-04 03:18:17 +00001741 // We should have this assert, but there may be dead SDNodes that never
1742 // materialize as SUnits, so they don't appear to generate liveness.
1743 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1744 int SkipRegDefs = (int)SU->NumRegDefsLeft;
1745 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1746 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1747 if (SkipRegDefs > 0)
1748 continue;
1749 EVT VT = RegDefPos.GetValue();
1750 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1751 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT)) {
1752 // Register pressure tracking is imprecise. This can happen. But we try
1753 // hard not to let it happen because it likely results in poor scheduling.
1754 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
1755 RegPressure[RCId] = 0;
1756 }
1757 else {
1758 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
Andrew Trick9ccce772011-01-14 21:11:41 +00001759 }
1760 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001761 dumpRegPressure();
1762}
1763
1764void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1765 if (!TracksRegPressure)
1766 return;
1767
1768 const SDNode *N = SU->getNode();
1769 if (!N->isMachineOpcode()) {
1770 if (N->getOpcode() != ISD::CopyToReg)
1771 return;
1772 } else {
1773 unsigned Opc = N->getMachineOpcode();
1774 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1775 Opc == TargetOpcode::INSERT_SUBREG ||
1776 Opc == TargetOpcode::SUBREG_TO_REG ||
1777 Opc == TargetOpcode::REG_SEQUENCE ||
1778 Opc == TargetOpcode::IMPLICIT_DEF)
1779 return;
1780 }
1781
1782 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1783 I != E; ++I) {
1784 if (I->isCtrl())
1785 continue;
1786 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001787 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1788 // counts data deps.
1789 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00001790 continue;
1791 const SDNode *PN = PredSU->getNode();
1792 if (!PN->isMachineOpcode()) {
1793 if (PN->getOpcode() == ISD::CopyFromReg) {
1794 EVT VT = PN->getValueType(0);
1795 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1796 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1797 }
1798 continue;
1799 }
1800 unsigned POpc = PN->getMachineOpcode();
1801 if (POpc == TargetOpcode::IMPLICIT_DEF)
1802 continue;
1803 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1804 EVT VT = PN->getOperand(0).getValueType();
1805 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1806 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1807 continue;
1808 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1809 POpc == TargetOpcode::SUBREG_TO_REG) {
1810 EVT VT = PN->getValueType(0);
1811 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1812 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1813 continue;
1814 }
1815 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1816 for (unsigned i = 0; i != NumDefs; ++i) {
1817 EVT VT = PN->getValueType(i);
1818 if (!PN->hasAnyUseOfValue(i))
1819 continue;
1820 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1821 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1822 // Register pressure tracking is imprecise. This can happen.
1823 RegPressure[RCId] = 0;
1824 else
1825 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1826 }
1827 }
1828
1829 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1830 // may transfer data dependencies to CopyToReg.
1831 if (SU->NumSuccs && N->isMachineOpcode()) {
1832 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1833 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1834 EVT VT = N->getValueType(i);
1835 if (VT == MVT::Glue || VT == MVT::Other)
1836 continue;
1837 if (!N->hasAnyUseOfValue(i))
1838 continue;
1839 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1840 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1841 }
1842 }
1843
1844 dumpRegPressure();
1845}
1846
1847//===----------------------------------------------------------------------===//
1848// Dynamic Node Priority for Register Pressure Reduction
1849//===----------------------------------------------------------------------===//
1850
Evan Chengb9e3db62007-03-14 22:43:40 +00001851/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00001852/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001853static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001854 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00001855 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001856 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00001857 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001858 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00001859 // If there are bunch of CopyToRegs stacked up, they should be considered
1860 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00001861 if (I->getSUnit()->getNode() &&
1862 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001863 Height = closestSucc(I->getSUnit())+1;
1864 if (Height > MaxHeight)
1865 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00001866 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001867 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00001868}
1869
Evan Cheng61bc51e2007-12-20 02:22:36 +00001870/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00001871/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00001872static unsigned calcMaxScratches(const SUnit *SU) {
1873 unsigned Scratches = 0;
1874 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00001875 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001876 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00001877 Scratches++;
1878 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00001879 return Scratches;
1880}
1881
Evan Cheng6c1414f2010-10-29 18:09:28 +00001882/// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1883/// CopyToReg to a virtual register. This SU def is probably a liveout and
1884/// it has no other use. It should be scheduled closer to the terminator.
1885static bool hasOnlyLiveOutUses(const SUnit *SU) {
1886 bool RetVal = false;
1887 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1888 I != E; ++I) {
1889 if (I->isCtrl()) continue;
1890 const SUnit *SuccSU = I->getSUnit();
1891 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1892 unsigned Reg =
1893 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1894 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1895 RetVal = true;
1896 continue;
1897 }
1898 }
1899 return false;
1900 }
1901 return RetVal;
1902}
1903
1904/// UnitsSharePred - Return true if the two scheduling units share a common
1905/// data predecessor.
1906static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1907 SmallSet<const SUnit*, 4> Preds;
1908 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1909 I != E; ++I) {
1910 if (I->isCtrl()) continue; // ignore chain preds
1911 Preds.insert(I->getSUnit());
1912 }
1913 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1914 I != E; ++I) {
1915 if (I->isCtrl()) continue; // ignore chain preds
1916 if (Preds.count(I->getSUnit()))
1917 return true;
1918 }
1919 return false;
1920}
1921
Andrew Trick9ccce772011-01-14 21:11:41 +00001922// Check for either a dependence (latency) or resource (hazard) stall.
1923//
1924// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
1925static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
1926 if ((int)SPQ->getCurCycle() < Height) return true;
1927 if (SPQ->getHazardRec()->getHazardType(SU, 0)
1928 != ScheduleHazardRecognizer::NoHazard)
1929 return true;
1930 return false;
1931}
1932
1933// Return -1 if left has higher priority, 1 if right has higher priority.
1934// Return 0 if latency-based priority is equivalent.
1935static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
1936 RegReductionPQBase *SPQ) {
1937 // If the two nodes share an operand and one of them has a single
1938 // use that is a live out copy, favor the one that is live out. Otherwise
1939 // it will be difficult to eliminate the copy if the instruction is a
1940 // loop induction variable update. e.g.
1941 // BB:
1942 // sub r1, r3, #1
1943 // str r0, [r2, r3]
1944 // mov r3, r1
1945 // cmp
1946 // bne BB
1947 bool SharePred = UnitsSharePred(left, right);
1948 // FIXME: Only adjust if BB is a loop back edge.
1949 // FIXME: What's the cost of a copy?
1950 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1951 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1952 int LHeight = (int)left->getHeight() - LBonus;
1953 int RHeight = (int)right->getHeight() - RBonus;
1954
1955 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
1956 BUHasStall(left, LHeight, SPQ);
1957 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
1958 BUHasStall(right, RHeight, SPQ);
1959
1960 // If scheduling one of the node will cause a pipeline stall, delay it.
1961 // If scheduling either one of the node will cause a pipeline stall, sort
1962 // them according to their height.
1963 if (LStall) {
1964 if (!RStall)
1965 return 1;
1966 if (LHeight != RHeight)
1967 return LHeight > RHeight ? 1 : -1;
1968 } else if (RStall)
1969 return -1;
1970
Andrew Trick47ff14b2011-01-21 05:51:33 +00001971 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00001972 // and latency.
1973 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
1974 right->SchedulingPref == Sched::Latency)) {
Andrew Trick47ff14b2011-01-21 05:51:33 +00001975 if (DisableSchedCycles) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001976 if (LHeight != RHeight)
1977 return LHeight > RHeight ? 1 : -1;
1978 }
Andrew Trick47ff14b2011-01-21 05:51:33 +00001979 else {
1980 // If neither instruction stalls (!LStall && !RStall) then
1981 // it's height is already covered so only its depth matters. We also reach
1982 // this if both stall but have the same height.
1983 unsigned LDepth = left->getDepth();
1984 unsigned RDepth = right->getDepth();
1985 if (LDepth != RDepth) {
1986 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
1987 << ") depth " << LDepth << " vs SU (" << right->NodeNum
1988 << ") depth " << RDepth << "\n");
1989 return LDepth < RDepth ? 1 : -1;
1990 }
1991 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001992 if (left->Latency != right->Latency)
1993 return left->Latency > right->Latency ? 1 : -1;
1994 }
1995 return 0;
1996}
1997
1998static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Evan Cheng6730f032007-01-08 23:55:53 +00001999 unsigned LPriority = SPQ->getNodePriority(left);
2000 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng73bdf042008-03-01 00:39:47 +00002001 if (LPriority != RPriority)
2002 return LPriority > RPriority;
2003
2004 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2005 // e.g.
2006 // t1 = op t2, c1
2007 // t3 = op t4, c2
2008 //
2009 // and the following instructions are both ready.
2010 // t2 = op c3
2011 // t4 = op c4
2012 //
2013 // Then schedule t2 = op first.
2014 // i.e.
2015 // t4 = op c4
2016 // t2 = op c3
2017 // t1 = op t2, c1
2018 // t3 = op t4, c2
2019 //
2020 // This creates more short live intervals.
2021 unsigned LDist = closestSucc(left);
2022 unsigned RDist = closestSucc(right);
2023 if (LDist != RDist)
2024 return LDist < RDist;
2025
Evan Cheng3a14efa2009-02-12 08:59:45 +00002026 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002027 unsigned LScratch = calcMaxScratches(left);
2028 unsigned RScratch = calcMaxScratches(right);
2029 if (LScratch != RScratch)
2030 return LScratch > RScratch;
2031
Andrew Trick47ff14b2011-01-21 05:51:33 +00002032 if (!DisableSchedCycles) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002033 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2034 if (result != 0)
2035 return result > 0;
2036 }
2037 else {
2038 if (left->getHeight() != right->getHeight())
2039 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002040
Andrew Trick9ccce772011-01-14 21:11:41 +00002041 if (left->getDepth() != right->getDepth())
2042 return left->getDepth() < right->getDepth();
2043 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002044
Andrew Trick2085a962010-12-21 22:25:04 +00002045 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002046 "NodeQueueId cannot be zero");
2047 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002048}
2049
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002050// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002051bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002052 return BURRSort(left, right, SPQ);
2053}
2054
2055// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002056bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002057 unsigned LOrder = SPQ->getNodeOrdering(left);
2058 unsigned ROrder = SPQ->getNodeOrdering(right);
2059
2060 // Prefer an ordering where the lower the non-zero order number, the higher
2061 // the preference.
2062 if ((LOrder || ROrder) && LOrder != ROrder)
2063 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2064
2065 return BURRSort(left, right, SPQ);
2066}
2067
Andrew Trick9ccce772011-01-14 21:11:41 +00002068// If the time between now and when the instruction will be ready can cover
2069// the spill code, then avoid adding it to the ready queue. This gives long
2070// stalls highest priority and allows hoisting across calls. It should also
2071// speed up processing the available queue.
2072bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2073 static const unsigned ReadyDelay = 3;
2074
2075 if (SPQ->MayReduceRegPressure(SU)) return true;
2076
2077 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2078
2079 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2080 != ScheduleHazardRecognizer::NoHazard)
2081 return false;
2082
2083 return true;
2084}
2085
2086// Return true if right should be scheduled with higher priority than left.
2087bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002088 if (left->isCall || right->isCall)
2089 // No way to compute latency of calls.
2090 return BURRSort(left, right, SPQ);
2091
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002092 bool LHigh = SPQ->HighRegPressure(left);
2093 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002094 // Avoid causing spills. If register pressure is high, schedule for
2095 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002096 if (LHigh && !RHigh) {
2097 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2098 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002099 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002100 }
2101 else if (!LHigh && RHigh) {
2102 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2103 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002104 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002105 }
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002106 else if (!LHigh && !RHigh) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002107 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2108 if (result != 0)
2109 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002110 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002111 return BURRSort(left, right, SPQ);
2112}
2113
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002114// Schedule as many instructions in each cycle as possible. So don't make an
2115// instruction available unless it is ready in the current cycle.
2116bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002117 if (SU->getHeight() > CurCycle) return false;
2118
2119 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2120 != ScheduleHazardRecognizer::NoHazard)
2121 return false;
2122
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002123 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002124}
2125
Andrew Trick9ccce772011-01-14 21:11:41 +00002126bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002127 if (left->isCall || right->isCall)
2128 // No way to compute latency of calls.
2129 return BURRSort(left, right, SPQ);
2130
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002131 bool LHigh = SPQ->HighRegPressure(left);
2132 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002133 // Avoid causing spills. If register pressure is high, schedule for
2134 // register pressure reduction.
2135 if (LHigh && !RHigh)
2136 return true;
2137 else if (!LHigh && RHigh)
2138 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002139 else if (!LHigh && !RHigh) {
Evan Cheng8ae3eca2010-07-25 18:59:43 +00002140 // Low register pressure situation, schedule to maximize instruction level
2141 // parallelism.
Evan Cheng37b740c2010-07-24 00:39:05 +00002142 if (left->NumPreds > right->NumPreds)
2143 return false;
2144 else if (left->NumPreds < right->NumPreds)
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002145 return true;
Evan Cheng37b740c2010-07-24 00:39:05 +00002146 }
2147
2148 return BURRSort(left, right, SPQ);
2149}
2150
Andrew Trick9ccce772011-01-14 21:11:41 +00002151//===----------------------------------------------------------------------===//
2152// Preschedule for Register Pressure
2153//===----------------------------------------------------------------------===//
2154
2155bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002156 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002157 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002158 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002159 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002160 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002161 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002162 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002163 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002164 if (DU->getNodeId() != -1 &&
2165 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002166 return true;
2167 }
2168 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002169 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002170 return false;
2171}
2172
Evan Chengf9891412007-12-20 09:25:31 +00002173/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002174/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002175static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002176 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002177 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002178 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002179 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2180 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002181 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002182 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002183 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002184 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002185 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002186 const unsigned *SUImpDefs =
2187 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2188 if (!SUImpDefs)
2189 return false;
2190 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002191 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002192 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002193 continue;
2194 if (!N->hasAnyUseOfValue(i))
2195 continue;
2196 unsigned Reg = ImpDefs[i - NumDefs];
2197 for (;*SUImpDefs; ++SUImpDefs) {
2198 unsigned SUReg = *SUImpDefs;
2199 if (TRI->regsOverlap(Reg, SUReg))
2200 return true;
2201 }
Evan Chengf9891412007-12-20 09:25:31 +00002202 }
2203 }
2204 return false;
2205}
2206
Dan Gohman9a658d72009-03-24 00:49:12 +00002207/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2208/// are not handled well by the general register pressure reduction
2209/// heuristics. When presented with code like this:
2210///
2211/// N
2212/// / |
2213/// / |
2214/// U store
2215/// |
2216/// ...
2217///
2218/// the heuristics tend to push the store up, but since the
2219/// operand of the store has another use (U), this would increase
2220/// the length of that other use (the U->N edge).
2221///
2222/// This function transforms code like the above to route U's
2223/// dependence through the store when possible, like this:
2224///
2225/// N
2226/// ||
2227/// ||
2228/// store
2229/// |
2230/// U
2231/// |
2232/// ...
2233///
2234/// This results in the store being scheduled immediately
2235/// after N, which shortens the U->N live range, reducing
2236/// register pressure.
2237///
Andrew Trick9ccce772011-01-14 21:11:41 +00002238void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002239 // Visit all the nodes in topological order, working top-down.
2240 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2241 SUnit *SU = &(*SUnits)[i];
2242 // For now, only look at nodes with no data successors, such as stores.
2243 // These are especially important, due to the heuristics in
2244 // getNodePriority for nodes with no data successors.
2245 if (SU->NumSuccs != 0)
2246 continue;
2247 // For now, only look at nodes with exactly one data predecessor.
2248 if (SU->NumPreds != 1)
2249 continue;
2250 // Avoid prescheduling copies to virtual registers, which don't behave
2251 // like other nodes from the perspective of scheduling heuristics.
2252 if (SDNode *N = SU->getNode())
2253 if (N->getOpcode() == ISD::CopyToReg &&
2254 TargetRegisterInfo::isVirtualRegister
2255 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2256 continue;
2257
2258 // Locate the single data predecessor.
2259 SUnit *PredSU = 0;
2260 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2261 EE = SU->Preds.end(); II != EE; ++II)
2262 if (!II->isCtrl()) {
2263 PredSU = II->getSUnit();
2264 break;
2265 }
2266 assert(PredSU);
2267
2268 // Don't rewrite edges that carry physregs, because that requires additional
2269 // support infrastructure.
2270 if (PredSU->hasPhysRegDefs)
2271 continue;
2272 // Short-circuit the case where SU is PredSU's only data successor.
2273 if (PredSU->NumSuccs == 1)
2274 continue;
2275 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002276 // like other nodes from the perspective of scheduling heuristics.
Dan Gohman9a658d72009-03-24 00:49:12 +00002277 if (SDNode *N = SU->getNode())
2278 if (N->getOpcode() == ISD::CopyFromReg &&
2279 TargetRegisterInfo::isVirtualRegister
2280 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2281 continue;
2282
2283 // Perform checks on the successors of PredSU.
2284 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2285 EE = PredSU->Succs.end(); II != EE; ++II) {
2286 SUnit *PredSuccSU = II->getSUnit();
2287 if (PredSuccSU == SU) continue;
2288 // If PredSU has another successor with no data successors, for
2289 // now don't attempt to choose either over the other.
2290 if (PredSuccSU->NumSuccs == 0)
2291 goto outer_loop_continue;
2292 // Don't break physical register dependencies.
2293 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2294 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2295 goto outer_loop_continue;
2296 // Don't introduce graph cycles.
2297 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2298 goto outer_loop_continue;
2299 }
2300
2301 // Ok, the transformation is safe and the heuristics suggest it is
2302 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002303 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2304 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002305 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002306 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2307 SDep Edge = PredSU->Succs[i];
2308 assert(!Edge.isAssignedRegDep());
2309 SUnit *SuccSU = Edge.getSUnit();
2310 if (SuccSU != SU) {
2311 Edge.setSUnit(PredSU);
2312 scheduleDAG->RemovePred(SuccSU, Edge);
2313 scheduleDAG->AddPred(SU, Edge);
2314 Edge.setSUnit(SU);
2315 scheduleDAG->AddPred(SuccSU, Edge);
2316 --i;
2317 }
2318 }
2319 outer_loop_continue:;
2320 }
2321}
2322
Evan Chengd38c22b2006-05-11 23:55:42 +00002323/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2324/// it as a def&use operand. Add a pseudo control edge from it to the other
2325/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002326/// first (lower in the schedule). If both nodes are two-address, favor the
2327/// one that has a CopyToReg use (more likely to be a loop induction update).
2328/// If both are two-address, but one is commutable while the other is not
2329/// commutable, favor the one that's not commutable.
Andrew Trick9ccce772011-01-14 21:11:41 +00002330void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002331 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002332 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002333 if (!SU->isTwoAddress)
2334 continue;
2335
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002336 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002337 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002338 continue;
2339
Evan Cheng6c1414f2010-10-29 18:09:28 +00002340 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002341 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002342 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002343 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002344 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002345 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002346 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2347 continue;
2348 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2349 if (DU->getNodeId() == -1)
2350 continue;
2351 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2352 if (!DUSU) continue;
2353 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2354 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002355 if (I->isCtrl()) continue;
2356 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002357 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002358 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002359 // Be conservative. Ignore if nodes aren't at roughly the same
2360 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002361 if (SuccSU->getHeight() < SU->getHeight() &&
2362 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002363 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002364 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2365 // constrains whatever is using the copy, instead of the copy
2366 // itself. In the case that the copy is coalesced, this
2367 // preserves the intent of the pseudo two-address heurietics.
2368 while (SuccSU->Succs.size() == 1 &&
2369 SuccSU->getNode()->isMachineOpcode() &&
2370 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002371 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002372 SuccSU = SuccSU->Succs.front().getSUnit();
2373 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002374 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2375 continue;
2376 // Don't constrain nodes with physical register defs if the
2377 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002378 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002379 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002380 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002381 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002382 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2383 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002384 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002385 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2386 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2387 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002388 continue;
2389 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002390 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002391 (!SU->isCommutable && SuccSU->isCommutable)) &&
2392 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002393 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002394 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002395 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002396 /*Reg=*/0, /*isNormalMemory=*/false,
2397 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002398 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002399 }
2400 }
2401 }
2402 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002403}
2404
Roman Levenstein30d09512008-03-27 09:44:37 +00002405/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002406/// predecessors of the successors of the SUnit SU. Stop when the provided
2407/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002408static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002409 unsigned Limit) {
2410 unsigned Sum = 0;
2411 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2412 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002413 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002414 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2415 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002416 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002417 if (!PredSU->isScheduled)
2418 if (++Sum > Limit)
2419 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002420 }
2421 }
2422 return Sum;
2423}
2424
Evan Chengd38c22b2006-05-11 23:55:42 +00002425
2426// Top down
2427bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00002428 unsigned LPriority = SPQ->getNodePriority(left);
2429 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002430 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2431 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002432 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2433 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002434 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2435 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002436
2437 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2438 return false;
2439 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2440 return true;
2441
Evan Chengd38c22b2006-05-11 23:55:42 +00002442 if (LIsFloater)
2443 LBonus -= 2;
2444 if (RIsFloater)
2445 RBonus -= 2;
2446 if (left->NumSuccs == 1)
2447 LBonus += 2;
2448 if (right->NumSuccs == 1)
2449 RBonus += 2;
2450
Evan Cheng73bdf042008-03-01 00:39:47 +00002451 if (LPriority+LBonus != RPriority+RBonus)
2452 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002453
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002454 if (left->getDepth() != right->getDepth())
2455 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002456
2457 if (left->NumSuccsLeft != right->NumSuccsLeft)
2458 return left->NumSuccsLeft > right->NumSuccsLeft;
2459
Andrew Trick2085a962010-12-21 22:25:04 +00002460 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002461 "NodeQueueId cannot be zero");
2462 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002463}
2464
Evan Chengd38c22b2006-05-11 23:55:42 +00002465//===----------------------------------------------------------------------===//
2466// Public Constructor Functions
2467//===----------------------------------------------------------------------===//
2468
Dan Gohmandfaf6462009-02-11 04:27:20 +00002469llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002470llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2471 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002472 const TargetMachine &TM = IS->TM;
2473 const TargetInstrInfo *TII = TM.getInstrInfo();
2474 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002475
Evan Chenga77f3d32010-07-21 06:09:07 +00002476 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002477 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002478 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002479 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002480 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002481}
2482
Dan Gohmandfaf6462009-02-11 04:27:20 +00002483llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002484llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2485 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002486 const TargetMachine &TM = IS->TM;
2487 const TargetInstrInfo *TII = TM.getInstrInfo();
2488 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002489
Evan Chenga77f3d32010-07-21 06:09:07 +00002490 TDRegReductionPriorityQueue *PQ =
2491 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002492 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002493 PQ->setScheduleDAG(SD);
2494 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002495}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002496
2497llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002498llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2499 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002500 const TargetMachine &TM = IS->TM;
2501 const TargetInstrInfo *TII = TM.getInstrInfo();
2502 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002503
Evan Chenga77f3d32010-07-21 06:09:07 +00002504 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002505 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002506 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002507 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002508 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002509}
2510
2511llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002512llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2513 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002514 const TargetMachine &TM = IS->TM;
2515 const TargetInstrInfo *TII = TM.getInstrInfo();
2516 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002517 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002518
Evan Chenga77f3d32010-07-21 06:09:07 +00002519 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002520 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002521
2522 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002523 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002524 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002525}
Evan Cheng37b740c2010-07-24 00:39:05 +00002526
2527llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002528llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2529 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002530 const TargetMachine &TM = IS->TM;
2531 const TargetInstrInfo *TII = TM.getInstrInfo();
2532 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2533 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002534
Evan Cheng37b740c2010-07-24 00:39:05 +00002535 ILPBURRPriorityQueue *PQ =
2536 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002537 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002538 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002539 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002540}