blob: e43bcfdac9b21a3fa35ee584b73cd1128491a953 [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(
70 "disable-sched-cycles", cl::Hidden, cl::init(true),
71 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
298 if (isReady(SU)) {
299 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 Trick033efdf2010-12-23 03:15:51 +0000505 // Update liveness of predecessors before successors to avoid treating a
506 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000507 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000508
509 // Release all the implicit physical register defs that are live.
510 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
511 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000512 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
513 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
514 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
515 --NumLiveRegs;
516 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000517 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000518 }
519 }
520
Evan Chengd38c22b2006-05-11 23:55:42 +0000521 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000522
523 // Conditions under which the scheduler should eagerly advance the cycle:
524 // (1) No available instructions
525 // (2) All pipelines full, so available instructions must have hazards.
526 //
Andrew Trick47ff14b2011-01-21 05:51:33 +0000527 // If HazardRec is disabled, count each inst as one cycle.
528 if (!HazardRec->isEnabled() || HazardRec->atIssueLimit()
529 || AvailableQueue->empty())
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000530 AdvanceToCycle(CurCycle + 1);
Evan Chengd38c22b2006-05-11 23:55:42 +0000531}
532
Evan Cheng5924bf72007-09-25 01:54:36 +0000533/// CapturePred - This does the opposite of ReleasePred. Since SU is being
534/// unscheduled, incrcease the succ left count of its predecessors. Remove
535/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000536void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000537 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000538 if (PredSU->isAvailable) {
539 PredSU->isAvailable = false;
540 if (!PredSU->isPending)
541 AvailableQueue->remove(PredSU);
542 }
543
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000544 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000545 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000546}
547
548/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
549/// its predecessor states to reflect the change.
550void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000551 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000552 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000553
Evan Cheng5924bf72007-09-25 01:54:36 +0000554 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
555 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000556 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000557 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000558 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000559 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000560 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000561 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000562 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000563 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000564 }
565 }
566
567 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
568 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000569 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000570 // This becomes the nearest def. Note that an earlier def may still be
571 // pending if this is a two-address node.
572 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000573 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000574 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000575 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000576 if (LiveRegGens[I->getReg()] == NULL ||
577 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
578 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000579 }
580 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000581 if (SU->getHeight() < MinAvailableCycle)
582 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000583
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000584 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000585 SU->isScheduled = false;
586 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000587 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000588 // Don't make available until backtracking is complete.
589 SU->isPending = true;
590 PendingQueue.push_back(SU);
591 }
592 else {
593 AvailableQueue->push(SU);
594 }
Evan Cheng28590382010-07-21 23:53:58 +0000595 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000596}
597
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000598/// After backtracking, the hazard checker needs to be restored to a state
599/// corresponding the the current cycle.
600void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
601 HazardRec->Reset();
602
603 unsigned LookAhead = std::min((unsigned)Sequence.size(),
604 HazardRec->getMaxLookAhead());
605 if (LookAhead == 0)
606 return;
607
608 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
609 unsigned HazardCycle = (*I)->getHeight();
610 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
611 SUnit *SU = *I;
612 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
613 HazardRec->RecedeCycle();
614 }
615 EmitNode(SU);
616 }
617}
618
Evan Cheng8e136a92007-09-26 21:36:17 +0000619/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000620/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000621void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
622 SUnit *OldSU = Sequence.back();
623 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000624 Sequence.pop_back();
625 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000626 // Don't try to remove SU from AvailableQueue.
627 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000628 // FIXME: use ready cycle instead of height
629 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000630 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000631 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000632 if (OldSU == BtSU)
633 break;
634 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000635 }
636
Dan Gohman60d68442009-01-29 19:49:27 +0000637 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000638
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000639 RestoreHazardCheckerBottomUp();
640
Andrew Trick5ce945c2010-12-24 07:10:19 +0000641 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000642
Evan Cheng1ec79b42007-09-27 07:09:03 +0000643 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000644}
645
Evan Cheng3b245872010-02-05 01:27:11 +0000646static bool isOperandOf(const SUnit *SU, SDNode *N) {
647 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000648 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000649 if (SUNode->isOperandOf(N))
650 return true;
651 }
652 return false;
653}
654
Evan Cheng5924bf72007-09-25 01:54:36 +0000655/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
656/// successors to the newly created node.
657SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000658 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000659 if (!N)
660 return NULL;
661
Andrew Trickc9405662010-12-24 06:46:50 +0000662 if (SU->getNode()->getGluedNode())
663 return NULL;
664
Evan Cheng79e97132007-10-05 01:39:18 +0000665 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000666 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000667 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000668 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000669 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000670 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000671 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000672 TryUnfold = true;
673 }
Evan Cheng79e97132007-10-05 01:39:18 +0000674 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000675 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000676 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000677 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000678 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000679 }
680
681 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000682 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000683 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000684 return NULL;
685
Evan Chengbdd062d2010-05-20 06:13:19 +0000686 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000687 assert(NewNodes.size() == 2 && "Expected a load folding node!");
688
689 N = NewNodes[1];
690 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000691 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000692 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000693 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000694 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
695 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000696 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000697
Dan Gohmane52e0892008-11-11 21:34:44 +0000698 // LoadNode may already exist. This can happen when there is another
699 // load from the same location and producing the same type of value
700 // but it has different alignment or volatileness.
701 bool isNewLoad = true;
702 SUnit *LoadSU;
703 if (LoadNode->getNodeId() != -1) {
704 LoadSU = &SUnits[LoadNode->getNodeId()];
705 isNewLoad = false;
706 } else {
707 LoadSU = CreateNewSUnit(LoadNode);
708 LoadNode->setNodeId(LoadSU->NodeNum);
Dan Gohmane52e0892008-11-11 21:34:44 +0000709 ComputeLatency(LoadSU);
710 }
711
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000712 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000713 assert(N->getNodeId() == -1 && "Node already inserted!");
714 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000715
Dan Gohman17059682008-07-17 19:10:17 +0000716 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000717 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000718 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000719 NewSU->isTwoAddress = true;
720 break;
721 }
722 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000723 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000724 NewSU->isCommutable = true;
Evan Cheng79e97132007-10-05 01:39:18 +0000725 ComputeLatency(NewSU);
726
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000727 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000728 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000729 SmallVector<SDep, 4> ChainSuccs;
730 SmallVector<SDep, 4> LoadPreds;
731 SmallVector<SDep, 4> NodePreds;
732 SmallVector<SDep, 4> NodeSuccs;
733 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
734 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000735 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000736 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000737 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000738 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000739 else
Dan Gohman2d170892008-12-09 22:54:47 +0000740 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000741 }
742 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
743 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000744 if (I->isCtrl())
745 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000746 else
Dan Gohman2d170892008-12-09 22:54:47 +0000747 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000748 }
749
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000750 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000751 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
752 const SDep &Pred = ChainPreds[i];
753 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000754 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000755 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000756 }
Evan Cheng79e97132007-10-05 01:39:18 +0000757 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000758 const SDep &Pred = LoadPreds[i];
759 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000760 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000761 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000762 }
763 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000764 const SDep &Pred = NodePreds[i];
765 RemovePred(SU, Pred);
766 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000767 }
768 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000769 SDep D = NodeSuccs[i];
770 SUnit *SuccDep = D.getSUnit();
771 D.setSUnit(SU);
772 RemovePred(SuccDep, D);
773 D.setSUnit(NewSU);
774 AddPred(SuccDep, D);
Evan Cheng79e97132007-10-05 01:39:18 +0000775 }
776 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000777 SDep D = ChainSuccs[i];
778 SUnit *SuccDep = D.getSUnit();
779 D.setSUnit(SU);
780 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000781 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000782 D.setSUnit(LoadSU);
783 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000784 }
Andrew Trick2085a962010-12-21 22:25:04 +0000785 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000786
787 // Add a data dependency to reflect that NewSU reads the value defined
788 // by LoadSU.
789 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000790
Evan Cheng91e0fc92007-12-18 08:42:10 +0000791 if (isNewLoad)
792 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000793 AvailableQueue->addNode(NewSU);
794
795 ++NumUnfolds;
796
797 if (NewSU->NumSuccsLeft == 0) {
798 NewSU->isAvailable = true;
799 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000800 }
801 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000802 }
803
Evan Chengbdd062d2010-05-20 06:13:19 +0000804 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000805 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000806
807 // New SUnit has the exact same predecessors.
808 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
809 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000810 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000811 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000812
813 // Only copy scheduled successors. Cut them from old node's successor
814 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000815 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000816 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
817 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000818 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000819 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000820 SUnit *SuccSU = I->getSUnit();
821 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000822 SDep D = *I;
823 D.setSUnit(NewSU);
824 AddPred(SuccSU, D);
825 D.setSUnit(SU);
826 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000827 }
828 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000829 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000830 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000831
832 AvailableQueue->updateNode(SU);
833 AvailableQueue->addNode(NewSU);
834
Evan Cheng1ec79b42007-09-27 07:09:03 +0000835 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000836 return NewSU;
837}
838
Evan Chengb2c42c62009-01-12 03:19:55 +0000839/// InsertCopiesAndMoveSuccs - Insert register copies and move all
840/// scheduled successors of the given SUnit to the last copy.
841void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
842 const TargetRegisterClass *DestRC,
843 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000844 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000845 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000846 CopyFromSU->CopySrcRC = SrcRC;
847 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000848
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000849 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000850 CopyToSU->CopySrcRC = DestRC;
851 CopyToSU->CopyDstRC = SrcRC;
852
853 // Only copy scheduled successors. Cut them from old node's successor
854 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000855 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000856 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
857 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000858 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000859 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000860 SUnit *SuccSU = I->getSUnit();
861 if (SuccSU->isScheduled) {
862 SDep D = *I;
863 D.setSUnit(CopyToSU);
864 AddPred(SuccSU, D);
865 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000866 }
867 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000868 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000869 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000870
Dan Gohman2d170892008-12-09 22:54:47 +0000871 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
872 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +0000873
874 AvailableQueue->updateNode(SU);
875 AvailableQueue->addNode(CopyFromSU);
876 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000877 Copies.push_back(CopyFromSU);
878 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000879
Evan Chengb2c42c62009-01-12 03:19:55 +0000880 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000881}
882
883/// getPhysicalRegisterVT - Returns the ValueType of the physical register
884/// definition of the specified node.
885/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +0000886static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +0000887 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +0000888 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000889 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000890 unsigned NumRes = TID.getNumDefs();
891 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000892 if (Reg == *ImpDef)
893 break;
894 ++NumRes;
895 }
896 return N->getValueType(NumRes);
897}
898
Evan Chengb8905c42009-03-04 01:41:49 +0000899/// CheckForLiveRegDef - Return true and update live register vector if the
900/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000901static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +0000902 std::vector<SUnit*> &LiveRegDefs,
903 SmallSet<unsigned, 4> &RegAdded,
904 SmallVector<unsigned, 4> &LRegs,
905 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +0000906 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
907
908 // Check if Ref is live.
909 if (!LiveRegDefs[Reg]) continue;
910
911 // Allow multiple uses of the same def.
912 if (LiveRegDefs[Reg] == SU) continue;
913
914 // Add Reg to the set of interfering live regs.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000915 if (RegAdded.insert(Reg))
Evan Chengb8905c42009-03-04 01:41:49 +0000916 LRegs.push_back(Reg);
Evan Chengb8905c42009-03-04 01:41:49 +0000917 }
Evan Chengb8905c42009-03-04 01:41:49 +0000918}
919
Evan Cheng5924bf72007-09-25 01:54:36 +0000920/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
921/// scheduling of the given node to satisfy live physical register dependencies.
922/// If the specific node is the last one that's available to schedule, do
923/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000924bool ScheduleDAGRRList::
925DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000926 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +0000927 return false;
928
Evan Chenge6f92252007-09-27 18:46:06 +0000929 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000930 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000931 //
932 // If SU is the currently live definition of the same register that it uses,
933 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +0000934 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
935 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000936 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +0000937 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
938 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000939 }
940
Chris Lattner11a33812010-12-23 17:24:32 +0000941 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +0000942 if (Node->getOpcode() == ISD::INLINEASM) {
943 // Inline asm can clobber physical defs.
944 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000945 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +0000946 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +0000947
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000948 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +0000949 unsigned Flags =
950 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000951 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +0000952
953 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000954 if (InlineAsm::isRegDefKind(Flags) ||
955 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +0000956 // Check for def of register or earlyclobber register.
957 for (; NumVals; --NumVals, ++i) {
958 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
959 if (TargetRegisterInfo::isPhysicalRegister(Reg))
960 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
961 }
962 } else
963 i += NumVals;
964 }
965 continue;
966 }
967
Dan Gohman072734e2008-11-13 23:24:17 +0000968 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000969 continue;
Dan Gohman17059682008-07-17 19:10:17 +0000970 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +0000971 if (!TID.ImplicitDefs)
972 continue;
Evan Chengb8905c42009-03-04 01:41:49 +0000973 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
974 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000975 }
Andrew Trick2085a962010-12-21 22:25:04 +0000976
Evan Cheng5924bf72007-09-25 01:54:36 +0000977 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000978}
979
Andrew Trick528fad92010-12-23 05:42:20 +0000980/// Return a node that can be scheduled in this cycle. Requirements:
981/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000982/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +0000983/// (3) No Interferences: may unschedule to break register interferences.
984SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
985 SmallVector<SUnit*, 4> Interferences;
986 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
987
988 SUnit *CurSU = AvailableQueue->pop();
989 while (CurSU) {
990 SmallVector<unsigned, 4> LRegs;
991 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
992 break;
993 LRegsMap.insert(std::make_pair(CurSU, LRegs));
994
995 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
996 Interferences.push_back(CurSU);
997 CurSU = AvailableQueue->pop();
998 }
999 if (CurSU) {
1000 // Add the nodes that aren't ready back onto the available list.
1001 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1002 Interferences[i]->isPending = false;
1003 assert(Interferences[i]->isAvailable && "must still be available");
1004 AvailableQueue->push(Interferences[i]);
1005 }
1006 return CurSU;
1007 }
1008
1009 // All candidates are delayed due to live physical reg dependencies.
1010 // Try backtracking, code duplication, or inserting cross class copies
1011 // to resolve it.
1012 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1013 SUnit *TrySU = Interferences[i];
1014 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1015
1016 // Try unscheduling up to the point where it's safe to schedule
1017 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001018 SUnit *BtSU = NULL;
1019 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001020 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1021 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001022 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1023 BtSU = LiveRegGens[Reg];
1024 LiveCycle = BtSU->getHeight();
1025 }
Andrew Trick528fad92010-12-23 05:42:20 +00001026 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001027 if (!WillCreateCycle(TrySU, BtSU)) {
1028 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001029
1030 // Force the current node to be scheduled before the node that
1031 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001032 if (BtSU->isAvailable) {
1033 BtSU->isAvailable = false;
1034 if (!BtSU->isPending)
1035 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001036 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001037 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001038 /*Reg=*/0, /*isNormalMemory=*/false,
1039 /*isMustAlias=*/false, /*isArtificial=*/true));
1040
1041 // If one or more successors has been unscheduled, then the current
1042 // node is no longer avaialable. Schedule a successor that's now
1043 // available instead.
1044 if (!TrySU->isAvailable) {
1045 CurSU = AvailableQueue->pop();
1046 }
1047 else {
1048 CurSU = TrySU;
1049 TrySU->isPending = false;
1050 Interferences.erase(Interferences.begin()+i);
1051 }
1052 break;
1053 }
1054 }
1055
1056 if (!CurSU) {
1057 // Can't backtrack. If it's too expensive to copy the value, then try
1058 // duplicate the nodes that produces these "too expensive to copy"
1059 // values to break the dependency. In case even that doesn't work,
1060 // insert cross class copies.
1061 // If it's not too expensive, i.e. cost != -1, issue copies.
1062 SUnit *TrySU = Interferences[0];
1063 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1064 assert(LRegs.size() == 1 && "Can't handle this yet!");
1065 unsigned Reg = LRegs[0];
1066 SUnit *LRDef = LiveRegDefs[Reg];
1067 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1068 const TargetRegisterClass *RC =
1069 TRI->getMinimalPhysRegClass(Reg, VT);
1070 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1071
1072 // If cross copy register class is null, then it must be possible copy
1073 // the value directly. Do not try duplicate the def.
1074 SUnit *NewDef = 0;
1075 if (DestRC)
1076 NewDef = CopyAndMoveSuccessors(LRDef);
1077 else
1078 DestRC = RC;
1079 if (!NewDef) {
1080 // Issue copies, these can be expensive cross register class copies.
1081 SmallVector<SUnit*, 2> Copies;
1082 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1083 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1084 << " to SU #" << Copies.front()->NodeNum << "\n");
1085 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1086 /*Reg=*/0, /*isNormalMemory=*/false,
1087 /*isMustAlias=*/false,
1088 /*isArtificial=*/true));
1089 NewDef = Copies.back();
1090 }
1091
1092 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1093 << " to SU #" << TrySU->NodeNum << "\n");
1094 LiveRegDefs[Reg] = NewDef;
1095 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1096 /*Reg=*/0, /*isNormalMemory=*/false,
1097 /*isMustAlias=*/false,
1098 /*isArtificial=*/true));
1099 TrySU->isAvailable = false;
1100 CurSU = NewDef;
1101 }
1102
1103 assert(CurSU && "Unable to resolve live physical register dependencies!");
1104
1105 // Add the nodes that aren't ready back onto the available list.
1106 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1107 Interferences[i]->isPending = false;
1108 // May no longer be available due to backtracking.
1109 if (Interferences[i]->isAvailable) {
1110 AvailableQueue->push(Interferences[i]);
1111 }
1112 }
1113 return CurSU;
1114}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001115
Evan Chengd38c22b2006-05-11 23:55:42 +00001116/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1117/// schedulers.
1118void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001119 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001120 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001121
Evan Chengd38c22b2006-05-11 23:55:42 +00001122 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001123 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001124 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001125 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1126 RootSU->isAvailable = true;
1127 AvailableQueue->push(RootSU);
1128 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001129
1130 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001131 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001132 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001133 while (!AvailableQueue->empty()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001134 DEBUG(dbgs() << "\n*** Examining Available\n";
1135 AvailableQueue->dump(this));
1136
Andrew Trick528fad92010-12-23 05:42:20 +00001137 // Pick the best node to schedule taking all constraints into
1138 // consideration.
1139 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001140
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001141 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001142
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001143 ScheduleNodeBottomUp(SU);
1144
1145 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1146 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1147 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1148 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1149 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001150 }
1151
Evan Chengd38c22b2006-05-11 23:55:42 +00001152 // Reverse the order if it is bottom up.
1153 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001154
Evan Chengd38c22b2006-05-11 23:55:42 +00001155#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001156 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001157#endif
1158}
1159
1160//===----------------------------------------------------------------------===//
1161// Top-Down Scheduling
1162//===----------------------------------------------------------------------===//
1163
1164/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001165/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001166void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001167 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001168
Evan Chengd38c22b2006-05-11 23:55:42 +00001169#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001170 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001171 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001172 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001173 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001174 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001175 }
1176#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001177 --SuccSU->NumPredsLeft;
1178
Dan Gohmanb9543432009-02-10 23:27:53 +00001179 // If all the node's predecessors are scheduled, this node is ready
1180 // to be scheduled. Ignore the special ExitSU node.
1181 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001182 SuccSU->isAvailable = true;
1183 AvailableQueue->push(SuccSU);
1184 }
1185}
1186
Dan Gohmanb9543432009-02-10 23:27:53 +00001187void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1188 // Top down: release successors
1189 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1190 I != E; ++I) {
1191 assert(!I->isAssignedRegDep() &&
1192 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1193
1194 ReleaseSucc(SU, &*I);
1195 }
1196}
1197
Evan Chengd38c22b2006-05-11 23:55:42 +00001198/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1199/// count of its successors. If a successor pending count is zero, add it to
1200/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001201void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001202 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001203 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001204
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001205 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1206 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001207 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001208
Dan Gohmanb9543432009-02-10 23:27:53 +00001209 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001210 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001211 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001212}
1213
Dan Gohman54a187e2007-08-20 19:28:38 +00001214/// ListScheduleTopDown - The main loop of list scheduling for top-down
1215/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001216void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001217 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001218
Dan Gohmanb9543432009-02-10 23:27:53 +00001219 // Release any successors of the special Entry node.
1220 ReleaseSuccessors(&EntrySU);
1221
Evan Chengd38c22b2006-05-11 23:55:42 +00001222 // All leaves to Available queue.
1223 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1224 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001225 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001226 AvailableQueue->push(&SUnits[i]);
1227 SUnits[i].isAvailable = true;
1228 }
1229 }
Andrew Trick2085a962010-12-21 22:25:04 +00001230
Evan Chengd38c22b2006-05-11 23:55:42 +00001231 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001232 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001233 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001234 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001235 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001236
Dan Gohmanc602dd42008-11-21 00:10:42 +00001237 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001238 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001239 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001240 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001241 }
Andrew Trick2085a962010-12-21 22:25:04 +00001242
Evan Chengd38c22b2006-05-11 23:55:42 +00001243#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001244 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001245#endif
1246}
1247
1248
Evan Chengd38c22b2006-05-11 23:55:42 +00001249//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001250// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001251//===----------------------------------------------------------------------===//
1252//
1253// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1254// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001255//
Evan Chengd38c22b2006-05-11 23:55:42 +00001256namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001257class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001258
Andrew Trick9ccce772011-01-14 21:11:41 +00001259struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1260 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1261};
1262
1263/// bu_ls_rr_sort - Priority function for bottom up register pressure
1264// reduction scheduler.
1265struct bu_ls_rr_sort : public queue_sort {
1266 enum {
1267 IsBottomUp = true,
1268 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001269 };
1270
Andrew Trick9ccce772011-01-14 21:11:41 +00001271 RegReductionPQBase *SPQ;
1272 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1273 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001274
Andrew Trick9ccce772011-01-14 21:11:41 +00001275 bool operator()(SUnit* left, SUnit* right) const;
1276};
Andrew Trick2085a962010-12-21 22:25:04 +00001277
Andrew Trick9ccce772011-01-14 21:11:41 +00001278// td_ls_rr_sort - Priority function for top down register pressure reduction
1279// scheduler.
1280struct td_ls_rr_sort : public queue_sort {
1281 enum {
1282 IsBottomUp = false,
1283 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001284 };
1285
Andrew Trick9ccce772011-01-14 21:11:41 +00001286 RegReductionPQBase *SPQ;
1287 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1288 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001289
Andrew Trick9ccce772011-01-14 21:11:41 +00001290 bool operator()(const SUnit* left, const SUnit* right) const;
1291};
Andrew Trick2085a962010-12-21 22:25:04 +00001292
Andrew Trick9ccce772011-01-14 21:11:41 +00001293// src_ls_rr_sort - Priority function for source order scheduler.
1294struct src_ls_rr_sort : public queue_sort {
1295 enum {
1296 IsBottomUp = true,
1297 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001298 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001299
Andrew Trick9ccce772011-01-14 21:11:41 +00001300 RegReductionPQBase *SPQ;
1301 src_ls_rr_sort(RegReductionPQBase *spq)
1302 : SPQ(spq) {}
1303 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1304 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001305
Andrew Trick9ccce772011-01-14 21:11:41 +00001306 bool operator()(SUnit* left, SUnit* right) const;
1307};
Andrew Trick2085a962010-12-21 22:25:04 +00001308
Andrew Trick9ccce772011-01-14 21:11:41 +00001309// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1310struct hybrid_ls_rr_sort : public queue_sort {
1311 enum {
1312 IsBottomUp = true,
1313 HasReadyFilter = true
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001314 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001315
Andrew Trick9ccce772011-01-14 21:11:41 +00001316 RegReductionPQBase *SPQ;
1317 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1318 : SPQ(spq) {}
1319 hybrid_ls_rr_sort(const hybrid_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 isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001323
Andrew Trick9ccce772011-01-14 21:11:41 +00001324 bool operator()(SUnit* left, SUnit* right) const;
1325};
1326
1327// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1328// scheduler.
1329struct ilp_ls_rr_sort : public queue_sort {
1330 enum {
1331 IsBottomUp = true,
1332 HasReadyFilter = true
Evan Chengbdd062d2010-05-20 06:13:19 +00001333 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001334
Andrew Trick9ccce772011-01-14 21:11:41 +00001335 RegReductionPQBase *SPQ;
1336 ilp_ls_rr_sort(RegReductionPQBase *spq)
1337 : SPQ(spq) {}
1338 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1339 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001340
Andrew Trick9ccce772011-01-14 21:11:41 +00001341 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001342
Andrew Trick9ccce772011-01-14 21:11:41 +00001343 bool operator()(SUnit* left, SUnit* right) const;
1344};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001345
Andrew Trick9ccce772011-01-14 21:11:41 +00001346class RegReductionPQBase : public SchedulingPriorityQueue {
1347protected:
1348 std::vector<SUnit*> Queue;
1349 unsigned CurQueueId;
1350 bool TracksRegPressure;
1351
1352 // SUnits - The SUnits for the current graph.
1353 std::vector<SUnit> *SUnits;
1354
1355 MachineFunction &MF;
1356 const TargetInstrInfo *TII;
1357 const TargetRegisterInfo *TRI;
1358 const TargetLowering *TLI;
1359 ScheduleDAGRRList *scheduleDAG;
1360
1361 // SethiUllmanNumbers - The SethiUllman number for each node.
1362 std::vector<unsigned> SethiUllmanNumbers;
1363
1364 /// RegPressure - Tracking current reg pressure per register class.
1365 ///
1366 std::vector<unsigned> RegPressure;
1367
1368 /// RegLimit - Tracking the number of allocatable registers per register
1369 /// class.
1370 std::vector<unsigned> RegLimit;
1371
1372public:
1373 RegReductionPQBase(MachineFunction &mf,
1374 bool hasReadyFilter,
1375 bool tracksrp,
1376 const TargetInstrInfo *tii,
1377 const TargetRegisterInfo *tri,
1378 const TargetLowering *tli)
1379 : SchedulingPriorityQueue(hasReadyFilter),
1380 CurQueueId(0), TracksRegPressure(tracksrp),
1381 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1382 if (TracksRegPressure) {
1383 unsigned NumRC = TRI->getNumRegClasses();
1384 RegLimit.resize(NumRC);
1385 RegPressure.resize(NumRC);
1386 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1387 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1388 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1389 E = TRI->regclass_end(); I != E; ++I)
1390 RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
1391 }
1392 }
1393
1394 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1395 scheduleDAG = scheduleDag;
1396 }
1397
1398 ScheduleHazardRecognizer* getHazardRec() {
1399 return scheduleDAG->getHazardRec();
1400 }
1401
1402 void initNodes(std::vector<SUnit> &sunits);
1403
1404 void addNode(const SUnit *SU);
1405
1406 void updateNode(const SUnit *SU);
1407
1408 void releaseState() {
1409 SUnits = 0;
1410 SethiUllmanNumbers.clear();
1411 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1412 }
1413
1414 unsigned getNodePriority(const SUnit *SU) const;
1415
1416 unsigned getNodeOrdering(const SUnit *SU) const {
1417 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1418 }
1419
1420 bool empty() const { return Queue.empty(); }
1421
1422 void push(SUnit *U) {
1423 assert(!U->NodeQueueId && "Node in the queue already");
1424 U->NodeQueueId = ++CurQueueId;
1425 Queue.push_back(U);
1426 }
1427
1428 void remove(SUnit *SU) {
1429 assert(!Queue.empty() && "Queue is empty!");
1430 assert(SU->NodeQueueId != 0 && "Not in queue!");
1431 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1432 SU);
1433 if (I != prior(Queue.end()))
1434 std::swap(*I, Queue.back());
1435 Queue.pop_back();
1436 SU->NodeQueueId = 0;
1437 }
1438
1439 void dumpRegPressure() const;
1440
1441 bool HighRegPressure(const SUnit *SU) const;
1442
1443 bool MayReduceRegPressure(SUnit *SU);
1444
1445 void ScheduledNode(SUnit *SU);
1446
1447 void UnscheduledNode(SUnit *SU);
1448
1449protected:
1450 bool canClobber(const SUnit *SU, const SUnit *Op);
1451 void AddPseudoTwoAddrDeps();
1452 void PrescheduleNodesWithMultipleUses();
1453 void CalculateSethiUllmanNumbers();
1454};
1455
1456template<class SF>
1457class RegReductionPriorityQueue : public RegReductionPQBase {
1458 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1459 std::vector<SUnit *>::iterator Best = Q.begin();
1460 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1461 E = Q.end(); I != E; ++I)
1462 if (Picker(*Best, *I))
1463 Best = I;
1464 SUnit *V = *Best;
1465 if (Best != prior(Q.end()))
1466 std::swap(*Best, Q.back());
1467 Q.pop_back();
1468 return V;
1469 }
1470
1471 SF Picker;
1472
1473public:
1474 RegReductionPriorityQueue(MachineFunction &mf,
1475 bool tracksrp,
1476 const TargetInstrInfo *tii,
1477 const TargetRegisterInfo *tri,
1478 const TargetLowering *tli)
1479 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1480 Picker(this) {}
1481
1482 bool isBottomUp() const { return SF::IsBottomUp; }
1483
1484 bool isReady(SUnit *U) const {
1485 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1486 }
1487
1488 SUnit *pop() {
1489 if (Queue.empty()) return NULL;
1490
1491 SUnit *V = popFromQueue(Queue, Picker);
1492 V->NodeQueueId = 0;
1493 return V;
1494 }
1495
1496 void dump(ScheduleDAG *DAG) const {
1497 // Emulate pop() without clobbering NodeQueueIds.
1498 std::vector<SUnit*> DumpQueue = Queue;
1499 SF DumpPicker = Picker;
1500 while (!DumpQueue.empty()) {
1501 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1502 if (isBottomUp())
1503 dbgs() << "Height " << SU->getHeight() << ": ";
1504 else
1505 dbgs() << "Depth " << SU->getDepth() << ": ";
1506 SU->dump(DAG);
1507 }
1508 }
1509};
1510
1511typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1512BURegReductionPriorityQueue;
1513
1514typedef RegReductionPriorityQueue<td_ls_rr_sort>
1515TDRegReductionPriorityQueue;
1516
1517typedef RegReductionPriorityQueue<src_ls_rr_sort>
1518SrcRegReductionPriorityQueue;
1519
1520typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1521HybridBURRPriorityQueue;
1522
1523typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1524ILPBURRPriorityQueue;
1525} // end anonymous namespace
1526
1527//===----------------------------------------------------------------------===//
1528// Static Node Priority for Register Pressure Reduction
1529//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001530
Dan Gohman186f65d2008-11-20 03:30:37 +00001531/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1532/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001533static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001534CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001535 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1536 if (SethiUllmanNumber != 0)
1537 return SethiUllmanNumber;
1538
1539 unsigned Extra = 0;
1540 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1541 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001542 if (I->isCtrl()) continue; // ignore chain preds
1543 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001544 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001545 if (PredSethiUllman > SethiUllmanNumber) {
1546 SethiUllmanNumber = PredSethiUllman;
1547 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001548 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001549 ++Extra;
1550 }
1551
1552 SethiUllmanNumber += Extra;
1553
1554 if (SethiUllmanNumber == 0)
1555 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001556
Evan Cheng7e4abde2008-07-02 09:23:51 +00001557 return SethiUllmanNumber;
1558}
1559
Andrew Trick9ccce772011-01-14 21:11:41 +00001560/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1561/// scheduling units.
1562void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1563 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001564
Andrew Trick9ccce772011-01-14 21:11:41 +00001565 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1566 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001567}
1568
Andrew Trick9ccce772011-01-14 21:11:41 +00001569void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1570 SUnits = &sunits;
1571 // Add pseudo dependency edges for two-address nodes.
1572 AddPseudoTwoAddrDeps();
1573 // Reroute edges to nodes with multiple uses.
1574 PrescheduleNodesWithMultipleUses();
1575 // Calculate node priorities.
1576 CalculateSethiUllmanNumbers();
1577}
1578
1579void RegReductionPQBase::addNode(const SUnit *SU) {
1580 unsigned SUSize = SethiUllmanNumbers.size();
1581 if (SUnits->size() > SUSize)
1582 SethiUllmanNumbers.resize(SUSize*2, 0);
1583 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1584}
1585
1586void RegReductionPQBase::updateNode(const SUnit *SU) {
1587 SethiUllmanNumbers[SU->NodeNum] = 0;
1588 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1589}
1590
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001591// Lower priority means schedule further down. For bottom-up scheduling, lower
1592// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001593unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1594 assert(SU->NodeNum < SethiUllmanNumbers.size());
1595 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1596 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1597 // CopyToReg should be close to its uses to facilitate coalescing and
1598 // avoid spilling.
1599 return 0;
1600 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1601 Opc == TargetOpcode::SUBREG_TO_REG ||
1602 Opc == TargetOpcode::INSERT_SUBREG)
1603 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1604 // close to their uses to facilitate coalescing.
1605 return 0;
1606 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1607 // If SU does not have a register use, i.e. it doesn't produce a value
1608 // that would be consumed (e.g. store), then it terminates a chain of
1609 // computation. Give it a large SethiUllman number so it will be
1610 // scheduled right before its predecessors that it doesn't lengthen
1611 // their live ranges.
1612 return 0xffff;
1613 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1614 // If SU does not have a register def, schedule it close to its uses
1615 // because it does not lengthen any live ranges.
1616 return 0;
1617 return SethiUllmanNumbers[SU->NodeNum];
1618}
1619
1620//===----------------------------------------------------------------------===//
1621// Register Pressure Tracking
1622//===----------------------------------------------------------------------===//
1623
1624void RegReductionPQBase::dumpRegPressure() const {
1625 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1626 E = TRI->regclass_end(); I != E; ++I) {
1627 const TargetRegisterClass *RC = *I;
1628 unsigned Id = RC->getID();
1629 unsigned RP = RegPressure[Id];
1630 if (!RP) continue;
1631 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1632 << '\n');
1633 }
1634}
1635
1636bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1637 if (!TLI)
1638 return false;
1639
1640 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1641 I != E; ++I) {
1642 if (I->isCtrl())
1643 continue;
1644 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001645 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1646 // counts data deps. To be more precise, we could maintain a
1647 // NumDataSuccsLeft count.
1648 if (PredSU->NumSuccsLeft != PredSU->Succs.size()) {
1649 DEBUG(dbgs() << " SU(" << PredSU->NodeNum << ") live across SU("
1650 << SU->NodeNum << ")\n");
1651 continue;
1652 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001653 const SDNode *PN = PredSU->getNode();
1654 if (!PN->isMachineOpcode()) {
1655 if (PN->getOpcode() == ISD::CopyFromReg) {
1656 EVT VT = PN->getValueType(0);
1657 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1658 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1659 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1660 return true;
1661 }
1662 continue;
1663 }
1664 unsigned POpc = PN->getMachineOpcode();
1665 if (POpc == TargetOpcode::IMPLICIT_DEF)
1666 continue;
1667 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1668 EVT VT = PN->getOperand(0).getValueType();
1669 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1670 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1671 // Check if this increases register pressure of the specific register
1672 // class to the point where it would cause spills.
1673 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1674 return true;
1675 continue;
1676 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1677 POpc == TargetOpcode::SUBREG_TO_REG) {
1678 EVT VT = PN->getValueType(0);
1679 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1680 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1681 // Check if this increases register pressure of the specific register
1682 // class to the point where it would cause spills.
1683 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1684 return true;
1685 continue;
1686 }
1687 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1688 for (unsigned i = 0; i != NumDefs; ++i) {
1689 EVT VT = PN->getValueType(i);
1690 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1691 if (RegPressure[RCId] >= RegLimit[RCId])
1692 return true; // Reg pressure already high.
1693 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1694 if (!PN->hasAnyUseOfValue(i))
1695 continue;
1696 // Check if this increases register pressure of the specific register
1697 // class to the point where it would cause spills.
1698 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1699 return true;
1700 }
1701 }
1702
1703 return false;
1704}
1705
1706bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) {
1707 const SDNode *N = SU->getNode();
1708
1709 if (!N->isMachineOpcode() || !SU->NumSuccs)
1710 return false;
1711
1712 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1713 for (unsigned i = 0; i != NumDefs; ++i) {
1714 EVT VT = N->getValueType(i);
1715 if (!N->hasAnyUseOfValue(i))
1716 continue;
1717 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1718 if (RegPressure[RCId] >= RegLimit[RCId])
1719 return true;
1720 }
1721 return false;
1722}
1723
1724void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1725 if (!TracksRegPressure)
1726 return;
1727
1728 const SDNode *N = SU->getNode();
1729 if (!N->isMachineOpcode()) {
1730 if (N->getOpcode() != ISD::CopyToReg)
1731 return;
1732 } else {
1733 unsigned Opc = N->getMachineOpcode();
1734 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1735 Opc == TargetOpcode::INSERT_SUBREG ||
1736 Opc == TargetOpcode::SUBREG_TO_REG ||
1737 Opc == TargetOpcode::REG_SEQUENCE ||
1738 Opc == TargetOpcode::IMPLICIT_DEF)
1739 return;
1740 }
1741
1742 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1743 I != E; ++I) {
1744 if (I->isCtrl())
1745 continue;
1746 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001747 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1748 // counts data deps.
1749 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00001750 continue;
1751 const SDNode *PN = PredSU->getNode();
1752 if (!PN->isMachineOpcode()) {
1753 if (PN->getOpcode() == ISD::CopyFromReg) {
1754 EVT VT = PN->getValueType(0);
1755 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1756 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1757 }
1758 continue;
1759 }
1760 unsigned POpc = PN->getMachineOpcode();
1761 if (POpc == TargetOpcode::IMPLICIT_DEF)
1762 continue;
1763 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1764 EVT VT = PN->getOperand(0).getValueType();
1765 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1766 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1767 continue;
1768 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1769 POpc == TargetOpcode::SUBREG_TO_REG) {
1770 EVT VT = PN->getValueType(0);
1771 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1772 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1773 continue;
1774 }
1775 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1776 for (unsigned i = 0; i != NumDefs; ++i) {
1777 EVT VT = PN->getValueType(i);
1778 if (!PN->hasAnyUseOfValue(i))
1779 continue;
1780 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1781 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1782 }
1783 }
1784
1785 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1786 // may transfer data dependencies to CopyToReg.
1787 if (SU->NumSuccs && N->isMachineOpcode()) {
1788 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1789 for (unsigned i = 0; i != NumDefs; ++i) {
1790 EVT VT = N->getValueType(i);
1791 if (!N->hasAnyUseOfValue(i))
1792 continue;
1793 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1794 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1795 // Register pressure tracking is imprecise. This can happen.
1796 RegPressure[RCId] = 0;
1797 else
1798 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1799 }
1800 }
1801
1802 dumpRegPressure();
1803}
1804
1805void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1806 if (!TracksRegPressure)
1807 return;
1808
1809 const SDNode *N = SU->getNode();
1810 if (!N->isMachineOpcode()) {
1811 if (N->getOpcode() != ISD::CopyToReg)
1812 return;
1813 } else {
1814 unsigned Opc = N->getMachineOpcode();
1815 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1816 Opc == TargetOpcode::INSERT_SUBREG ||
1817 Opc == TargetOpcode::SUBREG_TO_REG ||
1818 Opc == TargetOpcode::REG_SEQUENCE ||
1819 Opc == TargetOpcode::IMPLICIT_DEF)
1820 return;
1821 }
1822
1823 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1824 I != E; ++I) {
1825 if (I->isCtrl())
1826 continue;
1827 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001828 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1829 // counts data deps.
1830 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00001831 continue;
1832 const SDNode *PN = PredSU->getNode();
1833 if (!PN->isMachineOpcode()) {
1834 if (PN->getOpcode() == ISD::CopyFromReg) {
1835 EVT VT = PN->getValueType(0);
1836 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1837 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1838 }
1839 continue;
1840 }
1841 unsigned POpc = PN->getMachineOpcode();
1842 if (POpc == TargetOpcode::IMPLICIT_DEF)
1843 continue;
1844 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1845 EVT VT = PN->getOperand(0).getValueType();
1846 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1847 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1848 continue;
1849 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1850 POpc == TargetOpcode::SUBREG_TO_REG) {
1851 EVT VT = PN->getValueType(0);
1852 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1853 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1854 continue;
1855 }
1856 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1857 for (unsigned i = 0; i != NumDefs; ++i) {
1858 EVT VT = PN->getValueType(i);
1859 if (!PN->hasAnyUseOfValue(i))
1860 continue;
1861 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1862 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1863 // Register pressure tracking is imprecise. This can happen.
1864 RegPressure[RCId] = 0;
1865 else
1866 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1867 }
1868 }
1869
1870 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1871 // may transfer data dependencies to CopyToReg.
1872 if (SU->NumSuccs && N->isMachineOpcode()) {
1873 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1874 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1875 EVT VT = N->getValueType(i);
1876 if (VT == MVT::Glue || VT == MVT::Other)
1877 continue;
1878 if (!N->hasAnyUseOfValue(i))
1879 continue;
1880 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1881 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1882 }
1883 }
1884
1885 dumpRegPressure();
1886}
1887
1888//===----------------------------------------------------------------------===//
1889// Dynamic Node Priority for Register Pressure Reduction
1890//===----------------------------------------------------------------------===//
1891
Evan Chengb9e3db62007-03-14 22:43:40 +00001892/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00001893/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001894static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001895 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00001896 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001897 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00001898 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001899 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00001900 // If there are bunch of CopyToRegs stacked up, they should be considered
1901 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00001902 if (I->getSUnit()->getNode() &&
1903 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001904 Height = closestSucc(I->getSUnit())+1;
1905 if (Height > MaxHeight)
1906 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00001907 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001908 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00001909}
1910
Evan Cheng61bc51e2007-12-20 02:22:36 +00001911/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00001912/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00001913static unsigned calcMaxScratches(const SUnit *SU) {
1914 unsigned Scratches = 0;
1915 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00001916 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001917 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00001918 Scratches++;
1919 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00001920 return Scratches;
1921}
1922
Evan Cheng6c1414f2010-10-29 18:09:28 +00001923/// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1924/// CopyToReg to a virtual register. This SU def is probably a liveout and
1925/// it has no other use. It should be scheduled closer to the terminator.
1926static bool hasOnlyLiveOutUses(const SUnit *SU) {
1927 bool RetVal = false;
1928 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1929 I != E; ++I) {
1930 if (I->isCtrl()) continue;
1931 const SUnit *SuccSU = I->getSUnit();
1932 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1933 unsigned Reg =
1934 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1935 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1936 RetVal = true;
1937 continue;
1938 }
1939 }
1940 return false;
1941 }
1942 return RetVal;
1943}
1944
1945/// UnitsSharePred - Return true if the two scheduling units share a common
1946/// data predecessor.
1947static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1948 SmallSet<const SUnit*, 4> Preds;
1949 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1950 I != E; ++I) {
1951 if (I->isCtrl()) continue; // ignore chain preds
1952 Preds.insert(I->getSUnit());
1953 }
1954 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1955 I != E; ++I) {
1956 if (I->isCtrl()) continue; // ignore chain preds
1957 if (Preds.count(I->getSUnit()))
1958 return true;
1959 }
1960 return false;
1961}
1962
Andrew Trick9ccce772011-01-14 21:11:41 +00001963// Check for either a dependence (latency) or resource (hazard) stall.
1964//
1965// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
1966static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
1967 if ((int)SPQ->getCurCycle() < Height) return true;
1968 if (SPQ->getHazardRec()->getHazardType(SU, 0)
1969 != ScheduleHazardRecognizer::NoHazard)
1970 return true;
1971 return false;
1972}
1973
1974// Return -1 if left has higher priority, 1 if right has higher priority.
1975// Return 0 if latency-based priority is equivalent.
1976static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
1977 RegReductionPQBase *SPQ) {
1978 // If the two nodes share an operand and one of them has a single
1979 // use that is a live out copy, favor the one that is live out. Otherwise
1980 // it will be difficult to eliminate the copy if the instruction is a
1981 // loop induction variable update. e.g.
1982 // BB:
1983 // sub r1, r3, #1
1984 // str r0, [r2, r3]
1985 // mov r3, r1
1986 // cmp
1987 // bne BB
1988 bool SharePred = UnitsSharePred(left, right);
1989 // FIXME: Only adjust if BB is a loop back edge.
1990 // FIXME: What's the cost of a copy?
1991 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1992 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1993 int LHeight = (int)left->getHeight() - LBonus;
1994 int RHeight = (int)right->getHeight() - RBonus;
1995
1996 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
1997 BUHasStall(left, LHeight, SPQ);
1998 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
1999 BUHasStall(right, RHeight, SPQ);
2000
2001 // If scheduling one of the node will cause a pipeline stall, delay it.
2002 // If scheduling either one of the node will cause a pipeline stall, sort
2003 // them according to their height.
2004 if (LStall) {
2005 if (!RStall)
2006 return 1;
2007 if (LHeight != RHeight)
2008 return LHeight > RHeight ? 1 : -1;
2009 } else if (RStall)
2010 return -1;
2011
Andrew Trick47ff14b2011-01-21 05:51:33 +00002012 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002013 // and latency.
2014 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2015 right->SchedulingPref == Sched::Latency)) {
Andrew Trick47ff14b2011-01-21 05:51:33 +00002016 if (DisableSchedCycles) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002017 if (LHeight != RHeight)
2018 return LHeight > RHeight ? 1 : -1;
2019 }
Andrew Trick47ff14b2011-01-21 05:51:33 +00002020 else {
2021 // If neither instruction stalls (!LStall && !RStall) then
2022 // it's height is already covered so only its depth matters. We also reach
2023 // this if both stall but have the same height.
2024 unsigned LDepth = left->getDepth();
2025 unsigned RDepth = right->getDepth();
2026 if (LDepth != RDepth) {
2027 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2028 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2029 << ") depth " << RDepth << "\n");
2030 return LDepth < RDepth ? 1 : -1;
2031 }
2032 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002033 if (left->Latency != right->Latency)
2034 return left->Latency > right->Latency ? 1 : -1;
2035 }
2036 return 0;
2037}
2038
2039static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Evan Cheng6730f032007-01-08 23:55:53 +00002040 unsigned LPriority = SPQ->getNodePriority(left);
2041 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng73bdf042008-03-01 00:39:47 +00002042 if (LPriority != RPriority)
2043 return LPriority > RPriority;
2044
2045 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2046 // e.g.
2047 // t1 = op t2, c1
2048 // t3 = op t4, c2
2049 //
2050 // and the following instructions are both ready.
2051 // t2 = op c3
2052 // t4 = op c4
2053 //
2054 // Then schedule t2 = op first.
2055 // i.e.
2056 // t4 = op c4
2057 // t2 = op c3
2058 // t1 = op t2, c1
2059 // t3 = op t4, c2
2060 //
2061 // This creates more short live intervals.
2062 unsigned LDist = closestSucc(left);
2063 unsigned RDist = closestSucc(right);
2064 if (LDist != RDist)
2065 return LDist < RDist;
2066
Evan Cheng3a14efa2009-02-12 08:59:45 +00002067 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002068 unsigned LScratch = calcMaxScratches(left);
2069 unsigned RScratch = calcMaxScratches(right);
2070 if (LScratch != RScratch)
2071 return LScratch > RScratch;
2072
Andrew Trick47ff14b2011-01-21 05:51:33 +00002073 if (!DisableSchedCycles) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002074 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2075 if (result != 0)
2076 return result > 0;
2077 }
2078 else {
2079 if (left->getHeight() != right->getHeight())
2080 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002081
Andrew Trick9ccce772011-01-14 21:11:41 +00002082 if (left->getDepth() != right->getDepth())
2083 return left->getDepth() < right->getDepth();
2084 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002085
Andrew Trick2085a962010-12-21 22:25:04 +00002086 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002087 "NodeQueueId cannot be zero");
2088 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002089}
2090
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002091// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002092bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002093 return BURRSort(left, right, SPQ);
2094}
2095
2096// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002097bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002098 unsigned LOrder = SPQ->getNodeOrdering(left);
2099 unsigned ROrder = SPQ->getNodeOrdering(right);
2100
2101 // Prefer an ordering where the lower the non-zero order number, the higher
2102 // the preference.
2103 if ((LOrder || ROrder) && LOrder != ROrder)
2104 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2105
2106 return BURRSort(left, right, SPQ);
2107}
2108
Andrew Trick9ccce772011-01-14 21:11:41 +00002109// If the time between now and when the instruction will be ready can cover
2110// the spill code, then avoid adding it to the ready queue. This gives long
2111// stalls highest priority and allows hoisting across calls. It should also
2112// speed up processing the available queue.
2113bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2114 static const unsigned ReadyDelay = 3;
2115
2116 if (SPQ->MayReduceRegPressure(SU)) return true;
2117
2118 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2119
2120 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2121 != ScheduleHazardRecognizer::NoHazard)
2122 return false;
2123
2124 return true;
2125}
2126
2127// Return true if right should be scheduled with higher priority than left.
2128bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002129 if (left->isCall || right->isCall)
2130 // No way to compute latency of calls.
2131 return BURRSort(left, right, SPQ);
2132
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002133 bool LHigh = SPQ->HighRegPressure(left);
2134 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002135 // Avoid causing spills. If register pressure is high, schedule for
2136 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002137 if (LHigh && !RHigh) {
2138 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2139 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002140 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002141 }
2142 else if (!LHigh && RHigh) {
2143 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2144 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002145 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002146 }
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002147 else if (!LHigh && !RHigh) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002148 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2149 if (result != 0)
2150 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002151 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002152 return BURRSort(left, right, SPQ);
2153}
2154
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002155// Schedule as many instructions in each cycle as possible. So don't make an
2156// instruction available unless it is ready in the current cycle.
2157bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002158 if (SU->getHeight() > CurCycle) return false;
2159
2160 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2161 != ScheduleHazardRecognizer::NoHazard)
2162 return false;
2163
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002164 return SU->getHeight() <= CurCycle;
2165}
2166
Andrew Trick9ccce772011-01-14 21:11:41 +00002167bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002168 if (left->isCall || right->isCall)
2169 // No way to compute latency of calls.
2170 return BURRSort(left, right, SPQ);
2171
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002172 bool LHigh = SPQ->HighRegPressure(left);
2173 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002174 // Avoid causing spills. If register pressure is high, schedule for
2175 // register pressure reduction.
2176 if (LHigh && !RHigh)
2177 return true;
2178 else if (!LHigh && RHigh)
2179 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002180 else if (!LHigh && !RHigh) {
Evan Cheng8ae3eca2010-07-25 18:59:43 +00002181 // Low register pressure situation, schedule to maximize instruction level
2182 // parallelism.
Evan Cheng37b740c2010-07-24 00:39:05 +00002183 if (left->NumPreds > right->NumPreds)
2184 return false;
2185 else if (left->NumPreds < right->NumPreds)
2186 return false;
2187 }
2188
2189 return BURRSort(left, right, SPQ);
2190}
2191
Andrew Trick9ccce772011-01-14 21:11:41 +00002192//===----------------------------------------------------------------------===//
2193// Preschedule for Register Pressure
2194//===----------------------------------------------------------------------===//
2195
2196bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002197 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002198 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002199 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002200 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002201 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002202 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002203 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002204 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002205 if (DU->getNodeId() != -1 &&
2206 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002207 return true;
2208 }
2209 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002210 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002211 return false;
2212}
2213
Evan Chengf9891412007-12-20 09:25:31 +00002214/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002215/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002216static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002217 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002218 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002219 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002220 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2221 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002222 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002223 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002224 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002225 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002226 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002227 const unsigned *SUImpDefs =
2228 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2229 if (!SUImpDefs)
2230 return false;
2231 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002232 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002233 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002234 continue;
2235 if (!N->hasAnyUseOfValue(i))
2236 continue;
2237 unsigned Reg = ImpDefs[i - NumDefs];
2238 for (;*SUImpDefs; ++SUImpDefs) {
2239 unsigned SUReg = *SUImpDefs;
2240 if (TRI->regsOverlap(Reg, SUReg))
2241 return true;
2242 }
Evan Chengf9891412007-12-20 09:25:31 +00002243 }
2244 }
2245 return false;
2246}
2247
Dan Gohman9a658d72009-03-24 00:49:12 +00002248/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2249/// are not handled well by the general register pressure reduction
2250/// heuristics. When presented with code like this:
2251///
2252/// N
2253/// / |
2254/// / |
2255/// U store
2256/// |
2257/// ...
2258///
2259/// the heuristics tend to push the store up, but since the
2260/// operand of the store has another use (U), this would increase
2261/// the length of that other use (the U->N edge).
2262///
2263/// This function transforms code like the above to route U's
2264/// dependence through the store when possible, like this:
2265///
2266/// N
2267/// ||
2268/// ||
2269/// store
2270/// |
2271/// U
2272/// |
2273/// ...
2274///
2275/// This results in the store being scheduled immediately
2276/// after N, which shortens the U->N live range, reducing
2277/// register pressure.
2278///
Andrew Trick9ccce772011-01-14 21:11:41 +00002279void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002280 // Visit all the nodes in topological order, working top-down.
2281 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2282 SUnit *SU = &(*SUnits)[i];
2283 // For now, only look at nodes with no data successors, such as stores.
2284 // These are especially important, due to the heuristics in
2285 // getNodePriority for nodes with no data successors.
2286 if (SU->NumSuccs != 0)
2287 continue;
2288 // For now, only look at nodes with exactly one data predecessor.
2289 if (SU->NumPreds != 1)
2290 continue;
2291 // Avoid prescheduling copies to virtual registers, which don't behave
2292 // like other nodes from the perspective of scheduling heuristics.
2293 if (SDNode *N = SU->getNode())
2294 if (N->getOpcode() == ISD::CopyToReg &&
2295 TargetRegisterInfo::isVirtualRegister
2296 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2297 continue;
2298
2299 // Locate the single data predecessor.
2300 SUnit *PredSU = 0;
2301 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2302 EE = SU->Preds.end(); II != EE; ++II)
2303 if (!II->isCtrl()) {
2304 PredSU = II->getSUnit();
2305 break;
2306 }
2307 assert(PredSU);
2308
2309 // Don't rewrite edges that carry physregs, because that requires additional
2310 // support infrastructure.
2311 if (PredSU->hasPhysRegDefs)
2312 continue;
2313 // Short-circuit the case where SU is PredSU's only data successor.
2314 if (PredSU->NumSuccs == 1)
2315 continue;
2316 // Avoid prescheduling to copies from virtual registers, which don't behave
2317 // like other nodes from the perspective of scheduling // heuristics.
2318 if (SDNode *N = SU->getNode())
2319 if (N->getOpcode() == ISD::CopyFromReg &&
2320 TargetRegisterInfo::isVirtualRegister
2321 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2322 continue;
2323
2324 // Perform checks on the successors of PredSU.
2325 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2326 EE = PredSU->Succs.end(); II != EE; ++II) {
2327 SUnit *PredSuccSU = II->getSUnit();
2328 if (PredSuccSU == SU) continue;
2329 // If PredSU has another successor with no data successors, for
2330 // now don't attempt to choose either over the other.
2331 if (PredSuccSU->NumSuccs == 0)
2332 goto outer_loop_continue;
2333 // Don't break physical register dependencies.
2334 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2335 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2336 goto outer_loop_continue;
2337 // Don't introduce graph cycles.
2338 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2339 goto outer_loop_continue;
2340 }
2341
2342 // Ok, the transformation is safe and the heuristics suggest it is
2343 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002344 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2345 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002346 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002347 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2348 SDep Edge = PredSU->Succs[i];
2349 assert(!Edge.isAssignedRegDep());
2350 SUnit *SuccSU = Edge.getSUnit();
2351 if (SuccSU != SU) {
2352 Edge.setSUnit(PredSU);
2353 scheduleDAG->RemovePred(SuccSU, Edge);
2354 scheduleDAG->AddPred(SU, Edge);
2355 Edge.setSUnit(SU);
2356 scheduleDAG->AddPred(SuccSU, Edge);
2357 --i;
2358 }
2359 }
2360 outer_loop_continue:;
2361 }
2362}
2363
Evan Chengd38c22b2006-05-11 23:55:42 +00002364/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2365/// it as a def&use operand. Add a pseudo control edge from it to the other
2366/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002367/// first (lower in the schedule). If both nodes are two-address, favor the
2368/// one that has a CopyToReg use (more likely to be a loop induction update).
2369/// If both are two-address, but one is commutable while the other is not
2370/// commutable, favor the one that's not commutable.
Andrew Trick9ccce772011-01-14 21:11:41 +00002371void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002372 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002373 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002374 if (!SU->isTwoAddress)
2375 continue;
2376
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002377 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002378 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002379 continue;
2380
Evan Cheng6c1414f2010-10-29 18:09:28 +00002381 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002382 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002383 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002384 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002385 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002386 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002387 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2388 continue;
2389 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2390 if (DU->getNodeId() == -1)
2391 continue;
2392 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2393 if (!DUSU) continue;
2394 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2395 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002396 if (I->isCtrl()) continue;
2397 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002398 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002399 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002400 // Be conservative. Ignore if nodes aren't at roughly the same
2401 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002402 if (SuccSU->getHeight() < SU->getHeight() &&
2403 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002404 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002405 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2406 // constrains whatever is using the copy, instead of the copy
2407 // itself. In the case that the copy is coalesced, this
2408 // preserves the intent of the pseudo two-address heurietics.
2409 while (SuccSU->Succs.size() == 1 &&
2410 SuccSU->getNode()->isMachineOpcode() &&
2411 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002412 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002413 SuccSU = SuccSU->Succs.front().getSUnit();
2414 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002415 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2416 continue;
2417 // Don't constrain nodes with physical register defs if the
2418 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002419 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002420 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002421 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002422 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002423 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2424 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002425 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002426 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2427 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2428 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002429 continue;
2430 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002431 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002432 (!SU->isCommutable && SuccSU->isCommutable)) &&
2433 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002434 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002435 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002436 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002437 /*Reg=*/0, /*isNormalMemory=*/false,
2438 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002439 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002440 }
2441 }
2442 }
2443 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002444}
2445
Roman Levenstein30d09512008-03-27 09:44:37 +00002446/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002447/// predecessors of the successors of the SUnit SU. Stop when the provided
2448/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002449static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002450 unsigned Limit) {
2451 unsigned Sum = 0;
2452 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2453 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002454 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002455 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2456 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002457 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002458 if (!PredSU->isScheduled)
2459 if (++Sum > Limit)
2460 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002461 }
2462 }
2463 return Sum;
2464}
2465
Evan Chengd38c22b2006-05-11 23:55:42 +00002466
2467// Top down
2468bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00002469 unsigned LPriority = SPQ->getNodePriority(left);
2470 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002471 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2472 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002473 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2474 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002475 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2476 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002477
2478 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2479 return false;
2480 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2481 return true;
2482
Evan Chengd38c22b2006-05-11 23:55:42 +00002483 if (LIsFloater)
2484 LBonus -= 2;
2485 if (RIsFloater)
2486 RBonus -= 2;
2487 if (left->NumSuccs == 1)
2488 LBonus += 2;
2489 if (right->NumSuccs == 1)
2490 RBonus += 2;
2491
Evan Cheng73bdf042008-03-01 00:39:47 +00002492 if (LPriority+LBonus != RPriority+RBonus)
2493 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002494
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002495 if (left->getDepth() != right->getDepth())
2496 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002497
2498 if (left->NumSuccsLeft != right->NumSuccsLeft)
2499 return left->NumSuccsLeft > right->NumSuccsLeft;
2500
Andrew Trick2085a962010-12-21 22:25:04 +00002501 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002502 "NodeQueueId cannot be zero");
2503 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002504}
2505
Evan Chengd38c22b2006-05-11 23:55:42 +00002506//===----------------------------------------------------------------------===//
2507// Public Constructor Functions
2508//===----------------------------------------------------------------------===//
2509
Dan Gohmandfaf6462009-02-11 04:27:20 +00002510llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002511llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2512 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002513 const TargetMachine &TM = IS->TM;
2514 const TargetInstrInfo *TII = TM.getInstrInfo();
2515 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002516
Evan Chenga77f3d32010-07-21 06:09:07 +00002517 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002518 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002519 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002520 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002521 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002522}
2523
Dan Gohmandfaf6462009-02-11 04:27:20 +00002524llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002525llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2526 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002527 const TargetMachine &TM = IS->TM;
2528 const TargetInstrInfo *TII = TM.getInstrInfo();
2529 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002530
Evan Chenga77f3d32010-07-21 06:09:07 +00002531 TDRegReductionPriorityQueue *PQ =
2532 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002533 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002534 PQ->setScheduleDAG(SD);
2535 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002536}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002537
2538llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002539llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2540 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002541 const TargetMachine &TM = IS->TM;
2542 const TargetInstrInfo *TII = TM.getInstrInfo();
2543 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002544
Evan Chenga77f3d32010-07-21 06:09:07 +00002545 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002546 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002547 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002548 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002549 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002550}
2551
2552llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002553llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2554 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002555 const TargetMachine &TM = IS->TM;
2556 const TargetInstrInfo *TII = TM.getInstrInfo();
2557 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002558 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002559
Evan Chenga77f3d32010-07-21 06:09:07 +00002560 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002561 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002562
2563 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002564 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002565 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002566}
Evan Cheng37b740c2010-07-24 00:39:05 +00002567
2568llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002569llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2570 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002571 const TargetMachine &TM = IS->TM;
2572 const TargetInstrInfo *TII = TM.getInstrInfo();
2573 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2574 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002575
Evan Cheng37b740c2010-07-24 00:39:05 +00002576 ILPBURRPriorityQueue *PQ =
2577 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002578 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002579 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002580 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002581}