blob: 98931289ce25693447fdf94f8d0d4f0a020c395f [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
Bill Wendling8cbc25d2010-01-23 10:26:57 +000048 sourceListDAGScheduler("source",
49 "Similar to list-burr but schedules in source "
50 "order when possible",
51 createSourceListDAGScheduler);
Jim Laskey95eda5b2006-08-01 14:21:23 +000052
Evan Chengbdd062d2010-05-20 06:13:19 +000053static RegisterScheduler
Evan Cheng725211e2010-05-21 00:42:32 +000054 hybridListDAGScheduler("list-hybrid",
Evan Cheng37b740c2010-07-24 00:39:05 +000055 "Bottom-up register pressure aware list scheduling "
56 "which tries to balance latency and register pressure",
Evan Chengbdd062d2010-05-20 06:13:19 +000057 createHybridListDAGScheduler);
58
Evan Cheng37b740c2010-07-24 00:39:05 +000059static RegisterScheduler
60 ILPListDAGScheduler("list-ilp",
61 "Bottom-up register pressure aware list scheduling "
62 "which tries to balance ILP and register pressure",
63 createILPListDAGScheduler);
64
Andrew Trick47ff14b2011-01-21 05:51:33 +000065static cl::opt<bool> DisableSchedCycles(
Andrew Trickbd428ec2011-01-21 06:19:05 +000066 "disable-sched-cycles", cl::Hidden, cl::init(false),
Andrew Trick47ff14b2011-01-21 05:51:33 +000067 cl::desc("Disable cycle-level precision during preRA scheduling"));
Andrew Trick10ffc2b2010-12-24 05:03:26 +000068
Andrew Trick641e2d42011-03-05 08:00:22 +000069// Temporary sched=list-ilp flags until the heuristics are robust.
Andrew Trickbfbd9722011-04-14 05:15:06 +000070// Some options are also available under sched=list-hybrid.
Andrew Trick641e2d42011-03-05 08:00:22 +000071static cl::opt<bool> DisableSchedRegPressure(
72 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
73 cl::desc("Disable regpressure priority in sched=list-ilp"));
74static cl::opt<bool> DisableSchedLiveUses(
Andrew Trickdd017322011-03-06 00:03:32 +000075 "disable-sched-live-uses", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000076 cl::desc("Disable live use priority in sched=list-ilp"));
Andrew Trick2ad0b372011-04-07 19:54:57 +000077static cl::opt<bool> DisableSchedVRegCycle(
78 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
79 cl::desc("Disable virtual register cycle interference checks"));
Andrew Trickbfbd9722011-04-14 05:15:06 +000080static cl::opt<bool> DisableSchedPhysRegJoin(
81 "disable-sched-physreg-join", cl::Hidden, cl::init(false),
82 cl::desc("Disable physreg def-use affinity"));
Andrew Trick641e2d42011-03-05 08:00:22 +000083static cl::opt<bool> DisableSchedStalls(
Andrew Trickdd017322011-03-06 00:03:32 +000084 "disable-sched-stalls", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000085 cl::desc("Disable no-stall priority in sched=list-ilp"));
86static cl::opt<bool> DisableSchedCriticalPath(
87 "disable-sched-critical-path", cl::Hidden, cl::init(false),
88 cl::desc("Disable critical path priority in sched=list-ilp"));
89static cl::opt<bool> DisableSchedHeight(
90 "disable-sched-height", cl::Hidden, cl::init(false),
91 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
Evan Chengd33b2d62011-11-10 07:43:16 +000092static cl::opt<bool> Disable2AddrHack(
93 "disable-2addr-hack", cl::Hidden, cl::init(true),
94 cl::desc("Disable scheduler's two-address hack"));
Andrew Trick641e2d42011-03-05 08:00:22 +000095
96static cl::opt<int> MaxReorderWindow(
97 "max-sched-reorder", cl::Hidden, cl::init(6),
98 cl::desc("Number of instructions to allow ahead of the critical path "
99 "in sched=list-ilp"));
100
101static cl::opt<unsigned> AvgIPC(
102 "sched-avg-ipc", cl::Hidden, cl::init(1),
103 cl::desc("Average inst/cycle whan no target itinerary exists."));
104
Evan Chengd38c22b2006-05-11 23:55:42 +0000105namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +0000106//===----------------------------------------------------------------------===//
107/// ScheduleDAGRRList - The actual register reduction list scheduler
108/// implementation. This supports both top-down and bottom-up scheduling.
109///
Nick Lewycky02d5f772009-10-25 06:33:48 +0000110class ScheduleDAGRRList : public ScheduleDAGSDNodes {
Evan Chengd38c22b2006-05-11 23:55:42 +0000111private:
Evan Chengbdd062d2010-05-20 06:13:19 +0000112 /// NeedLatency - True if the scheduler will make use of latency information.
113 ///
114 bool NeedLatency;
115
Evan Chengd38c22b2006-05-11 23:55:42 +0000116 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +0000117 SchedulingPriorityQueue *AvailableQueue;
118
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000119 /// PendingQueue - This contains all of the instructions whose operands have
120 /// been issued, but their results are not ready yet (due to the latency of
121 /// the operation). Once the operands becomes available, the instruction is
122 /// added to the AvailableQueue.
123 std::vector<SUnit*> PendingQueue;
124
125 /// HazardRec - The hazard recognizer to use.
126 ScheduleHazardRecognizer *HazardRec;
127
Andrew Trick528fad92010-12-23 05:42:20 +0000128 /// CurCycle - The current scheduler state corresponds to this cycle.
129 unsigned CurCycle;
130
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000131 /// MinAvailableCycle - Cycle of the soonest available instruction.
132 unsigned MinAvailableCycle;
133
Andrew Trick641e2d42011-03-05 08:00:22 +0000134 /// IssueCount - Count instructions issued in this cycle
135 /// Currently valid only for bottom-up scheduling.
136 unsigned IssueCount;
137
Dan Gohmanc07f6862008-09-23 18:50:48 +0000138 /// LiveRegDefs - A set of physical registers and their definition
Evan Cheng5924bf72007-09-25 01:54:36 +0000139 /// that are "live". These nodes must be scheduled before any other nodes that
140 /// modifies the registers can be scheduled.
Dan Gohmanc07f6862008-09-23 18:50:48 +0000141 unsigned NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000142 std::vector<SUnit*> LiveRegDefs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000143 std::vector<SUnit*> LiveRegGens;
Evan Cheng5924bf72007-09-25 01:54:36 +0000144
Dan Gohmanad2134d2008-11-25 00:52:40 +0000145 /// Topo - A topological ordering for SUnits which permits fast IsReachable
146 /// and similar queries.
147 ScheduleDAGTopologicalSort Topo;
148
Evan Chengd38c22b2006-05-11 23:55:42 +0000149public:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000150 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
151 SchedulingPriorityQueue *availqueue,
152 CodeGenOpt::Level OptLevel)
Dan Gohman90fb5522011-10-20 21:44:34 +0000153 : ScheduleDAGSDNodes(mf),
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000154 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
155 Topo(SUnits) {
156
157 const TargetMachine &tm = mf.getTarget();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000158 if (DisableSchedCycles || !NeedLatency)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000159 HazardRec = new ScheduleHazardRecognizer();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000160 else
161 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000162 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000163
164 ~ScheduleDAGRRList() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000165 delete HazardRec;
Evan Chengd38c22b2006-05-11 23:55:42 +0000166 delete AvailableQueue;
167 }
168
169 void Schedule();
170
Andrew Trick9ccce772011-01-14 21:11:41 +0000171 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
172
Roman Levenstein733a4d62008-03-26 11:23:38 +0000173 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000174 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
175 return Topo.IsReachable(SU, TargetSU);
176 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000177
Dan Gohman60d68442009-01-29 19:49:27 +0000178 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000179 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000180 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
181 return Topo.WillCreateCycle(SU, TargetSU);
182 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000183
Dan Gohman2d170892008-12-09 22:54:47 +0000184 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000185 /// This returns true if this is a new predecessor.
186 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000187 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000188 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000189 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000190 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000191
Dan Gohman2d170892008-12-09 22:54:47 +0000192 /// RemovePred - removes a predecessor edge from SUnit SU.
193 /// This returns true if an edge was removed.
194 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000195 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000196 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000197 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000198 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000199
Evan Chengd38c22b2006-05-11 23:55:42 +0000200private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000201 bool isReady(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000202 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000203 AvailableQueue->isReady(SU);
204 }
205
Dan Gohman60d68442009-01-29 19:49:27 +0000206 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000207 void ReleasePredecessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000208 void ReleasePending();
209 void AdvanceToCycle(unsigned NextCycle);
210 void AdvancePastStalls(SUnit *SU);
211 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000212 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000213 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000214 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000215 void RestoreHazardCheckerBottomUp();
216 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000217 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000218 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
219 const TargetRegisterClass*,
220 const TargetRegisterClass*,
221 SmallVector<SUnit*, 2>&);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000222 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000223
Andrew Trick528fad92010-12-23 05:42:20 +0000224 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000225 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000226
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000227 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000228 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000229 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000230 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000231 SUnit *NewNode = NewSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000232 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000233 if (NewNode->NodeNum >= NumSUnits)
234 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000235 return NewNode;
236 }
237
Roman Levenstein733a4d62008-03-26 11:23:38 +0000238 /// CreateClone - Creates a new SUnit from an existing one.
239 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000240 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000241 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000242 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000243 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000244 if (NewNode->NodeNum >= NumSUnits)
245 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000246 return NewNode;
247 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000248
Evan Chengbdd062d2010-05-20 06:13:19 +0000249 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
250 /// need actual latency information but the hybrid scheduler does.
251 bool ForceUnitLatencies() const {
252 return !NeedLatency;
253 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000254};
255} // end anonymous namespace
256
Owen Anderson96adc4a2011-06-15 23:35:18 +0000257/// GetCostForDef - Looks up the register class and cost for a given definition.
258/// Typically this just means looking up the representative register class,
Owen Andersonca2f78a2011-11-16 01:02:57 +0000259/// but for untyped values (MVT::Untyped) it means inspecting the node's
Owen Anderson96adc4a2011-06-15 23:35:18 +0000260/// opcode to determine what register class is being generated.
261static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
262 const TargetLowering *TLI,
263 const TargetInstrInfo *TII,
264 const TargetRegisterInfo *TRI,
265 unsigned &RegClass, unsigned &Cost) {
266 EVT VT = RegDefPos.GetValue();
267
268 // Special handling for untyped values. These values can only come from
269 // the expansion of custom DAG-to-DAG patterns.
Owen Andersonca2f78a2011-11-16 01:02:57 +0000270 if (VT == MVT::Untyped) {
Owen Andersond1955e72011-06-21 22:54:23 +0000271 const SDNode *Node = RegDefPos.GetNode();
272 unsigned Opcode = Node->getMachineOpcode();
273
274 if (Opcode == TargetOpcode::REG_SEQUENCE) {
275 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
276 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
277 RegClass = RC->getID();
278 Cost = 1;
279 return;
280 }
281
Owen Anderson96adc4a2011-06-15 23:35:18 +0000282 unsigned Idx = RegDefPos.GetIdx();
Evan Cheng6cc775f2011-06-28 19:10:37 +0000283 const MCInstrDesc Desc = TII->get(Opcode);
Evan Cheng8d71a752011-06-27 21:26:13 +0000284 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI);
Owen Anderson96adc4a2011-06-15 23:35:18 +0000285 RegClass = RC->getID();
286 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
287 // better way to determine it.
288 Cost = 1;
289 } else {
290 RegClass = TLI->getRepRegClassFor(VT)->getID();
291 Cost = TLI->getRepRegClassCostFor(VT);
292 }
293}
Evan Chengd38c22b2006-05-11 23:55:42 +0000294
295/// Schedule - Schedule the DAG using list scheduling.
296void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000297 DEBUG(dbgs()
298 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000299 << " '" << BB->getName() << "' **********\n");
Evan Cheng5924bf72007-09-25 01:54:36 +0000300
Andrew Trick528fad92010-12-23 05:42:20 +0000301 CurCycle = 0;
Andrew Trick641e2d42011-03-05 08:00:22 +0000302 IssueCount = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000303 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000304 NumLiveRegs = 0;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000305 // Allocate slots for each physical register, plus one for a special register
306 // to track the virtual resource of a calling sequence.
307 LiveRegDefs.resize(TRI->getNumRegs() + 1, NULL);
308 LiveRegGens.resize(TRI->getNumRegs() + 1, NULL);
Evan Cheng5924bf72007-09-25 01:54:36 +0000309
Dan Gohman04543e72008-12-23 18:36:58 +0000310 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000311 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000312
Evan Chengd38c22b2006-05-11 23:55:42 +0000313 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000314 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000315 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000316
Dan Gohman46520a22008-06-21 19:18:17 +0000317 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000318
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000319 HazardRec->Reset();
320
Dan Gohman90fb5522011-10-20 21:44:34 +0000321 // Execute the actual scheduling loop.
322 ListScheduleBottomUp();
Andrew Trick2085a962010-12-21 22:25:04 +0000323
Evan Chengd38c22b2006-05-11 23:55:42 +0000324 AvailableQueue->releaseState();
Evan Chengafed73e2006-05-12 01:58:24 +0000325}
Evan Chengd38c22b2006-05-11 23:55:42 +0000326
327//===----------------------------------------------------------------------===//
328// Bottom-Up Scheduling
329//===----------------------------------------------------------------------===//
330
Evan Chengd38c22b2006-05-11 23:55:42 +0000331/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000332/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000333void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000334 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000335
Evan Chengd38c22b2006-05-11 23:55:42 +0000336#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000337 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000338 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000339 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000340 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000341 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000342 }
343#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000344 --PredSU->NumSuccsLeft;
345
Evan Chengbdd062d2010-05-20 06:13:19 +0000346 if (!ForceUnitLatencies()) {
347 // Updating predecessor's height. This is now the cycle when the
348 // predecessor can be scheduled without causing a pipeline stall.
349 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
350 }
351
Dan Gohmanb9543432009-02-10 23:27:53 +0000352 // If all the node's successors are scheduled, this node is ready
353 // to be scheduled. Ignore the special EntrySU node.
354 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000355 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000356
357 unsigned Height = PredSU->getHeight();
358 if (Height < MinAvailableCycle)
359 MinAvailableCycle = Height;
360
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000361 if (isReady(PredSU)) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000362 AvailableQueue->push(PredSU);
363 }
364 // CapturePred and others may have left the node in the pending queue, avoid
365 // adding it twice.
366 else if (!PredSU->isPending) {
367 PredSU->isPending = true;
368 PendingQueue.push_back(PredSU);
369 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000370 }
371}
372
Dan Gohman198b7ff2011-11-03 21:49:52 +0000373/// IsChainDependent - Test if Outer is reachable from Inner through
374/// chain dependencies.
375static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
376 unsigned NestLevel,
377 const TargetInstrInfo *TII) {
378 SDNode *N = Outer;
379 for (;;) {
380 if (N == Inner)
381 return true;
382 // For a TokenFactor, examine each operand. There may be multiple ways
383 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
384 // most nesting in order to ensure that we find the corresponding match.
385 if (N->getOpcode() == ISD::TokenFactor) {
386 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
387 if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel, TII))
388 return true;
389 return false;
390 }
391 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
392 if (N->isMachineOpcode()) {
393 if (N->getMachineOpcode() ==
394 (unsigned)TII->getCallFrameDestroyOpcode()) {
395 ++NestLevel;
396 } else if (N->getMachineOpcode() ==
397 (unsigned)TII->getCallFrameSetupOpcode()) {
398 if (NestLevel == 0)
399 return false;
400 --NestLevel;
401 }
402 }
403 // Otherwise, find the chain and continue climbing.
404 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
405 if (N->getOperand(i).getValueType() == MVT::Other) {
406 N = N->getOperand(i).getNode();
407 goto found_chain_operand;
408 }
409 return false;
410 found_chain_operand:;
411 if (N->getOpcode() == ISD::EntryToken)
412 return false;
413 }
414}
415
416/// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
417/// the corresponding (lowered) CALLSEQ_BEGIN node.
418///
419/// NestLevel and MaxNested are used in recursion to indcate the current level
420/// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
421/// level seen so far.
422///
423/// TODO: It would be better to give CALLSEQ_END an explicit operand to point
424/// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
425static SDNode *
426FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
427 const TargetInstrInfo *TII) {
428 for (;;) {
429 // For a TokenFactor, examine each operand. There may be multiple ways
430 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
431 // most nesting in order to ensure that we find the corresponding match.
432 if (N->getOpcode() == ISD::TokenFactor) {
433 SDNode *Best = 0;
434 unsigned BestMaxNest = MaxNest;
435 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
436 unsigned MyNestLevel = NestLevel;
437 unsigned MyMaxNest = MaxNest;
438 if (SDNode *New = FindCallSeqStart(N->getOperand(i).getNode(),
439 MyNestLevel, MyMaxNest, TII))
440 if (!Best || (MyMaxNest > BestMaxNest)) {
441 Best = New;
442 BestMaxNest = MyMaxNest;
443 }
444 }
445 assert(Best);
446 MaxNest = BestMaxNest;
447 return Best;
448 }
449 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
450 if (N->isMachineOpcode()) {
451 if (N->getMachineOpcode() ==
452 (unsigned)TII->getCallFrameDestroyOpcode()) {
453 ++NestLevel;
454 MaxNest = std::max(MaxNest, NestLevel);
455 } else if (N->getMachineOpcode() ==
456 (unsigned)TII->getCallFrameSetupOpcode()) {
457 assert(NestLevel != 0);
458 --NestLevel;
459 if (NestLevel == 0)
460 return N;
461 }
462 }
463 // Otherwise, find the chain and continue climbing.
464 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
465 if (N->getOperand(i).getValueType() == MVT::Other) {
466 N = N->getOperand(i).getNode();
467 goto found_chain_operand;
468 }
469 return 0;
470 found_chain_operand:;
471 if (N->getOpcode() == ISD::EntryToken)
472 return 0;
473 }
474}
475
Andrew Trick033efdf2010-12-23 03:15:51 +0000476/// Call ReleasePred for each predecessor, then update register live def/gen.
477/// Always update LiveRegDefs for a register dependence even if the current SU
478/// also defines the register. This effectively create one large live range
479/// across a sequence of two-address node. This is important because the
480/// entire chain must be scheduled together. Example:
481///
482/// flags = (3) add
483/// flags = (2) addc flags
484/// flags = (1) addc flags
485///
486/// results in
487///
488/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000489/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000490///
491/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
492/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000493void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000494 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000495 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000496 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000497 ReleasePred(SU, &*I);
498 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000499 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000500 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000501 // clobber the register is scheduled between the predecessor and
502 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000503 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000504 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
505 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000506 LiveRegDefs[I->getReg()] = I->getSUnit();
507 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000508 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000509 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000510 }
511 }
512 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000513
514 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
515 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
516 // these nodes, to prevent other calls from being interscheduled with them.
517 unsigned CallResource = TRI->getNumRegs();
518 if (!LiveRegDefs[CallResource])
519 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
520 if (Node->isMachineOpcode() &&
521 Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
522 unsigned NestLevel = 0;
523 unsigned MaxNest = 0;
524 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
525
526 SUnit *Def = &SUnits[N->getNodeId()];
527 ++NumLiveRegs;
528 LiveRegDefs[CallResource] = Def;
529 LiveRegGens[CallResource] = SU;
530 break;
531 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000532}
533
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000534/// Check to see if any of the pending instructions are ready to issue. If
535/// so, add them to the available queue.
536void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000537 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000538 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
539 return;
540 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000541
542 // If the available queue is empty, it is safe to reset MinAvailableCycle.
543 if (AvailableQueue->empty())
544 MinAvailableCycle = UINT_MAX;
545
546 // Check to see if any of the pending instructions are ready to issue. If
547 // so, add them to the available queue.
548 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000549 unsigned ReadyCycle = PendingQueue[i]->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000550 if (ReadyCycle < MinAvailableCycle)
551 MinAvailableCycle = ReadyCycle;
552
553 if (PendingQueue[i]->isAvailable) {
554 if (!isReady(PendingQueue[i]))
555 continue;
556 AvailableQueue->push(PendingQueue[i]);
557 }
558 PendingQueue[i]->isPending = false;
559 PendingQueue[i] = PendingQueue.back();
560 PendingQueue.pop_back();
561 --i; --e;
562 }
563}
564
565/// Move the scheduler state forward by the specified number of Cycles.
566void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
567 if (NextCycle <= CurCycle)
568 return;
569
Andrew Trick641e2d42011-03-05 08:00:22 +0000570 IssueCount = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000571 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000572 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000573 // Bypass lots of virtual calls in case of long latency.
574 CurCycle = NextCycle;
575 }
576 else {
577 for (; CurCycle != NextCycle; ++CurCycle) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000578 HazardRec->RecedeCycle();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000579 }
580 }
581 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
582 // available Q to release pending nodes at least once before popping.
583 ReleasePending();
584}
585
586/// Move the scheduler state forward until the specified node's dependents are
587/// ready and can be scheduled with no resource conflicts.
588void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000589 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000590 return;
591
Andrew Trickb53a00d2011-04-13 00:38:32 +0000592 // FIXME: Nodes such as CopyFromReg probably should not advance the current
593 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
594 // has predecessors the cycle will be advanced when they are scheduled.
595 // But given the crude nature of modeling latency though such nodes, we
596 // currently need to treat these nodes like real instructions.
597 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
598
Dan Gohman90fb5522011-10-20 21:44:34 +0000599 unsigned ReadyCycle = SU->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000600
601 // Bump CurCycle to account for latency. We assume the latency of other
602 // available instructions may be hidden by the stall (not a full pipe stall).
603 // This updates the hazard recognizer's cycle before reserving resources for
604 // this instruction.
605 AdvanceToCycle(ReadyCycle);
606
607 // Calls are scheduled in their preceding cycle, so don't conflict with
608 // hazards from instructions after the call. EmitNode will reset the
609 // scoreboard state before emitting the call.
Dan Gohman90fb5522011-10-20 21:44:34 +0000610 if (SU->isCall)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000611 return;
612
613 // FIXME: For resource conflicts in very long non-pipelined stages, we
614 // should probably skip ahead here to avoid useless scoreboard checks.
615 int Stalls = 0;
616 while (true) {
617 ScheduleHazardRecognizer::HazardType HT =
Dan Gohman90fb5522011-10-20 21:44:34 +0000618 HazardRec->getHazardType(SU, -Stalls);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000619
620 if (HT == ScheduleHazardRecognizer::NoHazard)
621 break;
622
623 ++Stalls;
624 }
625 AdvanceToCycle(CurCycle + Stalls);
626}
627
628/// Record this SUnit in the HazardRecognizer.
629/// Does not update CurCycle.
630void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000631 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000632 return;
633
634 // Check for phys reg copy.
635 if (!SU->getNode())
636 return;
637
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000638 switch (SU->getNode()->getOpcode()) {
639 default:
640 assert(SU->getNode()->isMachineOpcode() &&
641 "This target-independent node should not be scheduled.");
642 break;
643 case ISD::MERGE_VALUES:
644 case ISD::TokenFactor:
645 case ISD::CopyToReg:
646 case ISD::CopyFromReg:
647 case ISD::EH_LABEL:
648 // Noops don't affect the scoreboard state. Copies are likely to be
649 // removed.
650 return;
651 case ISD::INLINEASM:
652 // For inline asm, clear the pipeline state.
653 HazardRec->Reset();
654 return;
655 }
Dan Gohman90fb5522011-10-20 21:44:34 +0000656 if (SU->isCall) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000657 // Calls are scheduled with their preceding instructions. For bottom-up
658 // scheduling, clear the pipeline state before emitting.
659 HazardRec->Reset();
660 }
661
662 HazardRec->EmitInstruction(SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000663}
664
Andrew Trickb53a00d2011-04-13 00:38:32 +0000665static void resetVRegCycle(SUnit *SU);
666
Dan Gohmanb9543432009-02-10 23:27:53 +0000667/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
668/// count of its predecessors. If a predecessor pending count is zero, add it to
669/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000670void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Andrew Trick1b60ad62011-04-12 20:14:07 +0000671 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000672 DEBUG(SU->dump(this));
673
Evan Chengbdd062d2010-05-20 06:13:19 +0000674#ifndef NDEBUG
675 if (CurCycle < SU->getHeight())
Andrew Trickb53a00d2011-04-13 00:38:32 +0000676 DEBUG(dbgs() << " Height [" << SU->getHeight()
677 << "] pipeline stall!\n");
Evan Chengbdd062d2010-05-20 06:13:19 +0000678#endif
679
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000680 // FIXME: Do not modify node height. It may interfere with
681 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
Eric Christopher1b4b1e52011-03-21 18:06:21 +0000682 // node its ready cycle can aid heuristics, and after scheduling it can
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000683 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000684 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000685
686 // Reserve resources for the scheduled intruction.
687 EmitNode(SU);
688
Dan Gohmanb9543432009-02-10 23:27:53 +0000689 Sequence.push_back(SU);
690
Evan Cheng28590382010-07-21 23:53:58 +0000691 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000692
Andrew Trick641e2d42011-03-05 08:00:22 +0000693 // If HazardRec is disabled, and each inst counts as one cycle, then
Andrew Trickb53a00d2011-04-13 00:38:32 +0000694 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000695 // PendingQueue for schedulers that implement HasReadyFilter.
Andrew Trick641e2d42011-03-05 08:00:22 +0000696 if (!HazardRec->isEnabled() && AvgIPC < 2)
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000697 AdvanceToCycle(CurCycle + 1);
698
Andrew Trick033efdf2010-12-23 03:15:51 +0000699 // Update liveness of predecessors before successors to avoid treating a
700 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000701 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000702
703 // Release all the implicit physical register defs that are live.
704 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
705 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000706 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
707 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
708 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
709 --NumLiveRegs;
710 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000711 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000712 }
713 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000714 // Release the special call resource dependence, if this is the beginning
715 // of a call.
716 unsigned CallResource = TRI->getNumRegs();
717 if (LiveRegDefs[CallResource] == SU)
718 for (const SDNode *SUNode = SU->getNode(); SUNode;
719 SUNode = SUNode->getGluedNode()) {
720 if (SUNode->isMachineOpcode() &&
721 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
722 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
723 --NumLiveRegs;
724 LiveRegDefs[CallResource] = NULL;
725 LiveRegGens[CallResource] = NULL;
726 }
727 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000728
Andrew Trickb53a00d2011-04-13 00:38:32 +0000729 resetVRegCycle(SU);
730
Evan Chengd38c22b2006-05-11 23:55:42 +0000731 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000732
733 // Conditions under which the scheduler should eagerly advance the cycle:
734 // (1) No available instructions
735 // (2) All pipelines full, so available instructions must have hazards.
736 //
Andrew Trickb53a00d2011-04-13 00:38:32 +0000737 // If HazardRec is disabled, the cycle was pre-advanced before calling
738 // ReleasePredecessors. In that case, IssueCount should remain 0.
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000739 //
740 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
Andrew Trickb53a00d2011-04-13 00:38:32 +0000741 if (HazardRec->isEnabled() || AvgIPC > 1) {
742 if (SU->getNode() && SU->getNode()->isMachineOpcode())
743 ++IssueCount;
744 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
745 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
746 AdvanceToCycle(CurCycle + 1);
747 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000748}
749
Evan Cheng5924bf72007-09-25 01:54:36 +0000750/// CapturePred - This does the opposite of ReleasePred. Since SU is being
751/// unscheduled, incrcease the succ left count of its predecessors. Remove
752/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000753void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000754 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000755 if (PredSU->isAvailable) {
756 PredSU->isAvailable = false;
757 if (!PredSU->isPending)
758 AvailableQueue->remove(PredSU);
759 }
760
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000761 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000762 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000763}
764
765/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
766/// its predecessor states to reflect the change.
767void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000768 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000769 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000770
Evan Cheng5924bf72007-09-25 01:54:36 +0000771 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
772 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000773 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000774 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000775 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000776 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000777 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000778 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000779 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000780 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000781 }
782 }
783
Dan Gohman198b7ff2011-11-03 21:49:52 +0000784 // Reclaim the special call resource dependence, if this is the beginning
785 // of a call.
786 unsigned CallResource = TRI->getNumRegs();
787 for (const SDNode *SUNode = SU->getNode(); SUNode;
788 SUNode = SUNode->getGluedNode()) {
789 if (SUNode->isMachineOpcode() &&
790 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
791 ++NumLiveRegs;
792 LiveRegDefs[CallResource] = SU;
793 LiveRegGens[CallResource] = NULL;
794 }
795 }
796
797 // Release the special call resource dependence, if this is the end
798 // of a call.
799 if (LiveRegGens[CallResource] == SU)
800 for (const SDNode *SUNode = SU->getNode(); SUNode;
801 SUNode = SUNode->getGluedNode()) {
802 if (SUNode->isMachineOpcode() &&
803 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
804 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
805 --NumLiveRegs;
806 LiveRegDefs[CallResource] = NULL;
807 LiveRegGens[CallResource] = NULL;
808 }
809 }
810
Evan Cheng5924bf72007-09-25 01:54:36 +0000811 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
812 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000813 if (I->isAssignedRegDep()) {
Eli Friedman0bdc0832011-12-07 22:06:02 +0000814 if (!LiveRegDefs[I->getReg()])
815 ++NumLiveRegs;
Andrew Trick033efdf2010-12-23 03:15:51 +0000816 // This becomes the nearest def. Note that an earlier def may still be
817 // pending if this is a two-address node.
818 LiveRegDefs[I->getReg()] = SU;
Andrew Tricka52f3252010-12-23 04:16:14 +0000819 if (LiveRegGens[I->getReg()] == NULL ||
820 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
821 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000822 }
823 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000824 if (SU->getHeight() < MinAvailableCycle)
825 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000826
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000827 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000828 SU->isScheduled = false;
829 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000830 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000831 // Don't make available until backtracking is complete.
832 SU->isPending = true;
833 PendingQueue.push_back(SU);
834 }
835 else {
836 AvailableQueue->push(SU);
837 }
Evan Cheng28590382010-07-21 23:53:58 +0000838 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000839}
840
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000841/// After backtracking, the hazard checker needs to be restored to a state
842/// corresponding the the current cycle.
843void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
844 HazardRec->Reset();
845
846 unsigned LookAhead = std::min((unsigned)Sequence.size(),
847 HazardRec->getMaxLookAhead());
848 if (LookAhead == 0)
849 return;
850
851 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
852 unsigned HazardCycle = (*I)->getHeight();
853 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
854 SUnit *SU = *I;
855 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
856 HazardRec->RecedeCycle();
857 }
858 EmitNode(SU);
859 }
860}
861
Evan Cheng8e136a92007-09-26 21:36:17 +0000862/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000863/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000864void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
865 SUnit *OldSU = Sequence.back();
866 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000867 Sequence.pop_back();
868 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000869 // Don't try to remove SU from AvailableQueue.
870 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000871 // FIXME: use ready cycle instead of height
872 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000873 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000874 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000875 if (OldSU == BtSU)
876 break;
877 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000878 }
879
Dan Gohman60d68442009-01-29 19:49:27 +0000880 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000881
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000882 RestoreHazardCheckerBottomUp();
883
Andrew Trick5ce945c2010-12-24 07:10:19 +0000884 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000885
Evan Cheng1ec79b42007-09-27 07:09:03 +0000886 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000887}
888
Evan Cheng3b245872010-02-05 01:27:11 +0000889static bool isOperandOf(const SUnit *SU, SDNode *N) {
890 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000891 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000892 if (SUNode->isOperandOf(N))
893 return true;
894 }
895 return false;
896}
897
Evan Cheng5924bf72007-09-25 01:54:36 +0000898/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
899/// successors to the newly created node.
900SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000901 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000902 if (!N)
903 return NULL;
904
Andrew Trickc9405662010-12-24 06:46:50 +0000905 if (SU->getNode()->getGluedNode())
906 return NULL;
907
Evan Cheng79e97132007-10-05 01:39:18 +0000908 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000909 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000910 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000911 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000912 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000913 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000914 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000915 TryUnfold = true;
916 }
Evan Cheng79e97132007-10-05 01:39:18 +0000917 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000918 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000919 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000920 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000921 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000922 }
923
924 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000925 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000926 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000927 return NULL;
928
Pete Cooper7c7ba1b2011-11-15 21:57:53 +0000929 // unfolding an x86 DEC64m operation results in store, dec, load which
930 // can't be handled here so quit
931 if (NewNodes.size() == 3)
932 return NULL;
933
Evan Chengbdd062d2010-05-20 06:13:19 +0000934 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000935 assert(NewNodes.size() == 2 && "Expected a load folding node!");
936
937 N = NewNodes[1];
938 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000939 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000940 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000941 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000942 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
943 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000944 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000945
Dan Gohmane52e0892008-11-11 21:34:44 +0000946 // LoadNode may already exist. This can happen when there is another
947 // load from the same location and producing the same type of value
948 // but it has different alignment or volatileness.
949 bool isNewLoad = true;
950 SUnit *LoadSU;
951 if (LoadNode->getNodeId() != -1) {
952 LoadSU = &SUnits[LoadNode->getNodeId()];
953 isNewLoad = false;
954 } else {
955 LoadSU = CreateNewSUnit(LoadNode);
956 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000957
958 InitNumRegDefsLeft(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000959 ComputeLatency(LoadSU);
960 }
961
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000962 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000963 assert(N->getNodeId() == -1 && "Node already inserted!");
964 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000965
Evan Cheng6cc775f2011-06-28 19:10:37 +0000966 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
967 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
968 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000969 NewSU->isTwoAddress = true;
970 break;
971 }
972 }
Evan Cheng6cc775f2011-06-28 19:10:37 +0000973 if (MCID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000974 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +0000975
976 InitNumRegDefsLeft(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000977 ComputeLatency(NewSU);
978
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000979 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000980 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000981 SmallVector<SDep, 4> ChainSuccs;
982 SmallVector<SDep, 4> LoadPreds;
983 SmallVector<SDep, 4> NodePreds;
984 SmallVector<SDep, 4> NodeSuccs;
985 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
986 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000987 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000988 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000989 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000990 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000991 else
Dan Gohman2d170892008-12-09 22:54:47 +0000992 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000993 }
994 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
995 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000996 if (I->isCtrl())
997 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000998 else
Dan Gohman2d170892008-12-09 22:54:47 +0000999 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +00001000 }
1001
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001002 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +00001003 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
1004 const SDep &Pred = ChainPreds[i];
1005 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +00001006 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +00001007 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001008 }
Evan Cheng79e97132007-10-05 01:39:18 +00001009 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001010 const SDep &Pred = LoadPreds[i];
1011 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +00001012 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +00001013 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001014 }
1015 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001016 const SDep &Pred = NodePreds[i];
1017 RemovePred(SU, Pred);
1018 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001019 }
1020 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001021 SDep D = NodeSuccs[i];
1022 SUnit *SuccDep = D.getSUnit();
1023 D.setSUnit(SU);
1024 RemovePred(SuccDep, D);
1025 D.setSUnit(NewSU);
1026 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001027 // Balance register pressure.
1028 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1029 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1030 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +00001031 }
1032 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001033 SDep D = ChainSuccs[i];
1034 SUnit *SuccDep = D.getSUnit();
1035 D.setSUnit(SU);
1036 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001037 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +00001038 D.setSUnit(LoadSU);
1039 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001040 }
Andrew Trick2085a962010-12-21 22:25:04 +00001041 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001042
1043 // Add a data dependency to reflect that NewSU reads the value defined
1044 // by LoadSU.
1045 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +00001046
Evan Cheng91e0fc92007-12-18 08:42:10 +00001047 if (isNewLoad)
1048 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +00001049 AvailableQueue->addNode(NewSU);
1050
1051 ++NumUnfolds;
1052
1053 if (NewSU->NumSuccsLeft == 0) {
1054 NewSU->isAvailable = true;
1055 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +00001056 }
1057 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +00001058 }
1059
Evan Chengbdd062d2010-05-20 06:13:19 +00001060 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001061 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +00001062
1063 // New SUnit has the exact same predecessors.
1064 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1065 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001066 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +00001067 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +00001068
1069 // Only copy scheduled successors. Cut them from old node's successor
1070 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001071 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +00001072 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1073 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001074 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +00001075 continue;
Dan Gohman2d170892008-12-09 22:54:47 +00001076 SUnit *SuccSU = I->getSUnit();
1077 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +00001078 SDep D = *I;
1079 D.setSUnit(NewSU);
1080 AddPred(SuccSU, D);
1081 D.setSUnit(SU);
1082 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +00001083 }
1084 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001085 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +00001086 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +00001087
1088 AvailableQueue->updateNode(SU);
1089 AvailableQueue->addNode(NewSU);
1090
Evan Cheng1ec79b42007-09-27 07:09:03 +00001091 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +00001092 return NewSU;
1093}
1094
Evan Chengb2c42c62009-01-12 03:19:55 +00001095/// InsertCopiesAndMoveSuccs - Insert register copies and move all
1096/// scheduled successors of the given SUnit to the last copy.
1097void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1098 const TargetRegisterClass *DestRC,
1099 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +00001100 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001101 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +00001102 CopyFromSU->CopySrcRC = SrcRC;
1103 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +00001104
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001105 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +00001106 CopyToSU->CopySrcRC = DestRC;
1107 CopyToSU->CopyDstRC = SrcRC;
1108
1109 // Only copy scheduled successors. Cut them from old node's successor
1110 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001111 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +00001112 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1113 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001114 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +00001115 continue;
Dan Gohman2d170892008-12-09 22:54:47 +00001116 SUnit *SuccSU = I->getSUnit();
1117 if (SuccSU->isScheduled) {
1118 SDep D = *I;
1119 D.setSUnit(CopyToSU);
1120 AddPred(SuccSU, D);
1121 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +00001122 }
Andrew Trick13acae02011-03-23 20:42:39 +00001123 else {
1124 // Avoid scheduling the def-side copy before other successors. Otherwise
1125 // we could introduce another physreg interference on the copy and
1126 // continue inserting copies indefinitely.
1127 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
1128 /*Reg=*/0, /*isNormalMemory=*/false,
1129 /*isMustAlias=*/false, /*isArtificial=*/true);
1130 AddPred(SuccSU, D);
1131 }
Evan Cheng8e136a92007-09-26 21:36:17 +00001132 }
Evan Chengb2c42c62009-01-12 03:19:55 +00001133 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +00001134 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +00001135
Dan Gohman2d170892008-12-09 22:54:47 +00001136 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
1137 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +00001138
1139 AvailableQueue->updateNode(SU);
1140 AvailableQueue->addNode(CopyFromSU);
1141 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001142 Copies.push_back(CopyFromSU);
1143 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +00001144
Evan Chengb2c42c62009-01-12 03:19:55 +00001145 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +00001146}
1147
1148/// getPhysicalRegisterVT - Returns the ValueType of the physical register
1149/// definition of the specified node.
1150/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +00001151static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +00001152 const TargetInstrInfo *TII) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001153 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1154 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1155 unsigned NumRes = MCID.getNumDefs();
1156 for (const unsigned *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +00001157 if (Reg == *ImpDef)
1158 break;
1159 ++NumRes;
1160 }
1161 return N->getValueType(NumRes);
1162}
1163
Evan Chengb8905c42009-03-04 01:41:49 +00001164/// CheckForLiveRegDef - Return true and update live register vector if the
1165/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001166static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +00001167 std::vector<SUnit*> &LiveRegDefs,
1168 SmallSet<unsigned, 4> &RegAdded,
1169 SmallVector<unsigned, 4> &LRegs,
1170 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +00001171 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
1172
1173 // Check if Ref is live.
Andrew Trick0af2e472011-06-07 00:38:12 +00001174 if (!LiveRegDefs[*AliasI]) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001175
1176 // Allow multiple uses of the same def.
Andrew Trick0af2e472011-06-07 00:38:12 +00001177 if (LiveRegDefs[*AliasI] == SU) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001178
1179 // Add Reg to the set of interfering live regs.
Andrew Trick0af2e472011-06-07 00:38:12 +00001180 if (RegAdded.insert(*AliasI)) {
Andrew Trick0af2e472011-06-07 00:38:12 +00001181 LRegs.push_back(*AliasI);
1182 }
Evan Chengb8905c42009-03-04 01:41:49 +00001183 }
Evan Chengb8905c42009-03-04 01:41:49 +00001184}
1185
Evan Cheng5924bf72007-09-25 01:54:36 +00001186/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1187/// scheduling of the given node to satisfy live physical register dependencies.
1188/// If the specific node is the last one that's available to schedule, do
1189/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001190bool ScheduleDAGRRList::
1191DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +00001192 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +00001193 return false;
1194
Evan Chenge6f92252007-09-27 18:46:06 +00001195 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +00001196 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001197 //
1198 // If SU is the currently live definition of the same register that it uses,
1199 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +00001200 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1201 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001202 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +00001203 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1204 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001205 }
1206
Chris Lattner11a33812010-12-23 17:24:32 +00001207 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +00001208 if (Node->getOpcode() == ISD::INLINEASM) {
1209 // Inline asm can clobber physical defs.
1210 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001211 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +00001212 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +00001213
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001214 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +00001215 unsigned Flags =
1216 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001217 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +00001218
1219 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001220 if (InlineAsm::isRegDefKind(Flags) ||
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00001221 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1222 InlineAsm::isClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +00001223 // Check for def of register or earlyclobber register.
1224 for (; NumVals; --NumVals, ++i) {
1225 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1226 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1227 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1228 }
1229 } else
1230 i += NumVals;
1231 }
1232 continue;
1233 }
1234
Dan Gohman072734e2008-11-13 23:24:17 +00001235 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +00001236 continue;
Dan Gohman198b7ff2011-11-03 21:49:52 +00001237 // If we're in the middle of scheduling a call, don't begin scheduling
1238 // another call. Also, don't allow any physical registers to be live across
1239 // the call.
1240 if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
1241 // Check the special calling-sequence resource.
1242 unsigned CallResource = TRI->getNumRegs();
1243 if (LiveRegDefs[CallResource]) {
1244 SDNode *Gen = LiveRegGens[CallResource]->getNode();
1245 while (SDNode *Glued = Gen->getGluedNode())
1246 Gen = Glued;
1247 if (!IsChainDependent(Gen, Node, 0, TII) && RegAdded.insert(CallResource))
1248 LRegs.push_back(CallResource);
1249 }
1250 }
Evan Cheng6cc775f2011-06-28 19:10:37 +00001251 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1252 if (!MCID.ImplicitDefs)
Evan Cheng5924bf72007-09-25 01:54:36 +00001253 continue;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001254 for (const unsigned *Reg = MCID.ImplicitDefs; *Reg; ++Reg)
Evan Chengb8905c42009-03-04 01:41:49 +00001255 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001256 }
Andrew Trick2085a962010-12-21 22:25:04 +00001257
Evan Cheng5924bf72007-09-25 01:54:36 +00001258 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +00001259}
1260
Andrew Trick528fad92010-12-23 05:42:20 +00001261/// Return a node that can be scheduled in this cycle. Requirements:
1262/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001263/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +00001264/// (3) No Interferences: may unschedule to break register interferences.
1265SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1266 SmallVector<SUnit*, 4> Interferences;
1267 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1268
1269 SUnit *CurSU = AvailableQueue->pop();
1270 while (CurSU) {
1271 SmallVector<unsigned, 4> LRegs;
1272 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1273 break;
1274 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1275
1276 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1277 Interferences.push_back(CurSU);
1278 CurSU = AvailableQueue->pop();
1279 }
1280 if (CurSU) {
1281 // Add the nodes that aren't ready back onto the available list.
1282 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1283 Interferences[i]->isPending = false;
1284 assert(Interferences[i]->isAvailable && "must still be available");
1285 AvailableQueue->push(Interferences[i]);
1286 }
1287 return CurSU;
1288 }
1289
1290 // All candidates are delayed due to live physical reg dependencies.
1291 // Try backtracking, code duplication, or inserting cross class copies
1292 // to resolve it.
1293 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1294 SUnit *TrySU = Interferences[i];
1295 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1296
1297 // Try unscheduling up to the point where it's safe to schedule
1298 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001299 SUnit *BtSU = NULL;
1300 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001301 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1302 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001303 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1304 BtSU = LiveRegGens[Reg];
1305 LiveCycle = BtSU->getHeight();
1306 }
Andrew Trick528fad92010-12-23 05:42:20 +00001307 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001308 if (!WillCreateCycle(TrySU, BtSU)) {
1309 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001310
1311 // Force the current node to be scheduled before the node that
1312 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001313 if (BtSU->isAvailable) {
1314 BtSU->isAvailable = false;
1315 if (!BtSU->isPending)
1316 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001317 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001318 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001319 /*Reg=*/0, /*isNormalMemory=*/false,
1320 /*isMustAlias=*/false, /*isArtificial=*/true));
1321
1322 // If one or more successors has been unscheduled, then the current
1323 // node is no longer avaialable. Schedule a successor that's now
1324 // available instead.
1325 if (!TrySU->isAvailable) {
1326 CurSU = AvailableQueue->pop();
1327 }
1328 else {
1329 CurSU = TrySU;
1330 TrySU->isPending = false;
1331 Interferences.erase(Interferences.begin()+i);
1332 }
1333 break;
1334 }
1335 }
1336
1337 if (!CurSU) {
1338 // Can't backtrack. If it's too expensive to copy the value, then try
1339 // duplicate the nodes that produces these "too expensive to copy"
1340 // values to break the dependency. In case even that doesn't work,
1341 // insert cross class copies.
1342 // If it's not too expensive, i.e. cost != -1, issue copies.
1343 SUnit *TrySU = Interferences[0];
1344 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1345 assert(LRegs.size() == 1 && "Can't handle this yet!");
1346 unsigned Reg = LRegs[0];
1347 SUnit *LRDef = LiveRegDefs[Reg];
1348 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1349 const TargetRegisterClass *RC =
1350 TRI->getMinimalPhysRegClass(Reg, VT);
1351 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1352
Evan Chengb4c6a342011-03-10 00:16:32 +00001353 // If cross copy register class is the same as RC, then it must be possible
1354 // copy the value directly. Do not try duplicate the def.
1355 // If cross copy register class is not the same as RC, then it's possible to
1356 // copy the value but it require cross register class copies and it is
1357 // expensive.
1358 // If cross copy register class is null, then it's not possible to copy
1359 // the value at all.
Andrew Trick528fad92010-12-23 05:42:20 +00001360 SUnit *NewDef = 0;
Evan Chengb4c6a342011-03-10 00:16:32 +00001361 if (DestRC != RC) {
Andrew Trick528fad92010-12-23 05:42:20 +00001362 NewDef = CopyAndMoveSuccessors(LRDef);
Evan Chengb4c6a342011-03-10 00:16:32 +00001363 if (!DestRC && !NewDef)
1364 report_fatal_error("Can't handle live physical register dependency!");
1365 }
Andrew Trick528fad92010-12-23 05:42:20 +00001366 if (!NewDef) {
1367 // Issue copies, these can be expensive cross register class copies.
1368 SmallVector<SUnit*, 2> Copies;
1369 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1370 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1371 << " to SU #" << Copies.front()->NodeNum << "\n");
1372 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1373 /*Reg=*/0, /*isNormalMemory=*/false,
1374 /*isMustAlias=*/false,
1375 /*isArtificial=*/true));
1376 NewDef = Copies.back();
1377 }
1378
1379 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1380 << " to SU #" << TrySU->NodeNum << "\n");
1381 LiveRegDefs[Reg] = NewDef;
1382 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1383 /*Reg=*/0, /*isNormalMemory=*/false,
1384 /*isMustAlias=*/false,
1385 /*isArtificial=*/true));
1386 TrySU->isAvailable = false;
1387 CurSU = NewDef;
1388 }
1389
1390 assert(CurSU && "Unable to resolve live physical register dependencies!");
1391
1392 // Add the nodes that aren't ready back onto the available list.
1393 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1394 Interferences[i]->isPending = false;
1395 // May no longer be available due to backtracking.
1396 if (Interferences[i]->isAvailable) {
1397 AvailableQueue->push(Interferences[i]);
1398 }
1399 }
1400 return CurSU;
1401}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001402
Evan Chengd38c22b2006-05-11 23:55:42 +00001403/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1404/// schedulers.
1405void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001406 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001407 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001408
Evan Chengd38c22b2006-05-11 23:55:42 +00001409 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001410 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001411 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001412 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1413 RootSU->isAvailable = true;
1414 AvailableQueue->push(RootSU);
1415 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001416
1417 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001418 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001419 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001420 while (!AvailableQueue->empty()) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00001421 DEBUG(dbgs() << "\nExamining Available:\n";
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001422 AvailableQueue->dump(this));
1423
Andrew Trick528fad92010-12-23 05:42:20 +00001424 // Pick the best node to schedule taking all constraints into
1425 // consideration.
1426 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001427
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001428 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001429
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001430 ScheduleNodeBottomUp(SU);
1431
1432 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1433 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1434 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1435 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1436 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001437 }
1438
Evan Chengd38c22b2006-05-11 23:55:42 +00001439 // Reverse the order if it is bottom up.
1440 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001441
Evan Chengd38c22b2006-05-11 23:55:42 +00001442#ifndef NDEBUG
Dan Gohman90fb5522011-10-20 21:44:34 +00001443 VerifySchedule(/*isBottomUp=*/true);
Evan Chengd38c22b2006-05-11 23:55:42 +00001444#endif
1445}
1446
1447//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001448// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001449//===----------------------------------------------------------------------===//
1450//
1451// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1452// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001453//
Evan Chengd38c22b2006-05-11 23:55:42 +00001454namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001455class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001456
Andrew Trick9ccce772011-01-14 21:11:41 +00001457struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1458 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1459};
1460
Andrew Trick3013b6a2011-06-15 17:16:12 +00001461#ifndef NDEBUG
1462template<class SF>
1463struct reverse_sort : public queue_sort {
1464 SF &SortFunc;
1465 reverse_sort(SF &sf) : SortFunc(sf) {}
1466 reverse_sort(const reverse_sort &RHS) : SortFunc(RHS.SortFunc) {}
1467
1468 bool operator()(SUnit* left, SUnit* right) const {
1469 // reverse left/right rather than simply !SortFunc(left, right)
1470 // to expose different paths in the comparison logic.
1471 return SortFunc(right, left);
1472 }
1473};
1474#endif // NDEBUG
1475
Andrew Trick9ccce772011-01-14 21:11:41 +00001476/// bu_ls_rr_sort - Priority function for bottom up register pressure
1477// reduction scheduler.
1478struct bu_ls_rr_sort : public queue_sort {
1479 enum {
1480 IsBottomUp = true,
1481 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001482 };
1483
Andrew Trick9ccce772011-01-14 21:11:41 +00001484 RegReductionPQBase *SPQ;
1485 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1486 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001487
Andrew Trick9ccce772011-01-14 21:11:41 +00001488 bool operator()(SUnit* left, SUnit* right) const;
1489};
Andrew Trick2085a962010-12-21 22:25:04 +00001490
Andrew Trick9ccce772011-01-14 21:11:41 +00001491// src_ls_rr_sort - Priority function for source order scheduler.
1492struct src_ls_rr_sort : public queue_sort {
1493 enum {
1494 IsBottomUp = true,
1495 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001496 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001497
Andrew Trick9ccce772011-01-14 21:11:41 +00001498 RegReductionPQBase *SPQ;
1499 src_ls_rr_sort(RegReductionPQBase *spq)
1500 : SPQ(spq) {}
1501 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1502 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001503
Andrew Trick9ccce772011-01-14 21:11:41 +00001504 bool operator()(SUnit* left, SUnit* right) const;
1505};
Andrew Trick2085a962010-12-21 22:25:04 +00001506
Andrew Trick9ccce772011-01-14 21:11:41 +00001507// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1508struct hybrid_ls_rr_sort : public queue_sort {
1509 enum {
1510 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001511 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001512 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001513
Andrew Trick9ccce772011-01-14 21:11:41 +00001514 RegReductionPQBase *SPQ;
1515 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1516 : SPQ(spq) {}
1517 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1518 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001519
Andrew Trick9ccce772011-01-14 21:11:41 +00001520 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001521
Andrew Trick9ccce772011-01-14 21:11:41 +00001522 bool operator()(SUnit* left, SUnit* right) const;
1523};
1524
1525// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1526// scheduler.
1527struct ilp_ls_rr_sort : public queue_sort {
1528 enum {
1529 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001530 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001531 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001532
Andrew Trick9ccce772011-01-14 21:11:41 +00001533 RegReductionPQBase *SPQ;
1534 ilp_ls_rr_sort(RegReductionPQBase *spq)
1535 : SPQ(spq) {}
1536 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1537 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001538
Andrew Trick9ccce772011-01-14 21:11:41 +00001539 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001540
Andrew Trick9ccce772011-01-14 21:11:41 +00001541 bool operator()(SUnit* left, SUnit* right) const;
1542};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001543
Andrew Trick9ccce772011-01-14 21:11:41 +00001544class RegReductionPQBase : public SchedulingPriorityQueue {
1545protected:
1546 std::vector<SUnit*> Queue;
1547 unsigned CurQueueId;
1548 bool TracksRegPressure;
1549
1550 // SUnits - The SUnits for the current graph.
1551 std::vector<SUnit> *SUnits;
1552
1553 MachineFunction &MF;
1554 const TargetInstrInfo *TII;
1555 const TargetRegisterInfo *TRI;
1556 const TargetLowering *TLI;
1557 ScheduleDAGRRList *scheduleDAG;
1558
1559 // SethiUllmanNumbers - The SethiUllman number for each node.
1560 std::vector<unsigned> SethiUllmanNumbers;
1561
1562 /// RegPressure - Tracking current reg pressure per register class.
1563 ///
1564 std::vector<unsigned> RegPressure;
1565
1566 /// RegLimit - Tracking the number of allocatable registers per register
1567 /// class.
1568 std::vector<unsigned> RegLimit;
1569
1570public:
1571 RegReductionPQBase(MachineFunction &mf,
1572 bool hasReadyFilter,
1573 bool tracksrp,
1574 const TargetInstrInfo *tii,
1575 const TargetRegisterInfo *tri,
1576 const TargetLowering *tli)
1577 : SchedulingPriorityQueue(hasReadyFilter),
1578 CurQueueId(0), TracksRegPressure(tracksrp),
1579 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1580 if (TracksRegPressure) {
1581 unsigned NumRC = TRI->getNumRegClasses();
1582 RegLimit.resize(NumRC);
1583 RegPressure.resize(NumRC);
1584 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1585 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1586 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1587 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +00001588 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
Andrew Trick9ccce772011-01-14 21:11:41 +00001589 }
1590 }
1591
1592 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1593 scheduleDAG = scheduleDag;
1594 }
1595
1596 ScheduleHazardRecognizer* getHazardRec() {
1597 return scheduleDAG->getHazardRec();
1598 }
1599
1600 void initNodes(std::vector<SUnit> &sunits);
1601
1602 void addNode(const SUnit *SU);
1603
1604 void updateNode(const SUnit *SU);
1605
1606 void releaseState() {
1607 SUnits = 0;
1608 SethiUllmanNumbers.clear();
1609 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1610 }
1611
1612 unsigned getNodePriority(const SUnit *SU) const;
1613
1614 unsigned getNodeOrdering(const SUnit *SU) const {
Andrew Trick3bd8b7a2011-03-25 06:40:55 +00001615 if (!SU->getNode()) return 0;
1616
Andrew Trick9ccce772011-01-14 21:11:41 +00001617 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1618 }
1619
1620 bool empty() const { return Queue.empty(); }
1621
1622 void push(SUnit *U) {
1623 assert(!U->NodeQueueId && "Node in the queue already");
1624 U->NodeQueueId = ++CurQueueId;
1625 Queue.push_back(U);
1626 }
1627
1628 void remove(SUnit *SU) {
1629 assert(!Queue.empty() && "Queue is empty!");
1630 assert(SU->NodeQueueId != 0 && "Not in queue!");
1631 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1632 SU);
1633 if (I != prior(Queue.end()))
1634 std::swap(*I, Queue.back());
1635 Queue.pop_back();
1636 SU->NodeQueueId = 0;
1637 }
1638
Andrew Trickd0548ae2011-02-04 03:18:17 +00001639 bool tracksRegPressure() const { return TracksRegPressure; }
1640
Andrew Trick9ccce772011-01-14 21:11:41 +00001641 void dumpRegPressure() const;
1642
1643 bool HighRegPressure(const SUnit *SU) const;
1644
Andrew Trick641e2d42011-03-05 08:00:22 +00001645 bool MayReduceRegPressure(SUnit *SU) const;
1646
1647 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
Andrew Trick9ccce772011-01-14 21:11:41 +00001648
1649 void ScheduledNode(SUnit *SU);
1650
1651 void UnscheduledNode(SUnit *SU);
1652
1653protected:
1654 bool canClobber(const SUnit *SU, const SUnit *Op);
Duncan Sands635e4ef2011-11-09 14:20:48 +00001655 void AddPseudoTwoAddrDeps();
Andrew Trick9ccce772011-01-14 21:11:41 +00001656 void PrescheduleNodesWithMultipleUses();
1657 void CalculateSethiUllmanNumbers();
1658};
1659
1660template<class SF>
Andrew Trick3013b6a2011-06-15 17:16:12 +00001661static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1662 std::vector<SUnit *>::iterator Best = Q.begin();
1663 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1664 E = Q.end(); I != E; ++I)
1665 if (Picker(*Best, *I))
1666 Best = I;
1667 SUnit *V = *Best;
1668 if (Best != prior(Q.end()))
1669 std::swap(*Best, Q.back());
1670 Q.pop_back();
1671 return V;
1672}
Andrew Trick9ccce772011-01-14 21:11:41 +00001673
Andrew Trick3013b6a2011-06-15 17:16:12 +00001674template<class SF>
1675SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1676#ifndef NDEBUG
1677 if (DAG->StressSched) {
1678 reverse_sort<SF> RPicker(Picker);
1679 return popFromQueueImpl(Q, RPicker);
1680 }
1681#endif
1682 (void)DAG;
1683 return popFromQueueImpl(Q, Picker);
1684}
1685
1686template<class SF>
1687class RegReductionPriorityQueue : public RegReductionPQBase {
Andrew Trick9ccce772011-01-14 21:11:41 +00001688 SF Picker;
1689
1690public:
1691 RegReductionPriorityQueue(MachineFunction &mf,
1692 bool tracksrp,
1693 const TargetInstrInfo *tii,
1694 const TargetRegisterInfo *tri,
1695 const TargetLowering *tli)
1696 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1697 Picker(this) {}
1698
1699 bool isBottomUp() const { return SF::IsBottomUp; }
1700
1701 bool isReady(SUnit *U) const {
1702 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1703 }
1704
1705 SUnit *pop() {
1706 if (Queue.empty()) return NULL;
1707
Andrew Trick3013b6a2011-06-15 17:16:12 +00001708 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
Andrew Trick9ccce772011-01-14 21:11:41 +00001709 V->NodeQueueId = 0;
1710 return V;
1711 }
1712
1713 void dump(ScheduleDAG *DAG) const {
1714 // Emulate pop() without clobbering NodeQueueIds.
1715 std::vector<SUnit*> DumpQueue = Queue;
1716 SF DumpPicker = Picker;
1717 while (!DumpQueue.empty()) {
Andrew Trick3013b6a2011-06-15 17:16:12 +00001718 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
Dan Gohman90fb5522011-10-20 21:44:34 +00001719 dbgs() << "Height " << SU->getHeight() << ": ";
Andrew Trick9ccce772011-01-14 21:11:41 +00001720 SU->dump(DAG);
1721 }
1722 }
1723};
1724
1725typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1726BURegReductionPriorityQueue;
1727
Andrew Trick9ccce772011-01-14 21:11:41 +00001728typedef RegReductionPriorityQueue<src_ls_rr_sort>
1729SrcRegReductionPriorityQueue;
1730
1731typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1732HybridBURRPriorityQueue;
1733
1734typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1735ILPBURRPriorityQueue;
1736} // end anonymous namespace
1737
1738//===----------------------------------------------------------------------===//
1739// Static Node Priority for Register Pressure Reduction
1740//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001741
Andrew Trickbfbd9722011-04-14 05:15:06 +00001742// Check for special nodes that bypass scheduling heuristics.
1743// Currently this pushes TokenFactor nodes down, but may be used for other
1744// pseudo-ops as well.
1745//
1746// Return -1 to schedule right above left, 1 for left above right.
1747// Return 0 if no bias exists.
1748static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1749 bool LSchedLow = left->isScheduleLow;
1750 bool RSchedLow = right->isScheduleLow;
1751 if (LSchedLow != RSchedLow)
1752 return LSchedLow < RSchedLow ? 1 : -1;
1753 return 0;
1754}
1755
Dan Gohman186f65d2008-11-20 03:30:37 +00001756/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1757/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001758static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001759CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001760 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1761 if (SethiUllmanNumber != 0)
1762 return SethiUllmanNumber;
1763
1764 unsigned Extra = 0;
1765 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1766 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001767 if (I->isCtrl()) continue; // ignore chain preds
1768 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001769 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001770 if (PredSethiUllman > SethiUllmanNumber) {
1771 SethiUllmanNumber = PredSethiUllman;
1772 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001773 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001774 ++Extra;
1775 }
1776
1777 SethiUllmanNumber += Extra;
1778
1779 if (SethiUllmanNumber == 0)
1780 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001781
Evan Cheng7e4abde2008-07-02 09:23:51 +00001782 return SethiUllmanNumber;
1783}
1784
Andrew Trick9ccce772011-01-14 21:11:41 +00001785/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1786/// scheduling units.
1787void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1788 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001789
Andrew Trick9ccce772011-01-14 21:11:41 +00001790 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1791 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001792}
1793
Andrew Trick9ccce772011-01-14 21:11:41 +00001794void RegReductionPQBase::addNode(const SUnit *SU) {
1795 unsigned SUSize = SethiUllmanNumbers.size();
1796 if (SUnits->size() > SUSize)
1797 SethiUllmanNumbers.resize(SUSize*2, 0);
1798 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1799}
1800
1801void RegReductionPQBase::updateNode(const SUnit *SU) {
1802 SethiUllmanNumbers[SU->NodeNum] = 0;
1803 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1804}
1805
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001806// Lower priority means schedule further down. For bottom-up scheduling, lower
1807// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001808unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1809 assert(SU->NodeNum < SethiUllmanNumbers.size());
1810 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1811 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1812 // CopyToReg should be close to its uses to facilitate coalescing and
1813 // avoid spilling.
1814 return 0;
1815 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1816 Opc == TargetOpcode::SUBREG_TO_REG ||
1817 Opc == TargetOpcode::INSERT_SUBREG)
1818 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1819 // close to their uses to facilitate coalescing.
1820 return 0;
1821 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1822 // If SU does not have a register use, i.e. it doesn't produce a value
1823 // that would be consumed (e.g. store), then it terminates a chain of
1824 // computation. Give it a large SethiUllman number so it will be
1825 // scheduled right before its predecessors that it doesn't lengthen
1826 // their live ranges.
1827 return 0xffff;
1828 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1829 // If SU does not have a register def, schedule it close to its uses
1830 // because it does not lengthen any live ranges.
1831 return 0;
Evan Cheng1355bbd2011-04-26 21:31:35 +00001832#if 1
Andrew Trick9ccce772011-01-14 21:11:41 +00001833 return SethiUllmanNumbers[SU->NodeNum];
Evan Cheng1355bbd2011-04-26 21:31:35 +00001834#else
1835 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1836 if (SU->isCallOp) {
1837 // FIXME: This assumes all of the defs are used as call operands.
1838 int NP = (int)Priority - SU->getNode()->getNumValues();
1839 return (NP > 0) ? NP : 0;
1840 }
1841 return Priority;
1842#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001843}
1844
1845//===----------------------------------------------------------------------===//
1846// Register Pressure Tracking
1847//===----------------------------------------------------------------------===//
1848
1849void RegReductionPQBase::dumpRegPressure() const {
1850 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1851 E = TRI->regclass_end(); I != E; ++I) {
1852 const TargetRegisterClass *RC = *I;
1853 unsigned Id = RC->getID();
1854 unsigned RP = RegPressure[Id];
1855 if (!RP) continue;
1856 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1857 << '\n');
1858 }
1859}
1860
1861bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1862 if (!TLI)
1863 return false;
1864
1865 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1866 I != E; ++I) {
1867 if (I->isCtrl())
1868 continue;
1869 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001870 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1871 // to cover the number of registers defined (they are all live).
1872 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001873 continue;
1874 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001875 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1876 RegDefPos.IsValid(); RegDefPos.Advance()) {
Owen Anderson96adc4a2011-06-15 23:35:18 +00001877 unsigned RCId, Cost;
1878 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1879
Andrew Trick9ccce772011-01-14 21:11:41 +00001880 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1881 return true;
1882 }
1883 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001884 return false;
1885}
1886
Andrew Trick641e2d42011-03-05 08:00:22 +00001887bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00001888 const SDNode *N = SU->getNode();
1889
1890 if (!N->isMachineOpcode() || !SU->NumSuccs)
1891 return false;
1892
1893 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1894 for (unsigned i = 0; i != NumDefs; ++i) {
1895 EVT VT = N->getValueType(i);
1896 if (!N->hasAnyUseOfValue(i))
1897 continue;
1898 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1899 if (RegPressure[RCId] >= RegLimit[RCId])
1900 return true;
1901 }
1902 return false;
1903}
1904
Andrew Trick641e2d42011-03-05 08:00:22 +00001905// Compute the register pressure contribution by this instruction by count up
1906// for uses that are not live and down for defs. Only count register classes
1907// that are already under high pressure. As a side effect, compute the number of
1908// uses of registers that are already live.
1909//
1910// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1911// so could probably be factored.
1912int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1913 LiveUses = 0;
1914 int PDiff = 0;
1915 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1916 I != E; ++I) {
1917 if (I->isCtrl())
1918 continue;
1919 SUnit *PredSU = I->getSUnit();
1920 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1921 // to cover the number of registers defined (they are all live).
1922 if (PredSU->NumRegDefsLeft == 0) {
1923 if (PredSU->getNode()->isMachineOpcode())
1924 ++LiveUses;
1925 continue;
1926 }
1927 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1928 RegDefPos.IsValid(); RegDefPos.Advance()) {
1929 EVT VT = RegDefPos.GetValue();
1930 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1931 if (RegPressure[RCId] >= RegLimit[RCId])
1932 ++PDiff;
1933 }
1934 }
1935 const SDNode *N = SU->getNode();
1936
Eric Christopher7238cba2011-03-08 19:35:47 +00001937 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
Andrew Trick641e2d42011-03-05 08:00:22 +00001938 return PDiff;
1939
1940 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1941 for (unsigned i = 0; i != NumDefs; ++i) {
1942 EVT VT = N->getValueType(i);
1943 if (!N->hasAnyUseOfValue(i))
1944 continue;
1945 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1946 if (RegPressure[RCId] >= RegLimit[RCId])
1947 --PDiff;
1948 }
1949 return PDiff;
1950}
1951
Andrew Trick9ccce772011-01-14 21:11:41 +00001952void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1953 if (!TracksRegPressure)
1954 return;
1955
Eric Christopher7238cba2011-03-08 19:35:47 +00001956 if (!SU->getNode())
1957 return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001958
Andrew Trick9ccce772011-01-14 21:11:41 +00001959 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1960 I != E; ++I) {
1961 if (I->isCtrl())
1962 continue;
1963 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001964 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1965 // to cover the number of registers defined (they are all live).
1966 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001967 continue;
1968 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001969 // FIXME: The ScheduleDAG currently loses information about which of a
1970 // node's values is consumed by each dependence. Consequently, if the node
1971 // defines multiple register classes, we don't know which to pressurize
1972 // here. Instead the following loop consumes the register defs in an
1973 // arbitrary order. At least it handles the common case of clustered loads
1974 // to the same class. For precise liveness, each SDep needs to indicate the
1975 // result number. But that tightly couples the ScheduleDAG with the
1976 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1977 // value type or register class to SDep.
1978 //
1979 // The most important aspect of register tracking is balancing the increase
1980 // here with the reduction further below. Note that this SU may use multiple
1981 // defs in PredSU. The can't be determined here, but we've already
1982 // compensated by reducing NumRegDefsLeft in PredSU during
1983 // ScheduleDAGSDNodes::AddSchedEdges.
1984 --PredSU->NumRegDefsLeft;
1985 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1986 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1987 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1988 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00001989 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00001990
1991 unsigned RCId, Cost;
1992 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1993 RegPressure[RCId] += Cost;
Andrew Trickd0548ae2011-02-04 03:18:17 +00001994 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00001995 }
1996 }
1997
Andrew Trickd0548ae2011-02-04 03:18:17 +00001998 // We should have this assert, but there may be dead SDNodes that never
1999 // materialize as SUnits, so they don't appear to generate liveness.
2000 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2001 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2002 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2003 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2004 if (SkipRegDefs > 0)
2005 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00002006 unsigned RCId, Cost;
2007 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
2008 if (RegPressure[RCId] < Cost) {
Andrew Trickd0548ae2011-02-04 03:18:17 +00002009 // Register pressure tracking is imprecise. This can happen. But we try
2010 // hard not to let it happen because it likely results in poor scheduling.
2011 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
2012 RegPressure[RCId] = 0;
2013 }
2014 else {
Owen Anderson96adc4a2011-06-15 23:35:18 +00002015 RegPressure[RCId] -= Cost;
Andrew Trick9ccce772011-01-14 21:11:41 +00002016 }
2017 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002018 dumpRegPressure();
2019}
2020
2021void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
2022 if (!TracksRegPressure)
2023 return;
2024
2025 const SDNode *N = SU->getNode();
Eric Christopher7238cba2011-03-08 19:35:47 +00002026 if (!N) return;
Andrew Tricka8846e02011-03-23 20:40:18 +00002027
Andrew Trick9ccce772011-01-14 21:11:41 +00002028 if (!N->isMachineOpcode()) {
2029 if (N->getOpcode() != ISD::CopyToReg)
2030 return;
2031 } else {
2032 unsigned Opc = N->getMachineOpcode();
2033 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2034 Opc == TargetOpcode::INSERT_SUBREG ||
2035 Opc == TargetOpcode::SUBREG_TO_REG ||
2036 Opc == TargetOpcode::REG_SEQUENCE ||
2037 Opc == TargetOpcode::IMPLICIT_DEF)
2038 return;
2039 }
2040
2041 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2042 I != E; ++I) {
2043 if (I->isCtrl())
2044 continue;
2045 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002046 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2047 // counts data deps.
2048 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00002049 continue;
2050 const SDNode *PN = PredSU->getNode();
2051 if (!PN->isMachineOpcode()) {
2052 if (PN->getOpcode() == ISD::CopyFromReg) {
2053 EVT VT = PN->getValueType(0);
2054 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2055 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2056 }
2057 continue;
2058 }
2059 unsigned POpc = PN->getMachineOpcode();
2060 if (POpc == TargetOpcode::IMPLICIT_DEF)
2061 continue;
Andrew Trick31f25bc2011-06-27 18:01:20 +00002062 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2063 POpc == TargetOpcode::INSERT_SUBREG ||
2064 POpc == TargetOpcode::SUBREG_TO_REG) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002065 EVT VT = PN->getValueType(0);
2066 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2067 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2068 continue;
2069 }
2070 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2071 for (unsigned i = 0; i != NumDefs; ++i) {
2072 EVT VT = PN->getValueType(i);
2073 if (!PN->hasAnyUseOfValue(i))
2074 continue;
2075 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2076 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2077 // Register pressure tracking is imprecise. This can happen.
2078 RegPressure[RCId] = 0;
2079 else
2080 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2081 }
2082 }
2083
2084 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2085 // may transfer data dependencies to CopyToReg.
2086 if (SU->NumSuccs && N->isMachineOpcode()) {
2087 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2088 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2089 EVT VT = N->getValueType(i);
2090 if (VT == MVT::Glue || VT == MVT::Other)
2091 continue;
2092 if (!N->hasAnyUseOfValue(i))
2093 continue;
2094 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2095 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2096 }
2097 }
2098
2099 dumpRegPressure();
2100}
2101
2102//===----------------------------------------------------------------------===//
2103// Dynamic Node Priority for Register Pressure Reduction
2104//===----------------------------------------------------------------------===//
2105
Evan Chengb9e3db62007-03-14 22:43:40 +00002106/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00002107/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00002108static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002109 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00002110 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00002111 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00002112 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002113 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00002114 // If there are bunch of CopyToRegs stacked up, they should be considered
2115 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00002116 if (I->getSUnit()->getNode() &&
2117 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002118 Height = closestSucc(I->getSUnit())+1;
2119 if (Height > MaxHeight)
2120 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00002121 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002122 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00002123}
2124
Evan Cheng61bc51e2007-12-20 02:22:36 +00002125/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00002126/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00002127static unsigned calcMaxScratches(const SUnit *SU) {
2128 unsigned Scratches = 0;
2129 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00002130 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002131 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00002132 Scratches++;
2133 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00002134 return Scratches;
2135}
2136
Andrew Trickb53a00d2011-04-13 00:38:32 +00002137/// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2138/// CopyFromReg from a virtual register.
2139static bool hasOnlyLiveInOpers(const SUnit *SU) {
2140 bool RetVal = false;
2141 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2142 I != E; ++I) {
2143 if (I->isCtrl()) continue;
2144 const SUnit *PredSU = I->getSUnit();
2145 if (PredSU->getNode() &&
2146 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2147 unsigned Reg =
2148 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2149 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2150 RetVal = true;
2151 continue;
2152 }
2153 }
2154 return false;
2155 }
2156 return RetVal;
2157}
2158
2159/// hasOnlyLiveOutUses - Return true if SU has only value successors that are
Evan Cheng6c1414f2010-10-29 18:09:28 +00002160/// CopyToReg to a virtual register. This SU def is probably a liveout and
2161/// it has no other use. It should be scheduled closer to the terminator.
2162static bool hasOnlyLiveOutUses(const SUnit *SU) {
2163 bool RetVal = false;
2164 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2165 I != E; ++I) {
2166 if (I->isCtrl()) continue;
2167 const SUnit *SuccSU = I->getSUnit();
2168 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2169 unsigned Reg =
2170 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2171 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2172 RetVal = true;
2173 continue;
2174 }
2175 }
2176 return false;
2177 }
2178 return RetVal;
2179}
2180
Andrew Trickb53a00d2011-04-13 00:38:32 +00002181// Set isVRegCycle for a node with only live in opers and live out uses. Also
2182// set isVRegCycle for its CopyFromReg operands.
2183//
2184// This is only relevant for single-block loops, in which case the VRegCycle
2185// node is likely an induction variable in which the operand and target virtual
2186// registers should be coalesced (e.g. pre/post increment values). Setting the
2187// isVRegCycle flag helps the scheduler prioritize other uses of the same
2188// CopyFromReg so that this node becomes the virtual register "kill". This
2189// avoids interference between the values live in and out of the block and
2190// eliminates a copy inside the loop.
2191static void initVRegCycle(SUnit *SU) {
2192 if (DisableSchedVRegCycle)
2193 return;
2194
2195 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2196 return;
2197
2198 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2199
2200 SU->isVRegCycle = true;
2201
2202 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002203 I != E; ++I) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002204 if (I->isCtrl()) continue;
2205 I->getSUnit()->isVRegCycle = true;
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002206 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002207}
2208
Andrew Trickb53a00d2011-04-13 00:38:32 +00002209// After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2210// CopyFromReg operands. We should no longer penalize other uses of this VReg.
2211static void resetVRegCycle(SUnit *SU) {
2212 if (!SU->isVRegCycle)
2213 return;
2214
2215 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2216 I != E; ++I) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002217 if (I->isCtrl()) continue; // ignore chain preds
Andrew Trickb53a00d2011-04-13 00:38:32 +00002218 SUnit *PredSU = I->getSUnit();
2219 if (PredSU->isVRegCycle) {
2220 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2221 "VRegCycle def must be CopyFromReg");
2222 I->getSUnit()->isVRegCycle = 0;
2223 }
2224 }
2225}
2226
2227// Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2228// means a node that defines the VRegCycle has not been scheduled yet.
2229static bool hasVRegCycleUse(const SUnit *SU) {
2230 // If this SU also defines the VReg, don't hoist it as a "use".
2231 if (SU->isVRegCycle)
2232 return false;
2233
2234 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2235 I != E; ++I) {
2236 if (I->isCtrl()) continue; // ignore chain preds
2237 if (I->getSUnit()->isVRegCycle &&
2238 I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2239 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2240 return true;
Andrew Trick2ad0b372011-04-07 19:54:57 +00002241 }
2242 }
2243 return false;
2244}
2245
Andrew Trick9ccce772011-01-14 21:11:41 +00002246// Check for either a dependence (latency) or resource (hazard) stall.
2247//
2248// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2249static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2250 if ((int)SPQ->getCurCycle() < Height) return true;
2251 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2252 != ScheduleHazardRecognizer::NoHazard)
2253 return true;
2254 return false;
2255}
2256
2257// Return -1 if left has higher priority, 1 if right has higher priority.
2258// Return 0 if latency-based priority is equivalent.
2259static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2260 RegReductionPQBase *SPQ) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002261 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2262 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2263 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2264 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2265 int LHeight = (int)left->getHeight() + LPenalty;
2266 int RHeight = (int)right->getHeight() + RPenalty;
Andrew Trick9ccce772011-01-14 21:11:41 +00002267
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002268 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002269 BUHasStall(left, LHeight, SPQ);
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002270 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002271 BUHasStall(right, RHeight, SPQ);
2272
2273 // If scheduling one of the node will cause a pipeline stall, delay it.
2274 // If scheduling either one of the node will cause a pipeline stall, sort
2275 // them according to their height.
2276 if (LStall) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002277 if (!RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002278 return 1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002279 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002280 return LHeight > RHeight ? 1 : -1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002281 } else if (RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002282 return -1;
2283
Andrew Trick47ff14b2011-01-21 05:51:33 +00002284 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002285 // and latency.
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002286 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2287 right->SchedulingPref == Sched::ILP)) {
Andrew Trick47ff14b2011-01-21 05:51:33 +00002288 if (DisableSchedCycles) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002289 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002290 return LHeight > RHeight ? 1 : -1;
2291 }
Andrew Trick47ff14b2011-01-21 05:51:33 +00002292 else {
2293 // If neither instruction stalls (!LStall && !RStall) then
Eric Christopher9cb33de2011-03-06 21:13:45 +00002294 // its height is already covered so only its depth matters. We also reach
Andrew Trick47ff14b2011-01-21 05:51:33 +00002295 // this if both stall but have the same height.
Andrew Trickb53a00d2011-04-13 00:38:32 +00002296 int LDepth = left->getDepth() - LPenalty;
2297 int RDepth = right->getDepth() - RPenalty;
Andrew Trick47ff14b2011-01-21 05:51:33 +00002298 if (LDepth != RDepth) {
2299 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2300 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2301 << ") depth " << RDepth << "\n");
2302 return LDepth < RDepth ? 1 : -1;
2303 }
2304 }
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002305 if (left->Latency != right->Latency)
Andrew Trick9ccce772011-01-14 21:11:41 +00002306 return left->Latency > right->Latency ? 1 : -1;
2307 }
2308 return 0;
2309}
2310
2311static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002312 // Schedule physical register definitions close to their use. This is
2313 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2314 // long as shortening physreg live ranges is generally good, we can defer
2315 // creating a subtarget hook.
2316 if (!DisableSchedPhysRegJoin) {
2317 bool LHasPhysReg = left->hasPhysRegDefs;
2318 bool RHasPhysReg = right->hasPhysRegDefs;
2319 if (LHasPhysReg != RHasPhysReg) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002320 #ifndef NDEBUG
2321 const char *PhysRegMsg[] = {" has no physreg", " defines a physreg"};
2322 #endif
2323 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2324 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2325 << PhysRegMsg[RHasPhysReg] << "\n");
2326 return LHasPhysReg < RHasPhysReg;
2327 }
2328 }
2329
Evan Cheng2f647542011-04-26 04:57:37 +00002330 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
Evan Cheng6730f032007-01-08 23:55:53 +00002331 unsigned LPriority = SPQ->getNodePriority(left);
2332 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng1355bbd2011-04-26 21:31:35 +00002333
2334 // Be really careful about hoisting call operands above previous calls.
2335 // Only allows it if it would reduce register pressure.
2336 if (left->isCall && right->isCallOp) {
2337 unsigned RNumVals = right->getNode()->getNumValues();
2338 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2339 }
2340 if (right->isCall && left->isCallOp) {
2341 unsigned LNumVals = left->getNode()->getNumValues();
2342 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2343 }
2344
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002345 if (LPriority != RPriority)
Evan Cheng73bdf042008-03-01 00:39:47 +00002346 return LPriority > RPriority;
Andrew Trick52b3e382011-03-08 01:51:56 +00002347
Evan Cheng1355bbd2011-04-26 21:31:35 +00002348 // One or both of the nodes are calls and their sethi-ullman numbers are the
2349 // same, then keep source order.
2350 if (left->isCall || right->isCall) {
2351 unsigned LOrder = SPQ->getNodeOrdering(left);
2352 unsigned ROrder = SPQ->getNodeOrdering(right);
2353
2354 // Prefer an ordering where the lower the non-zero order number, the higher
2355 // the preference.
2356 if ((LOrder || ROrder) && LOrder != ROrder)
2357 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2358 }
2359
Evan Cheng73bdf042008-03-01 00:39:47 +00002360 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2361 // e.g.
2362 // t1 = op t2, c1
2363 // t3 = op t4, c2
2364 //
2365 // and the following instructions are both ready.
2366 // t2 = op c3
2367 // t4 = op c4
2368 //
2369 // Then schedule t2 = op first.
2370 // i.e.
2371 // t4 = op c4
2372 // t2 = op c3
2373 // t1 = op t2, c1
2374 // t3 = op t4, c2
2375 //
2376 // This creates more short live intervals.
2377 unsigned LDist = closestSucc(left);
2378 unsigned RDist = closestSucc(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002379 if (LDist != RDist)
Evan Cheng73bdf042008-03-01 00:39:47 +00002380 return LDist < RDist;
2381
Evan Cheng3a14efa2009-02-12 08:59:45 +00002382 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002383 unsigned LScratch = calcMaxScratches(left);
2384 unsigned RScratch = calcMaxScratches(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002385 if (LScratch != RScratch)
Evan Cheng73bdf042008-03-01 00:39:47 +00002386 return LScratch > RScratch;
2387
Evan Cheng1355bbd2011-04-26 21:31:35 +00002388 // Comparing latency against a call makes little sense unless the node
2389 // is register pressure-neutral.
2390 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2391 return (left->NodeQueueId > right->NodeQueueId);
2392
2393 // Do not compare latencies when one or both of the nodes are calls.
2394 if (!DisableSchedCycles &&
2395 !(left->isCall || right->isCall)) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002396 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2397 if (result != 0)
2398 return result > 0;
2399 }
2400 else {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002401 if (left->getHeight() != right->getHeight())
Andrew Trick9ccce772011-01-14 21:11:41 +00002402 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002403
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002404 if (left->getDepth() != right->getDepth())
Andrew Trick9ccce772011-01-14 21:11:41 +00002405 return left->getDepth() < right->getDepth();
2406 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002407
Andrew Trick2085a962010-12-21 22:25:04 +00002408 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002409 "NodeQueueId cannot be zero");
2410 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002411}
2412
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002413// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002414bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002415 if (int res = checkSpecialNodes(left, right))
2416 return res > 0;
2417
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002418 return BURRSort(left, right, SPQ);
2419}
2420
2421// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002422bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002423 if (int res = checkSpecialNodes(left, right))
2424 return res > 0;
2425
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002426 unsigned LOrder = SPQ->getNodeOrdering(left);
2427 unsigned ROrder = SPQ->getNodeOrdering(right);
2428
2429 // Prefer an ordering where the lower the non-zero order number, the higher
2430 // the preference.
2431 if ((LOrder || ROrder) && LOrder != ROrder)
2432 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2433
2434 return BURRSort(left, right, SPQ);
2435}
2436
Andrew Trick9ccce772011-01-14 21:11:41 +00002437// If the time between now and when the instruction will be ready can cover
2438// the spill code, then avoid adding it to the ready queue. This gives long
2439// stalls highest priority and allows hoisting across calls. It should also
2440// speed up processing the available queue.
2441bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2442 static const unsigned ReadyDelay = 3;
2443
2444 if (SPQ->MayReduceRegPressure(SU)) return true;
2445
2446 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2447
2448 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2449 != ScheduleHazardRecognizer::NoHazard)
2450 return false;
2451
2452 return true;
2453}
2454
2455// Return true if right should be scheduled with higher priority than left.
2456bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002457 if (int res = checkSpecialNodes(left, right))
2458 return res > 0;
2459
Evan Chengdebf9c52010-11-03 00:45:17 +00002460 if (left->isCall || right->isCall)
2461 // No way to compute latency of calls.
2462 return BURRSort(left, right, SPQ);
2463
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002464 bool LHigh = SPQ->HighRegPressure(left);
2465 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002466 // Avoid causing spills. If register pressure is high, schedule for
2467 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002468 if (LHigh && !RHigh) {
2469 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2470 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002471 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002472 }
2473 else if (!LHigh && RHigh) {
2474 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2475 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002476 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002477 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002478 if (!LHigh && !RHigh) {
2479 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2480 if (result != 0)
2481 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002482 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002483 return BURRSort(left, right, SPQ);
2484}
2485
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002486// Schedule as many instructions in each cycle as possible. So don't make an
2487// instruction available unless it is ready in the current cycle.
2488bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002489 if (SU->getHeight() > CurCycle) return false;
2490
2491 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2492 != ScheduleHazardRecognizer::NoHazard)
2493 return false;
2494
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002495 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002496}
2497
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002498static bool canEnableCoalescing(SUnit *SU) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002499 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2500 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2501 // CopyToReg should be close to its uses to facilitate coalescing and
2502 // avoid spilling.
2503 return true;
2504
2505 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2506 Opc == TargetOpcode::SUBREG_TO_REG ||
2507 Opc == TargetOpcode::INSERT_SUBREG)
2508 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2509 // close to their uses to facilitate coalescing.
2510 return true;
2511
2512 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2513 // If SU does not have a register def, schedule it close to its uses
2514 // because it does not lengthen any live ranges.
2515 return true;
2516
2517 return false;
2518}
2519
Andrew Trickb8390b72011-03-05 08:04:11 +00002520// list-ilp is currently an experimental scheduler that allows various
2521// heuristics to be enabled prior to the normal register reduction logic.
Andrew Trick9ccce772011-01-14 21:11:41 +00002522bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002523 if (int res = checkSpecialNodes(left, right))
2524 return res > 0;
2525
Evan Chengdebf9c52010-11-03 00:45:17 +00002526 if (left->isCall || right->isCall)
2527 // No way to compute latency of calls.
2528 return BURRSort(left, right, SPQ);
2529
Andrew Trick52b3e382011-03-08 01:51:56 +00002530 unsigned LLiveUses = 0, RLiveUses = 0;
2531 int LPDiff = 0, RPDiff = 0;
2532 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2533 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2534 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2535 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002536 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002537 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2538 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002539 return LPDiff > RPDiff;
2540 }
2541
Andrew Trick52b3e382011-03-08 01:51:56 +00002542 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002543 bool LReduce = canEnableCoalescing(left);
2544 bool RReduce = canEnableCoalescing(right);
Andrew Trick52b3e382011-03-08 01:51:56 +00002545 if (LReduce && !RReduce) return false;
2546 if (RReduce && !LReduce) return true;
2547 }
2548
2549 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2550 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2551 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002552 return LLiveUses < RLiveUses;
2553 }
2554
Andrew Trick52b3e382011-03-08 01:51:56 +00002555 if (!DisableSchedStalls) {
2556 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2557 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002558 if (LStall != RStall)
Andrew Trick52b3e382011-03-08 01:51:56 +00002559 return left->getHeight() > right->getHeight();
Andrew Trick641e2d42011-03-05 08:00:22 +00002560 }
2561
Andrew Trick25cedf32011-03-05 10:29:25 +00002562 if (!DisableSchedCriticalPath) {
2563 int spread = (int)left->getDepth() - (int)right->getDepth();
2564 if (std::abs(spread) > MaxReorderWindow) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002565 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2566 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2567 << right->getDepth() << "\n");
Andrew Trick25cedf32011-03-05 10:29:25 +00002568 return left->getDepth() < right->getDepth();
2569 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002570 }
2571
2572 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002573 int spread = (int)left->getHeight() - (int)right->getHeight();
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002574 if (std::abs(spread) > MaxReorderWindow)
Andrew Trick52b3e382011-03-08 01:51:56 +00002575 return left->getHeight() > right->getHeight();
Evan Cheng37b740c2010-07-24 00:39:05 +00002576 }
2577
2578 return BURRSort(left, right, SPQ);
2579}
2580
Andrew Trickb53a00d2011-04-13 00:38:32 +00002581void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2582 SUnits = &sunits;
2583 // Add pseudo dependency edges for two-address nodes.
Evan Chengd33b2d62011-11-10 07:43:16 +00002584 if (!Disable2AddrHack)
2585 AddPseudoTwoAddrDeps();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002586 // Reroute edges to nodes with multiple uses.
2587 if (!TracksRegPressure)
2588 PrescheduleNodesWithMultipleUses();
2589 // Calculate node priorities.
2590 CalculateSethiUllmanNumbers();
2591
2592 // For single block loops, mark nodes that look like canonical IV increments.
2593 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2594 for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2595 initVRegCycle(&sunits[i]);
2596 }
2597 }
2598}
2599
Andrew Trick9ccce772011-01-14 21:11:41 +00002600//===----------------------------------------------------------------------===//
2601// Preschedule for Register Pressure
2602//===----------------------------------------------------------------------===//
2603
2604bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002605 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002606 unsigned Opc = SU->getNode()->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002607 const MCInstrDesc &MCID = TII->get(Opc);
2608 unsigned NumRes = MCID.getNumDefs();
2609 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002610 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002611 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002612 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002613 if (DU->getNodeId() != -1 &&
2614 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002615 return true;
2616 }
2617 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002618 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002619 return false;
2620}
2621
Andrew Trick832a6a192011-09-01 00:54:31 +00002622/// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2623/// successor's explicit physregs whose definition can reach DepSU.
2624/// i.e. DepSU should not be scheduled above SU.
2625static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2626 ScheduleDAGRRList *scheduleDAG,
2627 const TargetInstrInfo *TII,
2628 const TargetRegisterInfo *TRI) {
2629 const unsigned *ImpDefs
2630 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
2631 if(!ImpDefs)
2632 return false;
2633
2634 for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
2635 SI != SE; ++SI) {
2636 SUnit *SuccSU = SI->getSUnit();
2637 for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
2638 PE = SuccSU->Preds.end(); PI != PE; ++PI) {
2639 if (!PI->isAssignedRegDep())
2640 continue;
2641
2642 for (const unsigned *ImpDef = ImpDefs; *ImpDef; ++ImpDef) {
2643 // Return true if SU clobbers this physical register use and the
2644 // definition of the register reaches from DepSU. IsReachable queries a
2645 // topological forward sort of the DAG (following the successors).
2646 if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
2647 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2648 return true;
2649 }
2650 }
2651 }
2652 return false;
2653}
2654
Evan Chengf9891412007-12-20 09:25:31 +00002655/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002656/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002657static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002658 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002659 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002660 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002661 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2662 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002663 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002664 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002665 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002666 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002667 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002668 const unsigned *SUImpDefs =
2669 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2670 if (!SUImpDefs)
2671 return false;
2672 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002673 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002674 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002675 continue;
2676 if (!N->hasAnyUseOfValue(i))
2677 continue;
2678 unsigned Reg = ImpDefs[i - NumDefs];
2679 for (;*SUImpDefs; ++SUImpDefs) {
2680 unsigned SUReg = *SUImpDefs;
2681 if (TRI->regsOverlap(Reg, SUReg))
2682 return true;
2683 }
Evan Chengf9891412007-12-20 09:25:31 +00002684 }
2685 }
2686 return false;
2687}
2688
Dan Gohman9a658d72009-03-24 00:49:12 +00002689/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2690/// are not handled well by the general register pressure reduction
2691/// heuristics. When presented with code like this:
2692///
2693/// N
2694/// / |
2695/// / |
2696/// U store
2697/// |
2698/// ...
2699///
2700/// the heuristics tend to push the store up, but since the
2701/// operand of the store has another use (U), this would increase
2702/// the length of that other use (the U->N edge).
2703///
2704/// This function transforms code like the above to route U's
2705/// dependence through the store when possible, like this:
2706///
2707/// N
2708/// ||
2709/// ||
2710/// store
2711/// |
2712/// U
2713/// |
2714/// ...
2715///
2716/// This results in the store being scheduled immediately
2717/// after N, which shortens the U->N live range, reducing
2718/// register pressure.
2719///
Andrew Trick9ccce772011-01-14 21:11:41 +00002720void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002721 // Visit all the nodes in topological order, working top-down.
2722 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2723 SUnit *SU = &(*SUnits)[i];
2724 // For now, only look at nodes with no data successors, such as stores.
2725 // These are especially important, due to the heuristics in
2726 // getNodePriority for nodes with no data successors.
2727 if (SU->NumSuccs != 0)
2728 continue;
2729 // For now, only look at nodes with exactly one data predecessor.
2730 if (SU->NumPreds != 1)
2731 continue;
2732 // Avoid prescheduling copies to virtual registers, which don't behave
2733 // like other nodes from the perspective of scheduling heuristics.
2734 if (SDNode *N = SU->getNode())
2735 if (N->getOpcode() == ISD::CopyToReg &&
2736 TargetRegisterInfo::isVirtualRegister
2737 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2738 continue;
2739
2740 // Locate the single data predecessor.
2741 SUnit *PredSU = 0;
2742 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2743 EE = SU->Preds.end(); II != EE; ++II)
2744 if (!II->isCtrl()) {
2745 PredSU = II->getSUnit();
2746 break;
2747 }
2748 assert(PredSU);
2749
2750 // Don't rewrite edges that carry physregs, because that requires additional
2751 // support infrastructure.
2752 if (PredSU->hasPhysRegDefs)
2753 continue;
2754 // Short-circuit the case where SU is PredSU's only data successor.
2755 if (PredSU->NumSuccs == 1)
2756 continue;
2757 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002758 // like other nodes from the perspective of scheduling heuristics.
Dan Gohman9a658d72009-03-24 00:49:12 +00002759 if (SDNode *N = SU->getNode())
2760 if (N->getOpcode() == ISD::CopyFromReg &&
2761 TargetRegisterInfo::isVirtualRegister
2762 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2763 continue;
2764
2765 // Perform checks on the successors of PredSU.
2766 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2767 EE = PredSU->Succs.end(); II != EE; ++II) {
2768 SUnit *PredSuccSU = II->getSUnit();
2769 if (PredSuccSU == SU) continue;
2770 // If PredSU has another successor with no data successors, for
2771 // now don't attempt to choose either over the other.
2772 if (PredSuccSU->NumSuccs == 0)
2773 goto outer_loop_continue;
2774 // Don't break physical register dependencies.
2775 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2776 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2777 goto outer_loop_continue;
2778 // Don't introduce graph cycles.
2779 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2780 goto outer_loop_continue;
2781 }
2782
2783 // Ok, the transformation is safe and the heuristics suggest it is
2784 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002785 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2786 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002787 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002788 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2789 SDep Edge = PredSU->Succs[i];
2790 assert(!Edge.isAssignedRegDep());
2791 SUnit *SuccSU = Edge.getSUnit();
2792 if (SuccSU != SU) {
2793 Edge.setSUnit(PredSU);
2794 scheduleDAG->RemovePred(SuccSU, Edge);
2795 scheduleDAG->AddPred(SU, Edge);
2796 Edge.setSUnit(SU);
2797 scheduleDAG->AddPred(SuccSU, Edge);
2798 --i;
2799 }
2800 }
2801 outer_loop_continue:;
2802 }
2803}
2804
Evan Chengd38c22b2006-05-11 23:55:42 +00002805/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2806/// it as a def&use operand. Add a pseudo control edge from it to the other
2807/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002808/// first (lower in the schedule). If both nodes are two-address, favor the
2809/// one that has a CopyToReg use (more likely to be a loop induction update).
2810/// If both are two-address, but one is commutable while the other is not
2811/// commutable, favor the one that's not commutable.
Duncan Sands635e4ef2011-11-09 14:20:48 +00002812void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002813 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002814 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002815 if (!SU->isTwoAddress)
2816 continue;
2817
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002818 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002819 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002820 continue;
2821
Evan Cheng6c1414f2010-10-29 18:09:28 +00002822 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002823 unsigned Opc = Node->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002824 const MCInstrDesc &MCID = TII->get(Opc);
2825 unsigned NumRes = MCID.getNumDefs();
2826 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002827 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002828 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
Dan Gohman82016c22008-11-19 02:00:32 +00002829 continue;
2830 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2831 if (DU->getNodeId() == -1)
2832 continue;
2833 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2834 if (!DUSU) continue;
2835 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2836 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002837 if (I->isCtrl()) continue;
2838 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002839 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002840 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002841 // Be conservative. Ignore if nodes aren't at roughly the same
2842 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002843 if (SuccSU->getHeight() < SU->getHeight() &&
2844 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002845 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002846 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2847 // constrains whatever is using the copy, instead of the copy
2848 // itself. In the case that the copy is coalesced, this
2849 // preserves the intent of the pseudo two-address heurietics.
2850 while (SuccSU->Succs.size() == 1 &&
2851 SuccSU->getNode()->isMachineOpcode() &&
2852 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002853 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002854 SuccSU = SuccSU->Succs.front().getSUnit();
2855 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002856 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2857 continue;
2858 // Don't constrain nodes with physical register defs if the
2859 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002860 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002861 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002862 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002863 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002864 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2865 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002866 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002867 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2868 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2869 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002870 continue;
Andrew Trick832a6a192011-09-01 00:54:31 +00002871 if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
2872 (!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002873 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002874 (!SU->isCommutable && SuccSU->isCommutable)) &&
2875 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002876 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002877 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002878 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002879 /*Reg=*/0, /*isNormalMemory=*/false,
2880 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002881 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002882 }
2883 }
2884 }
2885 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002886}
2887
Evan Chengd38c22b2006-05-11 23:55:42 +00002888//===----------------------------------------------------------------------===//
2889// Public Constructor Functions
2890//===----------------------------------------------------------------------===//
2891
Dan Gohmandfaf6462009-02-11 04:27:20 +00002892llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002893llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2894 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002895 const TargetMachine &TM = IS->TM;
2896 const TargetInstrInfo *TII = TM.getInstrInfo();
2897 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002898
Evan Chenga77f3d32010-07-21 06:09:07 +00002899 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002900 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002901 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002902 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002903 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002904}
2905
Dan Gohmandfaf6462009-02-11 04:27:20 +00002906llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002907llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2908 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002909 const TargetMachine &TM = IS->TM;
2910 const TargetInstrInfo *TII = TM.getInstrInfo();
2911 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002912
Evan Chenga77f3d32010-07-21 06:09:07 +00002913 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002914 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002915 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002916 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002917 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002918}
2919
2920llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002921llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2922 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002923 const TargetMachine &TM = IS->TM;
2924 const TargetInstrInfo *TII = TM.getInstrInfo();
2925 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002926 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002927
Evan Chenga77f3d32010-07-21 06:09:07 +00002928 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002929 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002930
2931 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002932 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002933 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002934}
Evan Cheng37b740c2010-07-24 00:39:05 +00002935
2936llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002937llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2938 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002939 const TargetMachine &TM = IS->TM;
2940 const TargetInstrInfo *TII = TM.getInstrInfo();
2941 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2942 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002943
Evan Cheng37b740c2010-07-24 00:39:05 +00002944 ILPBURRPriorityQueue *PQ =
2945 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002946 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002947 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002948 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002949}