blob: a0e2fb62f1dee7395107324c8d44fef85d865012 [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
Jim Laskey29e635d2006-08-02 12:30:23 +000018#include "llvm/CodeGen/SchedulerRegistry.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "ScheduleDAGSDNodes.h"
20#include "llvm/ADT/STLExtras.h"
Evan Cheng5924bf72007-09-25 01:54:36 +000021#include "llvm/ADT/SmallSet.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000022#include "llvm/ADT/Statistic.h"
Weiming Zhao4a0b4fb2013-01-29 21:18:43 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
25#include "llvm/CodeGen/SelectionDAGISel.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Chris Lattner3b9f02a2010-04-07 05:20:54 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000030#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000034#include "llvm/Target/TargetSubtargetInfo.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000035#include <climits>
Evan Chengd38c22b2006-05-11 23:55:42 +000036using namespace llvm;
37
Chandler Carruth1b9dde02014-04-22 02:02:50 +000038#define DEBUG_TYPE "pre-RA-sched"
39
Dan Gohmanfd227e92008-03-25 17:10:29 +000040STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
Evan Cheng79e97132007-10-05 01:39:18 +000041STATISTIC(NumUnfolds, "Number of nodes unfolded");
Evan Cheng1ec79b42007-09-27 07:09:03 +000042STATISTIC(NumDups, "Number of duplicated nodes");
Evan Chengb2c42c62009-01-12 03:19:55 +000043STATISTIC(NumPRCopies, "Number of physical register copies");
Evan Cheng1ec79b42007-09-27 07:09:03 +000044
Jim Laskey95eda5b2006-08-01 14:21:23 +000045static RegisterScheduler
46 burrListDAGScheduler("list-burr",
Dan Gohman9c4b7d52008-10-14 20:25:08 +000047 "Bottom-up register reduction list scheduling",
Jim Laskey95eda5b2006-08-01 14:21:23 +000048 createBURRListDAGScheduler);
49static RegisterScheduler
Bill Wendling8cbc25d2010-01-23 10:26:57 +000050 sourceListDAGScheduler("source",
51 "Similar to list-burr but schedules in source "
52 "order when possible",
53 createSourceListDAGScheduler);
Jim Laskey95eda5b2006-08-01 14:21:23 +000054
Evan Chengbdd062d2010-05-20 06:13:19 +000055static RegisterScheduler
Evan Cheng725211e2010-05-21 00:42:32 +000056 hybridListDAGScheduler("list-hybrid",
Evan Cheng37b740c2010-07-24 00:39:05 +000057 "Bottom-up register pressure aware list scheduling "
58 "which tries to balance latency and register pressure",
Evan Chengbdd062d2010-05-20 06:13:19 +000059 createHybridListDAGScheduler);
60
Evan Cheng37b740c2010-07-24 00:39:05 +000061static RegisterScheduler
62 ILPListDAGScheduler("list-ilp",
63 "Bottom-up register pressure aware list scheduling "
64 "which tries to balance ILP and register pressure",
65 createILPListDAGScheduler);
66
Andrew Trick47ff14b2011-01-21 05:51:33 +000067static cl::opt<bool> DisableSchedCycles(
Andrew Trickbd428ec2011-01-21 06:19:05 +000068 "disable-sched-cycles", cl::Hidden, cl::init(false),
Andrew Trick47ff14b2011-01-21 05:51:33 +000069 cl::desc("Disable cycle-level precision during preRA scheduling"));
Andrew Trick10ffc2b2010-12-24 05:03:26 +000070
Andrew Trick641e2d42011-03-05 08:00:22 +000071// Temporary sched=list-ilp flags until the heuristics are robust.
Andrew Trickbfbd9722011-04-14 05:15:06 +000072// Some options are also available under sched=list-hybrid.
Andrew Trick641e2d42011-03-05 08:00:22 +000073static cl::opt<bool> DisableSchedRegPressure(
74 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
75 cl::desc("Disable regpressure priority in sched=list-ilp"));
76static cl::opt<bool> DisableSchedLiveUses(
Andrew Trickdd017322011-03-06 00:03:32 +000077 "disable-sched-live-uses", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000078 cl::desc("Disable live use priority in sched=list-ilp"));
Andrew Trick2ad0b372011-04-07 19:54:57 +000079static cl::opt<bool> DisableSchedVRegCycle(
80 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
81 cl::desc("Disable virtual register cycle interference checks"));
Andrew Trickbfbd9722011-04-14 05:15:06 +000082static cl::opt<bool> DisableSchedPhysRegJoin(
83 "disable-sched-physreg-join", cl::Hidden, cl::init(false),
84 cl::desc("Disable physreg def-use affinity"));
Andrew Trick641e2d42011-03-05 08:00:22 +000085static cl::opt<bool> DisableSchedStalls(
Andrew Trickdd017322011-03-06 00:03:32 +000086 "disable-sched-stalls", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000087 cl::desc("Disable no-stall priority in sched=list-ilp"));
88static cl::opt<bool> DisableSchedCriticalPath(
89 "disable-sched-critical-path", cl::Hidden, cl::init(false),
90 cl::desc("Disable critical path priority in sched=list-ilp"));
91static cl::opt<bool> DisableSchedHeight(
92 "disable-sched-height", cl::Hidden, cl::init(false),
93 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
Evan Chengd33b2d62011-11-10 07:43:16 +000094static cl::opt<bool> Disable2AddrHack(
95 "disable-2addr-hack", cl::Hidden, cl::init(true),
96 cl::desc("Disable scheduler's two-address hack"));
Andrew Trick641e2d42011-03-05 08:00:22 +000097
98static cl::opt<int> MaxReorderWindow(
99 "max-sched-reorder", cl::Hidden, cl::init(6),
100 cl::desc("Number of instructions to allow ahead of the critical path "
101 "in sched=list-ilp"));
102
103static cl::opt<unsigned> AvgIPC(
104 "sched-avg-ipc", cl::Hidden, cl::init(1),
105 cl::desc("Average inst/cycle whan no target itinerary exists."));
106
Evan Chengd38c22b2006-05-11 23:55:42 +0000107namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +0000108//===----------------------------------------------------------------------===//
109/// ScheduleDAGRRList - The actual register reduction list scheduler
110/// implementation. This supports both top-down and bottom-up scheduling.
111///
Nick Lewycky02d5f772009-10-25 06:33:48 +0000112class ScheduleDAGRRList : public ScheduleDAGSDNodes {
Evan Chengd38c22b2006-05-11 23:55:42 +0000113private:
Evan Chengbdd062d2010-05-20 06:13:19 +0000114 /// NeedLatency - True if the scheduler will make use of latency information.
115 ///
116 bool NeedLatency;
117
Evan Chengd38c22b2006-05-11 23:55:42 +0000118 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +0000119 SchedulingPriorityQueue *AvailableQueue;
120
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000121 /// PendingQueue - This contains all of the instructions whose operands have
122 /// been issued, but their results are not ready yet (due to the latency of
123 /// the operation). Once the operands becomes available, the instruction is
124 /// added to the AvailableQueue.
125 std::vector<SUnit*> PendingQueue;
126
127 /// HazardRec - The hazard recognizer to use.
128 ScheduleHazardRecognizer *HazardRec;
129
Andrew Trick528fad92010-12-23 05:42:20 +0000130 /// CurCycle - The current scheduler state corresponds to this cycle.
131 unsigned CurCycle;
132
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000133 /// MinAvailableCycle - Cycle of the soonest available instruction.
134 unsigned MinAvailableCycle;
135
Andrew Trick641e2d42011-03-05 08:00:22 +0000136 /// IssueCount - Count instructions issued in this cycle
137 /// Currently valid only for bottom-up scheduling.
138 unsigned IssueCount;
139
Dan Gohmanc07f6862008-09-23 18:50:48 +0000140 /// LiveRegDefs - A set of physical registers and their definition
Evan Cheng5924bf72007-09-25 01:54:36 +0000141 /// that are "live". These nodes must be scheduled before any other nodes that
142 /// modifies the registers can be scheduled.
Dan Gohmanc07f6862008-09-23 18:50:48 +0000143 unsigned NumLiveRegs;
Fiona Glasere25b06f2015-12-02 18:32:59 +0000144 std::unique_ptr<SUnit*[]> LiveRegDefs;
145 std::unique_ptr<SUnit*[]> LiveRegGens;
Evan Cheng5924bf72007-09-25 01:54:36 +0000146
Andrew Trick7cf43612013-02-25 19:11:48 +0000147 // Collect interferences between physical register use/defs.
148 // Each interference is an SUnit and set of physical registers.
149 SmallVector<SUnit*, 4> Interferences;
150 typedef DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMapT;
151 LRegsMapT LRegsMap;
152
Dan Gohmanad2134d2008-11-25 00:52:40 +0000153 /// Topo - A topological ordering for SUnits which permits fast IsReachable
154 /// and similar queries.
155 ScheduleDAGTopologicalSort Topo;
156
Eli Friedmand5c173f2011-12-07 22:24:28 +0000157 // Hack to keep track of the inverse of FindCallSeqStart without more crazy
158 // DAG crawling.
159 DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
160
Evan Chengd38c22b2006-05-11 23:55:42 +0000161public:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000162 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
163 SchedulingPriorityQueue *availqueue,
164 CodeGenOpt::Level OptLevel)
Dan Gohman90fb5522011-10-20 21:44:34 +0000165 : ScheduleDAGSDNodes(mf),
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000166 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000167 Topo(SUnits, nullptr) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000168
Eric Christopheredba30c2014-10-09 06:28:06 +0000169 const TargetSubtargetInfo &STI = mf.getSubtarget();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000170 if (DisableSchedCycles || !NeedLatency)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000171 HazardRec = new ScheduleHazardRecognizer();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000172 else
Eric Christopheredba30c2014-10-09 06:28:06 +0000173 HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000174 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000175
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000176 ~ScheduleDAGRRList() override {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000177 delete HazardRec;
Evan Chengd38c22b2006-05-11 23:55:42 +0000178 delete AvailableQueue;
179 }
180
Craig Topper7b883b32014-03-08 06:31:39 +0000181 void Schedule() override;
Evan Chengd38c22b2006-05-11 23:55:42 +0000182
Andrew Trick9ccce772011-01-14 21:11:41 +0000183 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
184
Roman Levenstein733a4d62008-03-26 11:23:38 +0000185 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000186 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
187 return Topo.IsReachable(SU, TargetSU);
188 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000189
Dan Gohman60d68442009-01-29 19:49:27 +0000190 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000191 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000192 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
193 return Topo.WillCreateCycle(SU, TargetSU);
194 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000195
Dan Gohman2d170892008-12-09 22:54:47 +0000196 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000197 /// This returns true if this is a new predecessor.
198 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000199 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000200 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000201 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000202 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000203
Dan Gohman2d170892008-12-09 22:54:47 +0000204 /// RemovePred - removes a predecessor edge from SUnit SU.
205 /// This returns true if an edge was removed.
206 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000207 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000208 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000209 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000210 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000211
Evan Chengd38c22b2006-05-11 23:55:42 +0000212private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000213 bool isReady(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000214 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000215 AvailableQueue->isReady(SU);
216 }
217
Dan Gohman60d68442009-01-29 19:49:27 +0000218 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000219 void ReleasePredecessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000220 void ReleasePending();
221 void AdvanceToCycle(unsigned NextCycle);
222 void AdvancePastStalls(SUnit *SU);
223 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000224 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000225 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000226 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000227 void RestoreHazardCheckerBottomUp();
228 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000229 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000230 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
231 const TargetRegisterClass*,
232 const TargetRegisterClass*,
Craig Topperb94011f2013-07-14 04:42:23 +0000233 SmallVectorImpl<SUnit*>&);
234 bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000235
Andrew Trick7cf43612013-02-25 19:11:48 +0000236 void releaseInterferences(unsigned Reg = 0);
237
Andrew Trick528fad92010-12-23 05:42:20 +0000238 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000239 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000240
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000241 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000242 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000243 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000244 unsigned NumSUnits = SUnits.size();
Andrew Trick52226d42012-03-07 23:00:49 +0000245 SUnit *NewNode = newSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000246 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000247 if (NewNode->NodeNum >= NumSUnits)
248 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000249 return NewNode;
250 }
251
Roman Levenstein733a4d62008-03-26 11:23:38 +0000252 /// CreateClone - Creates a new SUnit from an existing one.
253 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000254 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000255 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000256 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000257 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000258 if (NewNode->NodeNum >= NumSUnits)
259 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000260 return NewNode;
261 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000262
Andrew Trick52226d42012-03-07 23:00:49 +0000263 /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
Evan Chengbdd062d2010-05-20 06:13:19 +0000264 /// need actual latency information but the hybrid scheduler does.
Craig Topper7b883b32014-03-08 06:31:39 +0000265 bool forceUnitLatencies() const override {
Evan Chengbdd062d2010-05-20 06:13:19 +0000266 return !NeedLatency;
267 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000268};
269} // end anonymous namespace
270
Owen Anderson96adc4a2011-06-15 23:35:18 +0000271/// GetCostForDef - Looks up the register class and cost for a given definition.
272/// Typically this just means looking up the representative register class,
Owen Andersonca2f78a2011-11-16 01:02:57 +0000273/// but for untyped values (MVT::Untyped) it means inspecting the node's
Owen Anderson96adc4a2011-06-15 23:35:18 +0000274/// opcode to determine what register class is being generated.
275static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
276 const TargetLowering *TLI,
277 const TargetInstrInfo *TII,
278 const TargetRegisterInfo *TRI,
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000279 unsigned &RegClass, unsigned &Cost,
280 const MachineFunction &MF) {
Patrik Hagglund05394352012-12-13 18:45:35 +0000281 MVT VT = RegDefPos.GetValue();
Owen Anderson96adc4a2011-06-15 23:35:18 +0000282
283 // Special handling for untyped values. These values can only come from
284 // the expansion of custom DAG-to-DAG patterns.
Owen Andersonca2f78a2011-11-16 01:02:57 +0000285 if (VT == MVT::Untyped) {
Owen Andersond1955e72011-06-21 22:54:23 +0000286 const SDNode *Node = RegDefPos.GetNode();
Owen Andersond1955e72011-06-21 22:54:23 +0000287
Weiming Zhao4a0b4fb2013-01-29 21:18:43 +0000288 // Special handling for CopyFromReg of untyped values.
289 if (!Node->isMachineOpcode() && Node->getOpcode() == ISD::CopyFromReg) {
290 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
291 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg);
292 RegClass = RC->getID();
293 Cost = 1;
294 return;
295 }
296
297 unsigned Opcode = Node->getMachineOpcode();
Owen Andersond1955e72011-06-21 22:54:23 +0000298 if (Opcode == TargetOpcode::REG_SEQUENCE) {
299 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
300 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
301 RegClass = RC->getID();
302 Cost = 1;
303 return;
304 }
305
Owen Anderson96adc4a2011-06-15 23:35:18 +0000306 unsigned Idx = RegDefPos.GetIdx();
Evan Cheng6cc775f2011-06-28 19:10:37 +0000307 const MCInstrDesc Desc = TII->get(Opcode);
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000308 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +0000309 RegClass = RC->getID();
310 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
311 // better way to determine it.
312 Cost = 1;
313 } else {
314 RegClass = TLI->getRepRegClassFor(VT)->getID();
315 Cost = TLI->getRepRegClassCostFor(VT);
316 }
317}
Evan Chengd38c22b2006-05-11 23:55:42 +0000318
319/// Schedule - Schedule the DAG using list scheduling.
320void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000321 DEBUG(dbgs()
322 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000323 << " '" << BB->getName() << "' **********\n");
Evan Cheng5924bf72007-09-25 01:54:36 +0000324
Andrew Trick528fad92010-12-23 05:42:20 +0000325 CurCycle = 0;
Andrew Trick641e2d42011-03-05 08:00:22 +0000326 IssueCount = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000327 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000328 NumLiveRegs = 0;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000329 // Allocate slots for each physical register, plus one for a special register
330 // to track the virtual resource of a calling sequence.
Fiona Glasere25b06f2015-12-02 18:32:59 +0000331 LiveRegDefs.reset(new SUnit*[TRI->getNumRegs() + 1]());
332 LiveRegGens.reset(new SUnit*[TRI->getNumRegs() + 1]());
Eli Friedmand5c173f2011-12-07 22:24:28 +0000333 CallSeqEndForStart.clear();
Andrew Trick7cf43612013-02-25 19:11:48 +0000334 assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
Evan Cheng5924bf72007-09-25 01:54:36 +0000335
Dan Gohman04543e72008-12-23 18:36:58 +0000336 // Build the scheduling graph.
Craig Topperc0196b12014-04-14 00:51:57 +0000337 BuildSchedGraph(nullptr);
Evan Chengd38c22b2006-05-11 23:55:42 +0000338
Sanjay Patele9fa3362016-02-03 22:44:14 +0000339 DEBUG(for (SUnit &SU : SUnits)
340 SU.dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000341 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000342
Dan Gohman46520a22008-06-21 19:18:17 +0000343 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000344
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000345 HazardRec->Reset();
346
Dan Gohman90fb5522011-10-20 21:44:34 +0000347 // Execute the actual scheduling loop.
348 ListScheduleBottomUp();
Andrew Trick2085a962010-12-21 22:25:04 +0000349
Evan Chengd38c22b2006-05-11 23:55:42 +0000350 AvailableQueue->releaseState();
Andrew Trickedee68c2012-03-07 05:21:40 +0000351
352 DEBUG({
353 dbgs() << "*** Final schedule ***\n";
354 dumpSchedule();
355 dbgs() << '\n';
356 });
Evan Chengafed73e2006-05-12 01:58:24 +0000357}
Evan Chengd38c22b2006-05-11 23:55:42 +0000358
359//===----------------------------------------------------------------------===//
360// Bottom-Up Scheduling
361//===----------------------------------------------------------------------===//
362
Evan Chengd38c22b2006-05-11 23:55:42 +0000363/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000364/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000365void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000366 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000367
Evan Chengd38c22b2006-05-11 23:55:42 +0000368#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000369 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000370 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000371 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000372 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000373 llvm_unreachable(nullptr);
Evan Chengd38c22b2006-05-11 23:55:42 +0000374 }
375#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000376 --PredSU->NumSuccsLeft;
377
Andrew Trick52226d42012-03-07 23:00:49 +0000378 if (!forceUnitLatencies()) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000379 // Updating predecessor's height. This is now the cycle when the
380 // predecessor can be scheduled without causing a pipeline stall.
381 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
382 }
383
Dan Gohmanb9543432009-02-10 23:27:53 +0000384 // If all the node's successors are scheduled, this node is ready
385 // to be scheduled. Ignore the special EntrySU node.
386 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000387 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000388
389 unsigned Height = PredSU->getHeight();
390 if (Height < MinAvailableCycle)
391 MinAvailableCycle = Height;
392
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000393 if (isReady(PredSU)) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000394 AvailableQueue->push(PredSU);
395 }
396 // CapturePred and others may have left the node in the pending queue, avoid
397 // adding it twice.
398 else if (!PredSU->isPending) {
399 PredSU->isPending = true;
400 PendingQueue.push_back(PredSU);
401 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000402 }
403}
404
Dan Gohman198b7ff2011-11-03 21:49:52 +0000405/// IsChainDependent - Test if Outer is reachable from Inner through
406/// chain dependencies.
407static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
408 unsigned NestLevel,
409 const TargetInstrInfo *TII) {
410 SDNode *N = Outer;
411 for (;;) {
412 if (N == Inner)
413 return true;
414 // For a TokenFactor, examine each operand. There may be multiple ways
415 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
416 // most nesting in order to ensure that we find the corresponding match.
417 if (N->getOpcode() == ISD::TokenFactor) {
Pete Cooper9271ccc2015-06-26 19:18:49 +0000418 for (const SDValue &Op : N->op_values())
419 if (IsChainDependent(Op.getNode(), Inner, NestLevel, TII))
Dan Gohman198b7ff2011-11-03 21:49:52 +0000420 return true;
421 return false;
422 }
423 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
424 if (N->isMachineOpcode()) {
425 if (N->getMachineOpcode() ==
426 (unsigned)TII->getCallFrameDestroyOpcode()) {
427 ++NestLevel;
428 } else if (N->getMachineOpcode() ==
429 (unsigned)TII->getCallFrameSetupOpcode()) {
430 if (NestLevel == 0)
431 return false;
432 --NestLevel;
433 }
434 }
435 // Otherwise, find the chain and continue climbing.
Pete Cooper9271ccc2015-06-26 19:18:49 +0000436 for (const SDValue &Op : N->op_values())
437 if (Op.getValueType() == MVT::Other) {
438 N = Op.getNode();
Dan Gohman198b7ff2011-11-03 21:49:52 +0000439 goto found_chain_operand;
440 }
441 return false;
442 found_chain_operand:;
443 if (N->getOpcode() == ISD::EntryToken)
444 return false;
445 }
446}
447
448/// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
449/// the corresponding (lowered) CALLSEQ_BEGIN node.
450///
451/// NestLevel and MaxNested are used in recursion to indcate the current level
452/// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
453/// level seen so far.
454///
455/// TODO: It would be better to give CALLSEQ_END an explicit operand to point
456/// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
457static SDNode *
458FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
459 const TargetInstrInfo *TII) {
460 for (;;) {
461 // For a TokenFactor, examine each operand. There may be multiple ways
462 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
463 // most nesting in order to ensure that we find the corresponding match.
464 if (N->getOpcode() == ISD::TokenFactor) {
Craig Topperc0196b12014-04-14 00:51:57 +0000465 SDNode *Best = nullptr;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000466 unsigned BestMaxNest = MaxNest;
Pete Cooper9271ccc2015-06-26 19:18:49 +0000467 for (const SDValue &Op : N->op_values()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000468 unsigned MyNestLevel = NestLevel;
469 unsigned MyMaxNest = MaxNest;
Pete Cooper9271ccc2015-06-26 19:18:49 +0000470 if (SDNode *New = FindCallSeqStart(Op.getNode(),
Dan Gohman198b7ff2011-11-03 21:49:52 +0000471 MyNestLevel, MyMaxNest, TII))
472 if (!Best || (MyMaxNest > BestMaxNest)) {
473 Best = New;
474 BestMaxNest = MyMaxNest;
475 }
476 }
477 assert(Best);
478 MaxNest = BestMaxNest;
479 return Best;
480 }
481 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
482 if (N->isMachineOpcode()) {
483 if (N->getMachineOpcode() ==
484 (unsigned)TII->getCallFrameDestroyOpcode()) {
485 ++NestLevel;
486 MaxNest = std::max(MaxNest, NestLevel);
487 } else if (N->getMachineOpcode() ==
488 (unsigned)TII->getCallFrameSetupOpcode()) {
489 assert(NestLevel != 0);
490 --NestLevel;
491 if (NestLevel == 0)
492 return N;
493 }
494 }
495 // Otherwise, find the chain and continue climbing.
Pete Cooper9271ccc2015-06-26 19:18:49 +0000496 for (const SDValue &Op : N->op_values())
497 if (Op.getValueType() == MVT::Other) {
498 N = Op.getNode();
Dan Gohman198b7ff2011-11-03 21:49:52 +0000499 goto found_chain_operand;
500 }
Craig Topperc0196b12014-04-14 00:51:57 +0000501 return nullptr;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000502 found_chain_operand:;
503 if (N->getOpcode() == ISD::EntryToken)
Craig Topperc0196b12014-04-14 00:51:57 +0000504 return nullptr;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000505 }
506}
507
Andrew Trick033efdf2010-12-23 03:15:51 +0000508/// Call ReleasePred for each predecessor, then update register live def/gen.
509/// Always update LiveRegDefs for a register dependence even if the current SU
510/// also defines the register. This effectively create one large live range
511/// across a sequence of two-address node. This is important because the
512/// entire chain must be scheduled together. Example:
513///
514/// flags = (3) add
515/// flags = (2) addc flags
516/// flags = (1) addc flags
517///
518/// results in
519///
520/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000521/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000522///
523/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
524/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000525void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000526 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000527 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000528 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000529 ReleasePred(SU, &*I);
530 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000531 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000532 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000533 // clobber the register is scheduled between the predecessor and
534 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000535 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000536 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
537 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000538 LiveRegDefs[I->getReg()] = I->getSUnit();
539 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000540 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000541 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000542 }
543 }
544 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000545
546 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
547 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
548 // these nodes, to prevent other calls from being interscheduled with them.
549 unsigned CallResource = TRI->getNumRegs();
550 if (!LiveRegDefs[CallResource])
551 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
552 if (Node->isMachineOpcode() &&
553 Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
554 unsigned NestLevel = 0;
555 unsigned MaxNest = 0;
556 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
557
558 SUnit *Def = &SUnits[N->getNodeId()];
Eli Friedmand5c173f2011-12-07 22:24:28 +0000559 CallSeqEndForStart[Def] = SU;
560
Dan Gohman198b7ff2011-11-03 21:49:52 +0000561 ++NumLiveRegs;
562 LiveRegDefs[CallResource] = Def;
563 LiveRegGens[CallResource] = SU;
564 break;
565 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000566}
567
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000568/// Check to see if any of the pending instructions are ready to issue. If
569/// so, add them to the available queue.
570void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000571 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000572 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
573 return;
574 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000575
576 // If the available queue is empty, it is safe to reset MinAvailableCycle.
577 if (AvailableQueue->empty())
578 MinAvailableCycle = UINT_MAX;
579
580 // Check to see if any of the pending instructions are ready to issue. If
581 // so, add them to the available queue.
582 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000583 unsigned ReadyCycle = PendingQueue[i]->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000584 if (ReadyCycle < MinAvailableCycle)
585 MinAvailableCycle = ReadyCycle;
586
587 if (PendingQueue[i]->isAvailable) {
588 if (!isReady(PendingQueue[i]))
589 continue;
590 AvailableQueue->push(PendingQueue[i]);
591 }
592 PendingQueue[i]->isPending = false;
593 PendingQueue[i] = PendingQueue.back();
594 PendingQueue.pop_back();
595 --i; --e;
596 }
597}
598
599/// Move the scheduler state forward by the specified number of Cycles.
600void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
601 if (NextCycle <= CurCycle)
602 return;
603
Andrew Trick641e2d42011-03-05 08:00:22 +0000604 IssueCount = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000605 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000606 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000607 // Bypass lots of virtual calls in case of long latency.
608 CurCycle = NextCycle;
609 }
610 else {
611 for (; CurCycle != NextCycle; ++CurCycle) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000612 HazardRec->RecedeCycle();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000613 }
614 }
615 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
616 // available Q to release pending nodes at least once before popping.
617 ReleasePending();
618}
619
620/// Move the scheduler state forward until the specified node's dependents are
621/// ready and can be scheduled with no resource conflicts.
622void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000623 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000624 return;
625
Andrew Trickb53a00d2011-04-13 00:38:32 +0000626 // FIXME: Nodes such as CopyFromReg probably should not advance the current
627 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
628 // has predecessors the cycle will be advanced when they are scheduled.
629 // But given the crude nature of modeling latency though such nodes, we
630 // currently need to treat these nodes like real instructions.
631 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
632
Dan Gohman90fb5522011-10-20 21:44:34 +0000633 unsigned ReadyCycle = SU->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000634
635 // Bump CurCycle to account for latency. We assume the latency of other
636 // available instructions may be hidden by the stall (not a full pipe stall).
637 // This updates the hazard recognizer's cycle before reserving resources for
638 // this instruction.
639 AdvanceToCycle(ReadyCycle);
640
641 // Calls are scheduled in their preceding cycle, so don't conflict with
642 // hazards from instructions after the call. EmitNode will reset the
643 // scoreboard state before emitting the call.
Dan Gohman90fb5522011-10-20 21:44:34 +0000644 if (SU->isCall)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000645 return;
646
647 // FIXME: For resource conflicts in very long non-pipelined stages, we
648 // should probably skip ahead here to avoid useless scoreboard checks.
649 int Stalls = 0;
650 while (true) {
651 ScheduleHazardRecognizer::HazardType HT =
Dan Gohman90fb5522011-10-20 21:44:34 +0000652 HazardRec->getHazardType(SU, -Stalls);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000653
654 if (HT == ScheduleHazardRecognizer::NoHazard)
655 break;
656
657 ++Stalls;
658 }
659 AdvanceToCycle(CurCycle + Stalls);
660}
661
662/// Record this SUnit in the HazardRecognizer.
663/// Does not update CurCycle.
664void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000665 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000666 return;
667
668 // Check for phys reg copy.
669 if (!SU->getNode())
670 return;
671
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000672 switch (SU->getNode()->getOpcode()) {
673 default:
674 assert(SU->getNode()->isMachineOpcode() &&
675 "This target-independent node should not be scheduled.");
676 break;
677 case ISD::MERGE_VALUES:
678 case ISD::TokenFactor:
Nadav Rotem7c277da2012-09-06 09:17:37 +0000679 case ISD::LIFETIME_START:
680 case ISD::LIFETIME_END:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000681 case ISD::CopyToReg:
682 case ISD::CopyFromReg:
683 case ISD::EH_LABEL:
684 // Noops don't affect the scoreboard state. Copies are likely to be
685 // removed.
686 return;
687 case ISD::INLINEASM:
688 // For inline asm, clear the pipeline state.
689 HazardRec->Reset();
690 return;
691 }
Dan Gohman90fb5522011-10-20 21:44:34 +0000692 if (SU->isCall) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000693 // Calls are scheduled with their preceding instructions. For bottom-up
694 // scheduling, clear the pipeline state before emitting.
695 HazardRec->Reset();
696 }
697
698 HazardRec->EmitInstruction(SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000699}
700
Andrew Trickb53a00d2011-04-13 00:38:32 +0000701static void resetVRegCycle(SUnit *SU);
702
Dan Gohmanb9543432009-02-10 23:27:53 +0000703/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
704/// count of its predecessors. If a predecessor pending count is zero, add it to
705/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000706void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Andrew Trick1b60ad62011-04-12 20:14:07 +0000707 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000708 DEBUG(SU->dump(this));
709
Evan Chengbdd062d2010-05-20 06:13:19 +0000710#ifndef NDEBUG
711 if (CurCycle < SU->getHeight())
Andrew Trickb53a00d2011-04-13 00:38:32 +0000712 DEBUG(dbgs() << " Height [" << SU->getHeight()
713 << "] pipeline stall!\n");
Evan Chengbdd062d2010-05-20 06:13:19 +0000714#endif
715
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000716 // FIXME: Do not modify node height. It may interfere with
717 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
Eric Christopher1b4b1e52011-03-21 18:06:21 +0000718 // node its ready cycle can aid heuristics, and after scheduling it can
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000719 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000720 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000721
Robert Wilhelmf0cfb832013-09-28 11:46:15 +0000722 // Reserve resources for the scheduled instruction.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000723 EmitNode(SU);
724
Dan Gohmanb9543432009-02-10 23:27:53 +0000725 Sequence.push_back(SU);
726
Andrew Trick52226d42012-03-07 23:00:49 +0000727 AvailableQueue->scheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000728
Andrew Trick641e2d42011-03-05 08:00:22 +0000729 // If HazardRec is disabled, and each inst counts as one cycle, then
Andrew Trickb53a00d2011-04-13 00:38:32 +0000730 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000731 // PendingQueue for schedulers that implement HasReadyFilter.
Andrew Trick641e2d42011-03-05 08:00:22 +0000732 if (!HazardRec->isEnabled() && AvgIPC < 2)
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000733 AdvanceToCycle(CurCycle + 1);
734
Andrew Trick033efdf2010-12-23 03:15:51 +0000735 // Update liveness of predecessors before successors to avoid treating a
736 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000737 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000738
739 // Release all the implicit physical register defs that are live.
740 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
741 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000742 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
743 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
744 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
745 --NumLiveRegs;
Craig Topperc0196b12014-04-14 00:51:57 +0000746 LiveRegDefs[I->getReg()] = nullptr;
747 LiveRegGens[I->getReg()] = nullptr;
Andrew Trick7cf43612013-02-25 19:11:48 +0000748 releaseInterferences(I->getReg());
Evan Cheng5924bf72007-09-25 01:54:36 +0000749 }
750 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000751 // Release the special call resource dependence, if this is the beginning
752 // of a call.
753 unsigned CallResource = TRI->getNumRegs();
754 if (LiveRegDefs[CallResource] == SU)
755 for (const SDNode *SUNode = SU->getNode(); SUNode;
756 SUNode = SUNode->getGluedNode()) {
757 if (SUNode->isMachineOpcode() &&
758 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
759 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
760 --NumLiveRegs;
Craig Topperc0196b12014-04-14 00:51:57 +0000761 LiveRegDefs[CallResource] = nullptr;
762 LiveRegGens[CallResource] = nullptr;
Andrew Trick7cf43612013-02-25 19:11:48 +0000763 releaseInterferences(CallResource);
Dan Gohman198b7ff2011-11-03 21:49:52 +0000764 }
765 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000766
Andrew Trickb53a00d2011-04-13 00:38:32 +0000767 resetVRegCycle(SU);
768
Evan Chengd38c22b2006-05-11 23:55:42 +0000769 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000770
771 // Conditions under which the scheduler should eagerly advance the cycle:
772 // (1) No available instructions
773 // (2) All pipelines full, so available instructions must have hazards.
774 //
Andrew Trickb53a00d2011-04-13 00:38:32 +0000775 // If HazardRec is disabled, the cycle was pre-advanced before calling
776 // ReleasePredecessors. In that case, IssueCount should remain 0.
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000777 //
778 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
Andrew Trickb53a00d2011-04-13 00:38:32 +0000779 if (HazardRec->isEnabled() || AvgIPC > 1) {
780 if (SU->getNode() && SU->getNode()->isMachineOpcode())
781 ++IssueCount;
782 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
783 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
784 AdvanceToCycle(CurCycle + 1);
785 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000786}
787
Evan Cheng5924bf72007-09-25 01:54:36 +0000788/// CapturePred - This does the opposite of ReleasePred. Since SU is being
789/// unscheduled, incrcease the succ left count of its predecessors. Remove
790/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000791void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000792 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000793 if (PredSU->isAvailable) {
794 PredSU->isAvailable = false;
795 if (!PredSU->isPending)
796 AvailableQueue->remove(PredSU);
797 }
798
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000799 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000800 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000801}
802
803/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
804/// its predecessor states to reflect the change.
805void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000806 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000807 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000808
Evan Cheng5924bf72007-09-25 01:54:36 +0000809 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
810 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000811 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000812 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000813 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000814 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000815 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000816 --NumLiveRegs;
Craig Topperc0196b12014-04-14 00:51:57 +0000817 LiveRegDefs[I->getReg()] = nullptr;
818 LiveRegGens[I->getReg()] = nullptr;
Andrew Trick7cf43612013-02-25 19:11:48 +0000819 releaseInterferences(I->getReg());
Evan Cheng5924bf72007-09-25 01:54:36 +0000820 }
821 }
822
Dan Gohman198b7ff2011-11-03 21:49:52 +0000823 // Reclaim the special call resource dependence, if this is the beginning
824 // of a call.
825 unsigned CallResource = TRI->getNumRegs();
826 for (const SDNode *SUNode = SU->getNode(); SUNode;
827 SUNode = SUNode->getGluedNode()) {
828 if (SUNode->isMachineOpcode() &&
829 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
830 ++NumLiveRegs;
831 LiveRegDefs[CallResource] = SU;
Eli Friedmand5c173f2011-12-07 22:24:28 +0000832 LiveRegGens[CallResource] = CallSeqEndForStart[SU];
Dan Gohman198b7ff2011-11-03 21:49:52 +0000833 }
834 }
835
836 // Release the special call resource dependence, if this is the end
837 // of a call.
838 if (LiveRegGens[CallResource] == SU)
839 for (const SDNode *SUNode = SU->getNode(); SUNode;
840 SUNode = SUNode->getGluedNode()) {
841 if (SUNode->isMachineOpcode() &&
842 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
843 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
844 --NumLiveRegs;
Craig Topperc0196b12014-04-14 00:51:57 +0000845 LiveRegDefs[CallResource] = nullptr;
846 LiveRegGens[CallResource] = nullptr;
Andrew Trick7cf43612013-02-25 19:11:48 +0000847 releaseInterferences(CallResource);
Dan Gohman198b7ff2011-11-03 21:49:52 +0000848 }
849 }
850
Pawel Bylicacc358122015-06-24 12:49:42 +0000851 for (auto &Succ : SU->Succs) {
852 if (Succ.isAssignedRegDep()) {
853 auto Reg = Succ.getReg();
854 if (!LiveRegDefs[Reg])
Eli Friedman0bdc0832011-12-07 22:06:02 +0000855 ++NumLiveRegs;
Andrew Trick033efdf2010-12-23 03:15:51 +0000856 // This becomes the nearest def. Note that an earlier def may still be
857 // pending if this is a two-address node.
Pawel Bylicacc358122015-06-24 12:49:42 +0000858 LiveRegDefs[Reg] = SU;
859
860 // Update LiveRegGen only if was empty before this unscheduling.
861 // This is to avoid incorrect updating LiveRegGen set in previous run.
862 if (!LiveRegGens[Reg]) {
863 // Find the successor with the lowest height.
864 LiveRegGens[Reg] = Succ.getSUnit();
865 for (auto &Succ2 : SU->Succs) {
866 if (Succ2.isAssignedRegDep() && Succ2.getReg() == Reg &&
867 Succ2.getSUnit()->getHeight() < LiveRegGens[Reg]->getHeight())
868 LiveRegGens[Reg] = Succ2.getSUnit();
869 }
870 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000871 }
872 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000873 if (SU->getHeight() < MinAvailableCycle)
874 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000875
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000876 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000877 SU->isScheduled = false;
878 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000879 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000880 // Don't make available until backtracking is complete.
881 SU->isPending = true;
882 PendingQueue.push_back(SU);
883 }
884 else {
885 AvailableQueue->push(SU);
886 }
Andrew Trick52226d42012-03-07 23:00:49 +0000887 AvailableQueue->unscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000888}
889
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000890/// After backtracking, the hazard checker needs to be restored to a state
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000891/// corresponding the current cycle.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000892void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
893 HazardRec->Reset();
894
895 unsigned LookAhead = std::min((unsigned)Sequence.size(),
896 HazardRec->getMaxLookAhead());
897 if (LookAhead == 0)
898 return;
899
900 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
901 unsigned HazardCycle = (*I)->getHeight();
902 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
903 SUnit *SU = *I;
904 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
905 HazardRec->RecedeCycle();
906 }
907 EmitNode(SU);
908 }
909}
910
Evan Cheng8e136a92007-09-26 21:36:17 +0000911/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000912/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000913void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
914 SUnit *OldSU = Sequence.back();
915 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000916 Sequence.pop_back();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000917 // FIXME: use ready cycle instead of height
918 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000919 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000920 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000921 if (OldSU == BtSU)
922 break;
923 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000924 }
925
Dan Gohman60d68442009-01-29 19:49:27 +0000926 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000927
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000928 RestoreHazardCheckerBottomUp();
929
Andrew Trick5ce945c2010-12-24 07:10:19 +0000930 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000931
Evan Cheng1ec79b42007-09-27 07:09:03 +0000932 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000933}
934
Evan Cheng3b245872010-02-05 01:27:11 +0000935static bool isOperandOf(const SUnit *SU, SDNode *N) {
936 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000937 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000938 if (SUNode->isOperandOf(N))
939 return true;
940 }
941 return false;
942}
943
Evan Cheng5924bf72007-09-25 01:54:36 +0000944/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
945/// successors to the newly created node.
946SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000947 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000948 if (!N)
Craig Topperc0196b12014-04-14 00:51:57 +0000949 return nullptr;
Evan Cheng79e97132007-10-05 01:39:18 +0000950
Andrew Trickc9405662010-12-24 06:46:50 +0000951 if (SU->getNode()->getGluedNode())
Craig Topperc0196b12014-04-14 00:51:57 +0000952 return nullptr;
Andrew Trickc9405662010-12-24 06:46:50 +0000953
Evan Cheng79e97132007-10-05 01:39:18 +0000954 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000955 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000956 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Craig Topper7f416c82014-11-16 21:17:18 +0000957 MVT VT = N->getSimpleValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000958 if (VT == MVT::Glue)
Craig Topperc0196b12014-04-14 00:51:57 +0000959 return nullptr;
Owen Anderson9f944592009-08-11 20:47:22 +0000960 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000961 TryUnfold = true;
962 }
Pete Cooper9271ccc2015-06-26 19:18:49 +0000963 for (const SDValue &Op : N->op_values()) {
Craig Topper7f416c82014-11-16 21:17:18 +0000964 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000965 if (VT == MVT::Glue)
Craig Topperc0196b12014-04-14 00:51:57 +0000966 return nullptr;
Evan Cheng79e97132007-10-05 01:39:18 +0000967 }
968
969 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000970 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000971 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Craig Topperc0196b12014-04-14 00:51:57 +0000972 return nullptr;
Evan Cheng79e97132007-10-05 01:39:18 +0000973
Pete Cooper7c7ba1b2011-11-15 21:57:53 +0000974 // unfolding an x86 DEC64m operation results in store, dec, load which
975 // can't be handled here so quit
976 if (NewNodes.size() == 3)
Craig Topperc0196b12014-04-14 00:51:57 +0000977 return nullptr;
Pete Cooper7c7ba1b2011-11-15 21:57:53 +0000978
Evan Chengbdd062d2010-05-20 06:13:19 +0000979 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000980 assert(NewNodes.size() == 2 && "Expected a load folding node!");
981
982 N = NewNodes[1];
983 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000984 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000985 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000986 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000987 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
988 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000989 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000990
Dan Gohmane52e0892008-11-11 21:34:44 +0000991 // LoadNode may already exist. This can happen when there is another
992 // load from the same location and producing the same type of value
993 // but it has different alignment or volatileness.
994 bool isNewLoad = true;
995 SUnit *LoadSU;
996 if (LoadNode->getNodeId() != -1) {
997 LoadSU = &SUnits[LoadNode->getNodeId()];
998 isNewLoad = false;
999 } else {
1000 LoadSU = CreateNewSUnit(LoadNode);
1001 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001002
1003 InitNumRegDefsLeft(LoadSU);
Andrew Trick52226d42012-03-07 23:00:49 +00001004 computeLatency(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +00001005 }
1006
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001007 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +00001008 assert(N->getNodeId() == -1 && "Node already inserted!");
1009 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +00001010
Evan Cheng6cc775f2011-06-28 19:10:37 +00001011 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1012 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
1013 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +00001014 NewSU->isTwoAddress = true;
1015 break;
1016 }
1017 }
Evan Cheng6cc775f2011-06-28 19:10:37 +00001018 if (MCID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +00001019 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +00001020
1021 InitNumRegDefsLeft(NewSU);
Andrew Trick52226d42012-03-07 23:00:49 +00001022 computeLatency(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +00001023
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001024 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +00001025 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +00001026 SmallVector<SDep, 4> ChainSuccs;
1027 SmallVector<SDep, 4> LoadPreds;
1028 SmallVector<SDep, 4> NodePreds;
1029 SmallVector<SDep, 4> NodeSuccs;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001030 for (SDep &Pred : SU->Preds) {
1031 if (Pred.isCtrl())
1032 ChainPreds.push_back(Pred);
1033 else if (isOperandOf(Pred.getSUnit(), LoadNode))
1034 LoadPreds.push_back(Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001035 else
Sanjay Patele9fa3362016-02-03 22:44:14 +00001036 NodePreds.push_back(Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001037 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001038 for (SDep &Succ : SU->Succs) {
1039 if (Succ.isCtrl())
1040 ChainSuccs.push_back(Succ);
Evan Cheng79e97132007-10-05 01:39:18 +00001041 else
Sanjay Patele9fa3362016-02-03 22:44:14 +00001042 NodeSuccs.push_back(Succ);
Evan Cheng79e97132007-10-05 01:39:18 +00001043 }
1044
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001045 // Now assign edges to the newly-created nodes.
Sanjay Patele9fa3362016-02-03 22:44:14 +00001046 for (const SDep &Pred : ChainPreds) {
Dan Gohman15af5522009-03-06 02:23:01 +00001047 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +00001048 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +00001049 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001050 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001051 for (const SDep &Pred : LoadPreds) {
Dan Gohman2d170892008-12-09 22:54:47 +00001052 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +00001053 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +00001054 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001055 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001056 for (const SDep &Pred : NodePreds) {
Dan Gohman2d170892008-12-09 22:54:47 +00001057 RemovePred(SU, Pred);
1058 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001059 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001060 for (SDep D : NodeSuccs) {
Dan Gohman2d170892008-12-09 22:54:47 +00001061 SUnit *SuccDep = D.getSUnit();
1062 D.setSUnit(SU);
1063 RemovePred(SuccDep, D);
1064 D.setSUnit(NewSU);
1065 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001066 // Balance register pressure.
1067 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1068 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1069 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +00001070 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001071 for (SDep D : ChainSuccs) {
Dan Gohman2d170892008-12-09 22:54:47 +00001072 SUnit *SuccDep = D.getSUnit();
1073 D.setSUnit(SU);
1074 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001075 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +00001076 D.setSUnit(LoadSU);
1077 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001078 }
Andrew Trick2085a962010-12-21 22:25:04 +00001079 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001080
1081 // Add a data dependency to reflect that NewSU reads the value defined
1082 // by LoadSU.
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001083 SDep D(LoadSU, SDep::Data, 0);
1084 D.setLatency(LoadSU->Latency);
1085 AddPred(NewSU, D);
Evan Cheng79e97132007-10-05 01:39:18 +00001086
Evan Cheng91e0fc92007-12-18 08:42:10 +00001087 if (isNewLoad)
1088 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +00001089 AvailableQueue->addNode(NewSU);
1090
1091 ++NumUnfolds;
1092
1093 if (NewSU->NumSuccsLeft == 0) {
1094 NewSU->isAvailable = true;
1095 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +00001096 }
1097 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +00001098 }
1099
Evan Chengbdd062d2010-05-20 06:13:19 +00001100 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001101 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +00001102
1103 // New SUnit has the exact same predecessors.
Sanjay Patele9fa3362016-02-03 22:44:14 +00001104 for (SDep &Pred : SU->Preds)
1105 if (!Pred.isArtificial())
1106 AddPred(NewSU, Pred);
Evan Cheng5924bf72007-09-25 01:54:36 +00001107
1108 // Only copy scheduled successors. Cut them from old node's successor
1109 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001110 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001111 for (SDep &Succ : SU->Succs) {
1112 if (Succ.isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +00001113 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001114 SUnit *SuccSU = Succ.getSUnit();
Dan Gohman2d170892008-12-09 22:54:47 +00001115 if (SuccSU->isScheduled) {
Sanjay Patele9fa3362016-02-03 22:44:14 +00001116 SDep D = Succ;
Dan Gohman2d170892008-12-09 22:54:47 +00001117 D.setSUnit(NewSU);
1118 AddPred(SuccSU, D);
1119 D.setSUnit(SU);
1120 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +00001121 }
1122 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001123 for (auto &DelDep : DelDeps)
1124 RemovePred(DelDep.first, DelDep.second);
Evan Cheng5924bf72007-09-25 01:54:36 +00001125
1126 AvailableQueue->updateNode(SU);
1127 AvailableQueue->addNode(NewSU);
1128
Evan Cheng1ec79b42007-09-27 07:09:03 +00001129 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +00001130 return NewSU;
1131}
1132
Evan Chengb2c42c62009-01-12 03:19:55 +00001133/// InsertCopiesAndMoveSuccs - Insert register copies and move all
1134/// scheduled successors of the given SUnit to the last copy.
1135void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
Craig Topperb94011f2013-07-14 04:42:23 +00001136 const TargetRegisterClass *DestRC,
1137 const TargetRegisterClass *SrcRC,
1138 SmallVectorImpl<SUnit*> &Copies) {
Craig Topperc0196b12014-04-14 00:51:57 +00001139 SUnit *CopyFromSU = CreateNewSUnit(nullptr);
Evan Cheng8e136a92007-09-26 21:36:17 +00001140 CopyFromSU->CopySrcRC = SrcRC;
1141 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +00001142
Craig Topperc0196b12014-04-14 00:51:57 +00001143 SUnit *CopyToSU = CreateNewSUnit(nullptr);
Evan Cheng8e136a92007-09-26 21:36:17 +00001144 CopyToSU->CopySrcRC = DestRC;
1145 CopyToSU->CopyDstRC = SrcRC;
1146
1147 // Only copy scheduled successors. Cut them from old node's successor
1148 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001149 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001150 for (SDep &Succ : SU->Succs) {
1151 if (Succ.isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +00001152 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001153 SUnit *SuccSU = Succ.getSUnit();
Dan Gohman2d170892008-12-09 22:54:47 +00001154 if (SuccSU->isScheduled) {
Sanjay Patele9fa3362016-02-03 22:44:14 +00001155 SDep D = Succ;
Dan Gohman2d170892008-12-09 22:54:47 +00001156 D.setSUnit(CopyToSU);
1157 AddPred(SuccSU, D);
Sanjay Patele9fa3362016-02-03 22:44:14 +00001158 DelDeps.push_back(std::make_pair(SuccSU, Succ));
Evan Cheng8e136a92007-09-26 21:36:17 +00001159 }
Andrew Trick13acae02011-03-23 20:42:39 +00001160 else {
1161 // Avoid scheduling the def-side copy before other successors. Otherwise
1162 // we could introduce another physreg interference on the copy and
1163 // continue inserting copies indefinitely.
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001164 AddPred(SuccSU, SDep(CopyFromSU, SDep::Artificial));
Andrew Trick13acae02011-03-23 20:42:39 +00001165 }
Evan Cheng8e136a92007-09-26 21:36:17 +00001166 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001167 for (auto &DelDep : DelDeps)
1168 RemovePred(DelDep.first, DelDep.second);
Evan Cheng8e136a92007-09-26 21:36:17 +00001169
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001170 SDep FromDep(SU, SDep::Data, Reg);
1171 FromDep.setLatency(SU->Latency);
1172 AddPred(CopyFromSU, FromDep);
1173 SDep ToDep(CopyFromSU, SDep::Data, 0);
1174 ToDep.setLatency(CopyFromSU->Latency);
1175 AddPred(CopyToSU, ToDep);
Evan Cheng8e136a92007-09-26 21:36:17 +00001176
1177 AvailableQueue->updateNode(SU);
1178 AvailableQueue->addNode(CopyFromSU);
1179 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001180 Copies.push_back(CopyFromSU);
1181 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +00001182
Evan Chengb2c42c62009-01-12 03:19:55 +00001183 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +00001184}
1185
1186/// getPhysicalRegisterVT - Returns the ValueType of the physical register
1187/// definition of the specified node.
1188/// FIXME: Move to SelectionDAG?
Craig Topper7f416c82014-11-16 21:17:18 +00001189static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +00001190 const TargetInstrInfo *TII) {
Tim Northovere4c7be52014-10-23 22:31:48 +00001191 unsigned NumRes;
1192 if (N->getOpcode() == ISD::CopyFromReg) {
1193 // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
1194 NumRes = 1;
1195 } else {
1196 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1197 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1198 NumRes = MCID.getNumDefs();
Craig Toppere5e035a32015-12-05 07:13:35 +00001199 for (const MCPhysReg *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Tim Northovere4c7be52014-10-23 22:31:48 +00001200 if (Reg == *ImpDef)
1201 break;
1202 ++NumRes;
1203 }
Evan Cheng8e136a92007-09-26 21:36:17 +00001204 }
Craig Topper7f416c82014-11-16 21:17:18 +00001205 return N->getSimpleValueType(NumRes);
Evan Cheng8e136a92007-09-26 21:36:17 +00001206}
1207
Evan Chengb8905c42009-03-04 01:41:49 +00001208/// CheckForLiveRegDef - Return true and update live register vector if the
1209/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001210static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Fiona Glasere25b06f2015-12-02 18:32:59 +00001211 SUnit **LiveRegDefs,
Evan Chengb8905c42009-03-04 01:41:49 +00001212 SmallSet<unsigned, 4> &RegAdded,
Craig Topperb94011f2013-07-14 04:42:23 +00001213 SmallVectorImpl<unsigned> &LRegs,
Evan Chengb8905c42009-03-04 01:41:49 +00001214 const TargetRegisterInfo *TRI) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001215 for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
Andrew Trick12acde112010-12-23 03:43:21 +00001216
1217 // Check if Ref is live.
Andrew Trick0af2e472011-06-07 00:38:12 +00001218 if (!LiveRegDefs[*AliasI]) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001219
1220 // Allow multiple uses of the same def.
Andrew Trick0af2e472011-06-07 00:38:12 +00001221 if (LiveRegDefs[*AliasI] == SU) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001222
1223 // Add Reg to the set of interfering live regs.
David Blaikie70573dc2014-11-19 07:49:26 +00001224 if (RegAdded.insert(*AliasI).second) {
Andrew Trick0af2e472011-06-07 00:38:12 +00001225 LRegs.push_back(*AliasI);
1226 }
Evan Chengb8905c42009-03-04 01:41:49 +00001227 }
Evan Chengb8905c42009-03-04 01:41:49 +00001228}
1229
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001230/// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1231/// by RegMask, and add them to LRegs.
1232static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
Fiona Glasere25b06f2015-12-02 18:32:59 +00001233 ArrayRef<SUnit*> LiveRegDefs,
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001234 SmallSet<unsigned, 4> &RegAdded,
Craig Topperb94011f2013-07-14 04:42:23 +00001235 SmallVectorImpl<unsigned> &LRegs) {
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001236 // Look at all live registers. Skip Reg0 and the special CallResource.
Fiona Glaser1075f632015-12-02 18:46:23 +00001237 for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001238 if (!LiveRegDefs[i]) continue;
1239 if (LiveRegDefs[i] == SU) continue;
1240 if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
David Blaikie70573dc2014-11-19 07:49:26 +00001241 if (RegAdded.insert(i).second)
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001242 LRegs.push_back(i);
1243 }
1244}
1245
1246/// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1247static const uint32_t *getNodeRegMask(const SDNode *N) {
Pete Cooper9271ccc2015-06-26 19:18:49 +00001248 for (const SDValue &Op : N->op_values())
1249 if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode()))
1250 return RegOp->getRegMask();
Craig Topperc0196b12014-04-14 00:51:57 +00001251 return nullptr;
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001252}
1253
Evan Cheng5924bf72007-09-25 01:54:36 +00001254/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1255/// scheduling of the given node to satisfy live physical register dependencies.
1256/// If the specific node is the last one that's available to schedule, do
1257/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001258bool ScheduleDAGRRList::
Craig Topperb94011f2013-07-14 04:42:23 +00001259DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +00001260 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +00001261 return false;
1262
Evan Chenge6f92252007-09-27 18:46:06 +00001263 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +00001264 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001265 //
1266 // If SU is the currently live definition of the same register that it uses,
1267 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +00001268 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1269 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001270 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Fiona Glasere25b06f2015-12-02 18:32:59 +00001271 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs.get(),
Evan Chengb8905c42009-03-04 01:41:49 +00001272 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001273 }
1274
Chris Lattner11a33812010-12-23 17:24:32 +00001275 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +00001276 if (Node->getOpcode() == ISD::INLINEASM) {
1277 // Inline asm can clobber physical defs.
1278 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001279 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +00001280 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +00001281
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001282 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +00001283 unsigned Flags =
1284 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001285 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +00001286
1287 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001288 if (InlineAsm::isRegDefKind(Flags) ||
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00001289 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1290 InlineAsm::isClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +00001291 // Check for def of register or earlyclobber register.
1292 for (; NumVals; --NumVals, ++i) {
1293 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1294 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Fiona Glasere25b06f2015-12-02 18:32:59 +00001295 CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
Evan Chengb8905c42009-03-04 01:41:49 +00001296 }
1297 } else
1298 i += NumVals;
1299 }
1300 continue;
1301 }
1302
Dan Gohman072734e2008-11-13 23:24:17 +00001303 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +00001304 continue;
Dan Gohman198b7ff2011-11-03 21:49:52 +00001305 // If we're in the middle of scheduling a call, don't begin scheduling
1306 // another call. Also, don't allow any physical registers to be live across
1307 // the call.
1308 if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
1309 // Check the special calling-sequence resource.
1310 unsigned CallResource = TRI->getNumRegs();
1311 if (LiveRegDefs[CallResource]) {
1312 SDNode *Gen = LiveRegGens[CallResource]->getNode();
1313 while (SDNode *Glued = Gen->getGluedNode())
1314 Gen = Glued;
David Blaikie70573dc2014-11-19 07:49:26 +00001315 if (!IsChainDependent(Gen, Node, 0, TII) &&
1316 RegAdded.insert(CallResource).second)
Dan Gohman198b7ff2011-11-03 21:49:52 +00001317 LRegs.push_back(CallResource);
1318 }
1319 }
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001320 if (const uint32_t *RegMask = getNodeRegMask(Node))
Fiona Glasere25b06f2015-12-02 18:32:59 +00001321 CheckForLiveRegDefMasked(SU, RegMask,
1322 makeArrayRef(LiveRegDefs.get(), TRI->getNumRegs()),
1323 RegAdded, LRegs);
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001324
Evan Cheng6cc775f2011-06-28 19:10:37 +00001325 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1326 if (!MCID.ImplicitDefs)
Evan Cheng5924bf72007-09-25 01:54:36 +00001327 continue;
Craig Toppere5e035a32015-12-05 07:13:35 +00001328 for (const MCPhysReg *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
Fiona Glasere25b06f2015-12-02 18:32:59 +00001329 CheckForLiveRegDef(SU, *Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001330 }
Andrew Trick2085a962010-12-21 22:25:04 +00001331
Evan Cheng5924bf72007-09-25 01:54:36 +00001332 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +00001333}
1334
Andrew Trick7cf43612013-02-25 19:11:48 +00001335void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
1336 // Add the nodes that aren't ready back onto the available list.
1337 for (unsigned i = Interferences.size(); i > 0; --i) {
1338 SUnit *SU = Interferences[i-1];
1339 LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
1340 if (Reg) {
Craig Topperb94011f2013-07-14 04:42:23 +00001341 SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
David Majnemer0d955d02016-08-11 22:21:41 +00001342 if (!is_contained(LRegs, Reg))
Andrew Trick7cf43612013-02-25 19:11:48 +00001343 continue;
1344 }
1345 SU->isPending = false;
1346 // The interfering node may no longer be available due to backtracking.
1347 // Furthermore, it may have been made available again, in which case it is
1348 // now already in the AvailableQueue.
1349 if (SU->isAvailable && !SU->NodeQueueId) {
1350 DEBUG(dbgs() << " Repushing SU #" << SU->NodeNum << '\n');
1351 AvailableQueue->push(SU);
1352 }
1353 if (i < Interferences.size())
1354 Interferences[i-1] = Interferences.back();
1355 Interferences.pop_back();
1356 LRegsMap.erase(LRegsPos);
1357 }
1358}
1359
Andrew Trick528fad92010-12-23 05:42:20 +00001360/// Return a node that can be scheduled in this cycle. Requirements:
1361/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001362/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +00001363/// (3) No Interferences: may unschedule to break register interferences.
1364SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
Craig Topperc0196b12014-04-14 00:51:57 +00001365 SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
Andrew Trick528fad92010-12-23 05:42:20 +00001366 while (CurSU) {
1367 SmallVector<unsigned, 4> LRegs;
1368 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1369 break;
Andrew Trick0f23b762013-03-07 19:21:08 +00001370 DEBUG(dbgs() << " Interfering reg " <<
1371 (LRegs[0] == TRI->getNumRegs() ? "CallResource"
1372 : TRI->getName(LRegs[0]))
1373 << " SU #" << CurSU->NodeNum << '\n');
Andrew Trick7cf43612013-02-25 19:11:48 +00001374 std::pair<LRegsMapT::iterator, bool> LRegsPair =
1375 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1376 if (LRegsPair.second) {
1377 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1378 Interferences.push_back(CurSU);
1379 }
1380 else {
Sanjay Patelb49bf162014-07-14 18:21:07 +00001381 assert(CurSU->isPending && "Interferences are pending");
Andrew Trick7cf43612013-02-25 19:11:48 +00001382 // Update the interference with current live regs.
1383 LRegsPair.first->second = LRegs;
1384 }
Andrew Trick528fad92010-12-23 05:42:20 +00001385 CurSU = AvailableQueue->pop();
1386 }
Andrew Trick7cf43612013-02-25 19:11:48 +00001387 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001388 return CurSU;
Andrew Trick528fad92010-12-23 05:42:20 +00001389
1390 // All candidates are delayed due to live physical reg dependencies.
1391 // Try backtracking, code duplication, or inserting cross class copies
1392 // to resolve it.
Sanjay Patele9fa3362016-02-03 22:44:14 +00001393 for (SUnit *TrySU : Interferences) {
Craig Topperb94011f2013-07-14 04:42:23 +00001394 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
Andrew Trick528fad92010-12-23 05:42:20 +00001395
1396 // Try unscheduling up to the point where it's safe to schedule
1397 // this node.
Craig Topperc0196b12014-04-14 00:51:57 +00001398 SUnit *BtSU = nullptr;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001399 unsigned LiveCycle = UINT_MAX;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001400 for (unsigned Reg : LRegs) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001401 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1402 BtSU = LiveRegGens[Reg];
1403 LiveCycle = BtSU->getHeight();
1404 }
Andrew Trick528fad92010-12-23 05:42:20 +00001405 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001406 if (!WillCreateCycle(TrySU, BtSU)) {
Andrew Trick7cf43612013-02-25 19:11:48 +00001407 // BacktrackBottomUp mutates Interferences!
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001408 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001409
1410 // Force the current node to be scheduled before the node that
1411 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001412 if (BtSU->isAvailable) {
1413 BtSU->isAvailable = false;
1414 if (!BtSU->isPending)
1415 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001416 }
Andrew Trick7cf43612013-02-25 19:11:48 +00001417 DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU("
1418 << TrySU->NodeNum << ")\n");
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001419 AddPred(TrySU, SDep(BtSU, SDep::Artificial));
Andrew Trick528fad92010-12-23 05:42:20 +00001420
1421 // If one or more successors has been unscheduled, then the current
Andrew Trick7cf43612013-02-25 19:11:48 +00001422 // node is no longer available.
Andrew Tricke97ff5a2015-03-27 03:44:13 +00001423 if (!TrySU->isAvailable || !TrySU->NodeQueueId)
Andrew Trick528fad92010-12-23 05:42:20 +00001424 CurSU = AvailableQueue->pop();
Andrew Trick528fad92010-12-23 05:42:20 +00001425 else {
Andrew Tricke97ff5a2015-03-27 03:44:13 +00001426 // Available and in AvailableQueue
Andrew Trick7cf43612013-02-25 19:11:48 +00001427 AvailableQueue->remove(TrySU);
Andrew Trick528fad92010-12-23 05:42:20 +00001428 CurSU = TrySU;
Andrew Trick528fad92010-12-23 05:42:20 +00001429 }
Andrew Trick7cf43612013-02-25 19:11:48 +00001430 // Interferences has been mutated. We must break.
Andrew Trick528fad92010-12-23 05:42:20 +00001431 break;
1432 }
1433 }
1434
1435 if (!CurSU) {
1436 // Can't backtrack. If it's too expensive to copy the value, then try
1437 // duplicate the nodes that produces these "too expensive to copy"
1438 // values to break the dependency. In case even that doesn't work,
1439 // insert cross class copies.
1440 // If it's not too expensive, i.e. cost != -1, issue copies.
1441 SUnit *TrySU = Interferences[0];
Craig Topperb94011f2013-07-14 04:42:23 +00001442 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
Andrew Trick528fad92010-12-23 05:42:20 +00001443 assert(LRegs.size() == 1 && "Can't handle this yet!");
1444 unsigned Reg = LRegs[0];
1445 SUnit *LRDef = LiveRegDefs[Reg];
Craig Topper7f416c82014-11-16 21:17:18 +00001446 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
Andrew Trick528fad92010-12-23 05:42:20 +00001447 const TargetRegisterClass *RC =
1448 TRI->getMinimalPhysRegClass(Reg, VT);
1449 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1450
Evan Chengb4c6a342011-03-10 00:16:32 +00001451 // If cross copy register class is the same as RC, then it must be possible
1452 // copy the value directly. Do not try duplicate the def.
1453 // If cross copy register class is not the same as RC, then it's possible to
1454 // copy the value but it require cross register class copies and it is
1455 // expensive.
1456 // If cross copy register class is null, then it's not possible to copy
1457 // the value at all.
Craig Topperc0196b12014-04-14 00:51:57 +00001458 SUnit *NewDef = nullptr;
Evan Chengb4c6a342011-03-10 00:16:32 +00001459 if (DestRC != RC) {
Andrew Trick528fad92010-12-23 05:42:20 +00001460 NewDef = CopyAndMoveSuccessors(LRDef);
Evan Chengb4c6a342011-03-10 00:16:32 +00001461 if (!DestRC && !NewDef)
1462 report_fatal_error("Can't handle live physical register dependency!");
1463 }
Andrew Trick528fad92010-12-23 05:42:20 +00001464 if (!NewDef) {
1465 // Issue copies, these can be expensive cross register class copies.
1466 SmallVector<SUnit*, 2> Copies;
1467 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1468 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1469 << " to SU #" << Copies.front()->NodeNum << "\n");
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001470 AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
Andrew Trick528fad92010-12-23 05:42:20 +00001471 NewDef = Copies.back();
1472 }
1473
1474 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1475 << " to SU #" << TrySU->NodeNum << "\n");
1476 LiveRegDefs[Reg] = NewDef;
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001477 AddPred(NewDef, SDep(TrySU, SDep::Artificial));
Andrew Trick528fad92010-12-23 05:42:20 +00001478 TrySU->isAvailable = false;
1479 CurSU = NewDef;
1480 }
Andrew Trick528fad92010-12-23 05:42:20 +00001481 assert(CurSU && "Unable to resolve live physical register dependencies!");
Andrew Trick528fad92010-12-23 05:42:20 +00001482 return CurSU;
1483}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001484
Evan Chengd38c22b2006-05-11 23:55:42 +00001485/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1486/// schedulers.
1487void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001488 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001489 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001490
Evan Chengd38c22b2006-05-11 23:55:42 +00001491 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001492 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001493 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001494 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1495 RootSU->isAvailable = true;
1496 AvailableQueue->push(RootSU);
1497 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001498
1499 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001500 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001501 Sequence.reserve(SUnits.size());
Andrew Trick7cf43612013-02-25 19:11:48 +00001502 while (!AvailableQueue->empty() || !Interferences.empty()) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00001503 DEBUG(dbgs() << "\nExamining Available:\n";
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001504 AvailableQueue->dump(this));
1505
Andrew Trick528fad92010-12-23 05:42:20 +00001506 // Pick the best node to schedule taking all constraints into
1507 // consideration.
1508 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001509
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001510 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001511
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001512 ScheduleNodeBottomUp(SU);
1513
1514 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1515 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1516 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1517 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1518 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001519 }
1520
Evan Chengd38c22b2006-05-11 23:55:42 +00001521 // Reverse the order if it is bottom up.
1522 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001523
Evan Chengd38c22b2006-05-11 23:55:42 +00001524#ifndef NDEBUG
Andrew Trick46a58662012-03-07 05:21:36 +00001525 VerifyScheduledSequence(/*isBottomUp=*/true);
Evan Chengd38c22b2006-05-11 23:55:42 +00001526#endif
1527}
1528
1529//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001530// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001531//===----------------------------------------------------------------------===//
1532//
1533// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1534// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001535//
Evan Chengd38c22b2006-05-11 23:55:42 +00001536namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001537class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001538
Andrew Trick9ccce772011-01-14 21:11:41 +00001539struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1540 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1541};
1542
Andrew Trick3013b6a2011-06-15 17:16:12 +00001543#ifndef NDEBUG
1544template<class SF>
1545struct reverse_sort : public queue_sort {
1546 SF &SortFunc;
1547 reverse_sort(SF &sf) : SortFunc(sf) {}
Andrew Trick3013b6a2011-06-15 17:16:12 +00001548
1549 bool operator()(SUnit* left, SUnit* right) const {
1550 // reverse left/right rather than simply !SortFunc(left, right)
1551 // to expose different paths in the comparison logic.
1552 return SortFunc(right, left);
1553 }
1554};
1555#endif // NDEBUG
1556
Andrew Trick9ccce772011-01-14 21:11:41 +00001557/// bu_ls_rr_sort - Priority function for bottom up register pressure
1558// reduction scheduler.
1559struct bu_ls_rr_sort : public queue_sort {
1560 enum {
1561 IsBottomUp = true,
1562 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001563 };
1564
Andrew Trick9ccce772011-01-14 21:11:41 +00001565 RegReductionPQBase *SPQ;
1566 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001567
Andrew Trick9ccce772011-01-14 21:11:41 +00001568 bool operator()(SUnit* left, SUnit* right) const;
1569};
Andrew Trick2085a962010-12-21 22:25:04 +00001570
Andrew Trick9ccce772011-01-14 21:11:41 +00001571// src_ls_rr_sort - Priority function for source order scheduler.
1572struct src_ls_rr_sort : public queue_sort {
1573 enum {
1574 IsBottomUp = true,
1575 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001576 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001577
Andrew Trick9ccce772011-01-14 21:11:41 +00001578 RegReductionPQBase *SPQ;
1579 src_ls_rr_sort(RegReductionPQBase *spq)
1580 : SPQ(spq) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001581
Andrew Trick9ccce772011-01-14 21:11:41 +00001582 bool operator()(SUnit* left, SUnit* right) const;
1583};
Andrew Trick2085a962010-12-21 22:25:04 +00001584
Andrew Trick9ccce772011-01-14 21:11:41 +00001585// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1586struct hybrid_ls_rr_sort : public queue_sort {
1587 enum {
1588 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001589 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001590 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001591
Andrew Trick9ccce772011-01-14 21:11:41 +00001592 RegReductionPQBase *SPQ;
1593 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1594 : SPQ(spq) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001595
Andrew Trick9ccce772011-01-14 21:11:41 +00001596 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001597
Andrew Trick9ccce772011-01-14 21:11:41 +00001598 bool operator()(SUnit* left, SUnit* right) const;
1599};
1600
1601// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1602// scheduler.
1603struct ilp_ls_rr_sort : public queue_sort {
1604 enum {
1605 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001606 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001607 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001608
Andrew Trick9ccce772011-01-14 21:11:41 +00001609 RegReductionPQBase *SPQ;
1610 ilp_ls_rr_sort(RegReductionPQBase *spq)
1611 : SPQ(spq) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001612
Andrew Trick9ccce772011-01-14 21:11:41 +00001613 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001614
Andrew Trick9ccce772011-01-14 21:11:41 +00001615 bool operator()(SUnit* left, SUnit* right) const;
1616};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001617
Andrew Trick9ccce772011-01-14 21:11:41 +00001618class RegReductionPQBase : public SchedulingPriorityQueue {
1619protected:
1620 std::vector<SUnit*> Queue;
1621 unsigned CurQueueId;
1622 bool TracksRegPressure;
Evan Cheng8ab58a22012-03-22 19:31:17 +00001623 bool SrcOrder;
Andrew Trick9ccce772011-01-14 21:11:41 +00001624
1625 // SUnits - The SUnits for the current graph.
1626 std::vector<SUnit> *SUnits;
1627
1628 MachineFunction &MF;
1629 const TargetInstrInfo *TII;
1630 const TargetRegisterInfo *TRI;
1631 const TargetLowering *TLI;
1632 ScheduleDAGRRList *scheduleDAG;
1633
1634 // SethiUllmanNumbers - The SethiUllman number for each node.
1635 std::vector<unsigned> SethiUllmanNumbers;
1636
1637 /// RegPressure - Tracking current reg pressure per register class.
1638 ///
1639 std::vector<unsigned> RegPressure;
1640
1641 /// RegLimit - Tracking the number of allocatable registers per register
1642 /// class.
1643 std::vector<unsigned> RegLimit;
1644
1645public:
1646 RegReductionPQBase(MachineFunction &mf,
1647 bool hasReadyFilter,
1648 bool tracksrp,
Evan Cheng8ab58a22012-03-22 19:31:17 +00001649 bool srcorder,
Andrew Trick9ccce772011-01-14 21:11:41 +00001650 const TargetInstrInfo *tii,
1651 const TargetRegisterInfo *tri,
1652 const TargetLowering *tli)
1653 : SchedulingPriorityQueue(hasReadyFilter),
Evan Cheng8ab58a22012-03-22 19:31:17 +00001654 CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
Craig Topperc0196b12014-04-14 00:51:57 +00001655 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001656 if (TracksRegPressure) {
1657 unsigned NumRC = TRI->getNumRegClasses();
1658 RegLimit.resize(NumRC);
1659 RegPressure.resize(NumRC);
1660 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1661 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Krzysztof Parzyszekee9aa3f2017-01-25 19:29:04 +00001662 for (const TargetRegisterClass *RC : TRI->regclasses())
1663 RegLimit[RC->getID()] = tri->getRegPressureLimit(RC, MF);
Andrew Trick9ccce772011-01-14 21:11:41 +00001664 }
1665 }
1666
1667 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1668 scheduleDAG = scheduleDag;
1669 }
1670
1671 ScheduleHazardRecognizer* getHazardRec() {
1672 return scheduleDAG->getHazardRec();
1673 }
1674
Craig Topper7b883b32014-03-08 06:31:39 +00001675 void initNodes(std::vector<SUnit> &sunits) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001676
Craig Topper7b883b32014-03-08 06:31:39 +00001677 void addNode(const SUnit *SU) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001678
Craig Topper7b883b32014-03-08 06:31:39 +00001679 void updateNode(const SUnit *SU) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001680
Craig Topper7b883b32014-03-08 06:31:39 +00001681 void releaseState() override {
Craig Topperc0196b12014-04-14 00:51:57 +00001682 SUnits = nullptr;
Andrew Trick9ccce772011-01-14 21:11:41 +00001683 SethiUllmanNumbers.clear();
1684 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1685 }
1686
1687 unsigned getNodePriority(const SUnit *SU) const;
1688
1689 unsigned getNodeOrdering(const SUnit *SU) const {
Andrew Trick3bd8b7a2011-03-25 06:40:55 +00001690 if (!SU->getNode()) return 0;
1691
Andrew Tricke2431c62013-05-25 03:08:10 +00001692 return SU->getNode()->getIROrder();
Andrew Trick9ccce772011-01-14 21:11:41 +00001693 }
1694
Craig Topper7b883b32014-03-08 06:31:39 +00001695 bool empty() const override { return Queue.empty(); }
Andrew Trick9ccce772011-01-14 21:11:41 +00001696
Craig Topper7b883b32014-03-08 06:31:39 +00001697 void push(SUnit *U) override {
Andrew Trick9ccce772011-01-14 21:11:41 +00001698 assert(!U->NodeQueueId && "Node in the queue already");
1699 U->NodeQueueId = ++CurQueueId;
1700 Queue.push_back(U);
1701 }
1702
Craig Topper7b883b32014-03-08 06:31:39 +00001703 void remove(SUnit *SU) override {
Andrew Trick9ccce772011-01-14 21:11:41 +00001704 assert(!Queue.empty() && "Queue is empty!");
1705 assert(SU->NodeQueueId != 0 && "Not in queue!");
David Majnemer0d955d02016-08-11 22:21:41 +00001706 std::vector<SUnit *>::iterator I = find(Queue, SU);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001707 if (I != std::prev(Queue.end()))
Andrew Trick9ccce772011-01-14 21:11:41 +00001708 std::swap(*I, Queue.back());
1709 Queue.pop_back();
1710 SU->NodeQueueId = 0;
1711 }
1712
Craig Topper7b883b32014-03-08 06:31:39 +00001713 bool tracksRegPressure() const override { return TracksRegPressure; }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001714
Andrew Trick9ccce772011-01-14 21:11:41 +00001715 void dumpRegPressure() const;
1716
1717 bool HighRegPressure(const SUnit *SU) const;
1718
Andrew Trick641e2d42011-03-05 08:00:22 +00001719 bool MayReduceRegPressure(SUnit *SU) const;
1720
1721 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
Andrew Trick9ccce772011-01-14 21:11:41 +00001722
Craig Topper7b883b32014-03-08 06:31:39 +00001723 void scheduledNode(SUnit *SU) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001724
Craig Topper7b883b32014-03-08 06:31:39 +00001725 void unscheduledNode(SUnit *SU) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001726
1727protected:
1728 bool canClobber(const SUnit *SU, const SUnit *Op);
Duncan Sands635e4ef2011-11-09 14:20:48 +00001729 void AddPseudoTwoAddrDeps();
Andrew Trick9ccce772011-01-14 21:11:41 +00001730 void PrescheduleNodesWithMultipleUses();
1731 void CalculateSethiUllmanNumbers();
1732};
1733
1734template<class SF>
Andrew Trick3013b6a2011-06-15 17:16:12 +00001735static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1736 std::vector<SUnit *>::iterator Best = Q.begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001737 for (std::vector<SUnit *>::iterator I = std::next(Q.begin()),
Andrew Trick3013b6a2011-06-15 17:16:12 +00001738 E = Q.end(); I != E; ++I)
1739 if (Picker(*Best, *I))
1740 Best = I;
1741 SUnit *V = *Best;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001742 if (Best != std::prev(Q.end()))
Andrew Trick3013b6a2011-06-15 17:16:12 +00001743 std::swap(*Best, Q.back());
1744 Q.pop_back();
1745 return V;
1746}
Andrew Trick9ccce772011-01-14 21:11:41 +00001747
Andrew Trick3013b6a2011-06-15 17:16:12 +00001748template<class SF>
1749SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1750#ifndef NDEBUG
1751 if (DAG->StressSched) {
1752 reverse_sort<SF> RPicker(Picker);
1753 return popFromQueueImpl(Q, RPicker);
1754 }
1755#endif
1756 (void)DAG;
1757 return popFromQueueImpl(Q, Picker);
1758}
1759
1760template<class SF>
1761class RegReductionPriorityQueue : public RegReductionPQBase {
Andrew Trick9ccce772011-01-14 21:11:41 +00001762 SF Picker;
1763
1764public:
1765 RegReductionPriorityQueue(MachineFunction &mf,
1766 bool tracksrp,
Evan Cheng8ab58a22012-03-22 19:31:17 +00001767 bool srcorder,
Andrew Trick9ccce772011-01-14 21:11:41 +00001768 const TargetInstrInfo *tii,
1769 const TargetRegisterInfo *tri,
1770 const TargetLowering *tli)
Evan Cheng8ab58a22012-03-22 19:31:17 +00001771 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
1772 tii, tri, tli),
Andrew Trick9ccce772011-01-14 21:11:41 +00001773 Picker(this) {}
1774
Craig Topper7b883b32014-03-08 06:31:39 +00001775 bool isBottomUp() const override { return SF::IsBottomUp; }
Andrew Trick9ccce772011-01-14 21:11:41 +00001776
Craig Topper7b883b32014-03-08 06:31:39 +00001777 bool isReady(SUnit *U) const override {
Andrew Trick9ccce772011-01-14 21:11:41 +00001778 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1779 }
1780
Craig Topper7b883b32014-03-08 06:31:39 +00001781 SUnit *pop() override {
Craig Topperc0196b12014-04-14 00:51:57 +00001782 if (Queue.empty()) return nullptr;
Andrew Trick9ccce772011-01-14 21:11:41 +00001783
Andrew Trick3013b6a2011-06-15 17:16:12 +00001784 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
Andrew Trick9ccce772011-01-14 21:11:41 +00001785 V->NodeQueueId = 0;
1786 return V;
1787 }
1788
Manman Ren19f49ac2012-09-11 22:23:19 +00001789#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +00001790 LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override {
Andrew Trick9ccce772011-01-14 21:11:41 +00001791 // Emulate pop() without clobbering NodeQueueIds.
1792 std::vector<SUnit*> DumpQueue = Queue;
1793 SF DumpPicker = Picker;
1794 while (!DumpQueue.empty()) {
Andrew Trick3013b6a2011-06-15 17:16:12 +00001795 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
Dan Gohman90fb5522011-10-20 21:44:34 +00001796 dbgs() << "Height " << SU->getHeight() << ": ";
Andrew Trick9ccce772011-01-14 21:11:41 +00001797 SU->dump(DAG);
1798 }
1799 }
Manman Ren742534c2012-09-06 19:06:06 +00001800#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001801};
1802
1803typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1804BURegReductionPriorityQueue;
1805
Andrew Trick9ccce772011-01-14 21:11:41 +00001806typedef RegReductionPriorityQueue<src_ls_rr_sort>
1807SrcRegReductionPriorityQueue;
1808
1809typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1810HybridBURRPriorityQueue;
1811
1812typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1813ILPBURRPriorityQueue;
1814} // end anonymous namespace
1815
1816//===----------------------------------------------------------------------===//
1817// Static Node Priority for Register Pressure Reduction
1818//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001819
Andrew Trickbfbd9722011-04-14 05:15:06 +00001820// Check for special nodes that bypass scheduling heuristics.
1821// Currently this pushes TokenFactor nodes down, but may be used for other
1822// pseudo-ops as well.
1823//
1824// Return -1 to schedule right above left, 1 for left above right.
1825// Return 0 if no bias exists.
1826static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1827 bool LSchedLow = left->isScheduleLow;
1828 bool RSchedLow = right->isScheduleLow;
1829 if (LSchedLow != RSchedLow)
1830 return LSchedLow < RSchedLow ? 1 : -1;
1831 return 0;
1832}
1833
Dan Gohman186f65d2008-11-20 03:30:37 +00001834/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1835/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001836static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001837CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001838 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1839 if (SethiUllmanNumber != 0)
1840 return SethiUllmanNumber;
1841
1842 unsigned Extra = 0;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001843 for (const SDep &Pred : SU->Preds) {
1844 if (Pred.isCtrl()) continue; // ignore chain preds
1845 SUnit *PredSU = Pred.getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001846 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001847 if (PredSethiUllman > SethiUllmanNumber) {
1848 SethiUllmanNumber = PredSethiUllman;
1849 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001850 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001851 ++Extra;
1852 }
1853
1854 SethiUllmanNumber += Extra;
1855
1856 if (SethiUllmanNumber == 0)
1857 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001858
Evan Cheng7e4abde2008-07-02 09:23:51 +00001859 return SethiUllmanNumber;
1860}
1861
Andrew Trick9ccce772011-01-14 21:11:41 +00001862/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1863/// scheduling units.
1864void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1865 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001866
Sanjay Patele9fa3362016-02-03 22:44:14 +00001867 for (const SUnit &SU : *SUnits)
1868 CalcNodeSethiUllmanNumber(&SU, SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001869}
1870
Andrew Trick9ccce772011-01-14 21:11:41 +00001871void RegReductionPQBase::addNode(const SUnit *SU) {
1872 unsigned SUSize = SethiUllmanNumbers.size();
1873 if (SUnits->size() > SUSize)
1874 SethiUllmanNumbers.resize(SUSize*2, 0);
1875 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1876}
1877
1878void RegReductionPQBase::updateNode(const SUnit *SU) {
1879 SethiUllmanNumbers[SU->NodeNum] = 0;
1880 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1881}
1882
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001883// Lower priority means schedule further down. For bottom-up scheduling, lower
1884// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001885unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1886 assert(SU->NodeNum < SethiUllmanNumbers.size());
1887 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1888 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1889 // CopyToReg should be close to its uses to facilitate coalescing and
1890 // avoid spilling.
1891 return 0;
Christian Koniged34d0e2013-03-20 15:43:00 +00001892 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1893 Opc == TargetOpcode::SUBREG_TO_REG ||
1894 Opc == TargetOpcode::INSERT_SUBREG)
1895 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1896 // close to their uses to facilitate coalescing.
1897 return 0;
Andrew Trick9ccce772011-01-14 21:11:41 +00001898 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1899 // If SU does not have a register use, i.e. it doesn't produce a value
1900 // that would be consumed (e.g. store), then it terminates a chain of
1901 // computation. Give it a large SethiUllman number so it will be
1902 // scheduled right before its predecessors that it doesn't lengthen
1903 // their live ranges.
1904 return 0xffff;
1905 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1906 // If SU does not have a register def, schedule it close to its uses
1907 // because it does not lengthen any live ranges.
1908 return 0;
Evan Cheng1355bbd2011-04-26 21:31:35 +00001909#if 1
Andrew Trick9ccce772011-01-14 21:11:41 +00001910 return SethiUllmanNumbers[SU->NodeNum];
Evan Cheng1355bbd2011-04-26 21:31:35 +00001911#else
1912 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1913 if (SU->isCallOp) {
1914 // FIXME: This assumes all of the defs are used as call operands.
1915 int NP = (int)Priority - SU->getNode()->getNumValues();
1916 return (NP > 0) ? NP : 0;
1917 }
1918 return Priority;
1919#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001920}
1921
1922//===----------------------------------------------------------------------===//
1923// Register Pressure Tracking
1924//===----------------------------------------------------------------------===//
1925
Manman Ren19f49ac2012-09-11 22:23:19 +00001926#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +00001927LLVM_DUMP_METHOD void RegReductionPQBase::dumpRegPressure() const {
Krzysztof Parzyszekee9aa3f2017-01-25 19:29:04 +00001928 for (const TargetRegisterClass *RC : TRI->regclasses()) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001929 unsigned Id = RC->getID();
1930 unsigned RP = RegPressure[Id];
1931 if (!RP) continue;
Craig Toppercf0444b2014-11-17 05:50:14 +00001932 DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
1933 << RegLimit[Id] << '\n');
Andrew Trick9ccce772011-01-14 21:11:41 +00001934 }
1935}
Matthias Braun8c209aa2017-01-28 02:02:38 +00001936#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001937
1938bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1939 if (!TLI)
1940 return false;
1941
Sanjay Patele9fa3362016-02-03 22:44:14 +00001942 for (const SDep &Pred : SU->Preds) {
1943 if (Pred.isCtrl())
Andrew Trick9ccce772011-01-14 21:11:41 +00001944 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001945 SUnit *PredSU = Pred.getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001946 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1947 // to cover the number of registers defined (they are all live).
1948 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001949 continue;
1950 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001951 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1952 RegDefPos.IsValid(); RegDefPos.Advance()) {
Owen Anderson96adc4a2011-06-15 23:35:18 +00001953 unsigned RCId, Cost;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001954 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +00001955
Andrew Trick9ccce772011-01-14 21:11:41 +00001956 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1957 return true;
1958 }
1959 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001960 return false;
1961}
1962
Andrew Trick641e2d42011-03-05 08:00:22 +00001963bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00001964 const SDNode *N = SU->getNode();
1965
1966 if (!N->isMachineOpcode() || !SU->NumSuccs)
1967 return false;
1968
1969 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1970 for (unsigned i = 0; i != NumDefs; ++i) {
Patrik Hagglund05394352012-12-13 18:45:35 +00001971 MVT VT = N->getSimpleValueType(i);
Andrew Trick9ccce772011-01-14 21:11:41 +00001972 if (!N->hasAnyUseOfValue(i))
1973 continue;
1974 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1975 if (RegPressure[RCId] >= RegLimit[RCId])
1976 return true;
1977 }
1978 return false;
1979}
1980
Andrew Trick641e2d42011-03-05 08:00:22 +00001981// Compute the register pressure contribution by this instruction by count up
1982// for uses that are not live and down for defs. Only count register classes
1983// that are already under high pressure. As a side effect, compute the number of
1984// uses of registers that are already live.
1985//
1986// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1987// so could probably be factored.
1988int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1989 LiveUses = 0;
1990 int PDiff = 0;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001991 for (const SDep &Pred : SU->Preds) {
1992 if (Pred.isCtrl())
Andrew Trick641e2d42011-03-05 08:00:22 +00001993 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001994 SUnit *PredSU = Pred.getSUnit();
Andrew Trick641e2d42011-03-05 08:00:22 +00001995 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1996 // to cover the number of registers defined (they are all live).
1997 if (PredSU->NumRegDefsLeft == 0) {
1998 if (PredSU->getNode()->isMachineOpcode())
1999 ++LiveUses;
2000 continue;
2001 }
2002 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2003 RegDefPos.IsValid(); RegDefPos.Advance()) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002004 MVT VT = RegDefPos.GetValue();
Andrew Trick641e2d42011-03-05 08:00:22 +00002005 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2006 if (RegPressure[RCId] >= RegLimit[RCId])
2007 ++PDiff;
2008 }
2009 }
2010 const SDNode *N = SU->getNode();
2011
Eric Christopher7238cba2011-03-08 19:35:47 +00002012 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
Andrew Trick641e2d42011-03-05 08:00:22 +00002013 return PDiff;
2014
2015 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2016 for (unsigned i = 0; i != NumDefs; ++i) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002017 MVT VT = N->getSimpleValueType(i);
Andrew Trick641e2d42011-03-05 08:00:22 +00002018 if (!N->hasAnyUseOfValue(i))
2019 continue;
2020 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2021 if (RegPressure[RCId] >= RegLimit[RCId])
2022 --PDiff;
2023 }
2024 return PDiff;
2025}
2026
Andrew Trick52226d42012-03-07 23:00:49 +00002027void RegReductionPQBase::scheduledNode(SUnit *SU) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002028 if (!TracksRegPressure)
2029 return;
2030
Eric Christopher7238cba2011-03-08 19:35:47 +00002031 if (!SU->getNode())
2032 return;
Andrew Tricka8846e02011-03-23 20:40:18 +00002033
Sanjay Patele9fa3362016-02-03 22:44:14 +00002034 for (const SDep &Pred : SU->Preds) {
2035 if (Pred.isCtrl())
Andrew Trick9ccce772011-01-14 21:11:41 +00002036 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002037 SUnit *PredSU = Pred.getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00002038 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2039 // to cover the number of registers defined (they are all live).
2040 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002041 continue;
2042 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00002043 // FIXME: The ScheduleDAG currently loses information about which of a
2044 // node's values is consumed by each dependence. Consequently, if the node
2045 // defines multiple register classes, we don't know which to pressurize
2046 // here. Instead the following loop consumes the register defs in an
2047 // arbitrary order. At least it handles the common case of clustered loads
2048 // to the same class. For precise liveness, each SDep needs to indicate the
2049 // result number. But that tightly couples the ScheduleDAG with the
2050 // SelectionDAG making updates tricky. A simpler hack would be to attach a
2051 // value type or register class to SDep.
2052 //
2053 // The most important aspect of register tracking is balancing the increase
2054 // here with the reduction further below. Note that this SU may use multiple
2055 // defs in PredSU. The can't be determined here, but we've already
2056 // compensated by reducing NumRegDefsLeft in PredSU during
2057 // ScheduleDAGSDNodes::AddSchedEdges.
2058 --PredSU->NumRegDefsLeft;
2059 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2060 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2061 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2062 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00002063 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00002064
2065 unsigned RCId, Cost;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00002066 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +00002067 RegPressure[RCId] += Cost;
Andrew Trickd0548ae2011-02-04 03:18:17 +00002068 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00002069 }
2070 }
2071
Andrew Trickd0548ae2011-02-04 03:18:17 +00002072 // We should have this assert, but there may be dead SDNodes that never
2073 // materialize as SUnits, so they don't appear to generate liveness.
2074 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2075 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2076 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2077 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2078 if (SkipRegDefs > 0)
2079 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00002080 unsigned RCId, Cost;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00002081 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +00002082 if (RegPressure[RCId] < Cost) {
Andrew Trickd0548ae2011-02-04 03:18:17 +00002083 // Register pressure tracking is imprecise. This can happen. But we try
2084 // hard not to let it happen because it likely results in poor scheduling.
2085 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
2086 RegPressure[RCId] = 0;
2087 }
2088 else {
Owen Anderson96adc4a2011-06-15 23:35:18 +00002089 RegPressure[RCId] -= Cost;
Andrew Trick9ccce772011-01-14 21:11:41 +00002090 }
2091 }
Matthias Braun8c209aa2017-01-28 02:02:38 +00002092 DEBUG(dumpRegPressure());
Andrew Trick9ccce772011-01-14 21:11:41 +00002093}
2094
Andrew Trick52226d42012-03-07 23:00:49 +00002095void RegReductionPQBase::unscheduledNode(SUnit *SU) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002096 if (!TracksRegPressure)
2097 return;
2098
2099 const SDNode *N = SU->getNode();
Eric Christopher7238cba2011-03-08 19:35:47 +00002100 if (!N) return;
Andrew Tricka8846e02011-03-23 20:40:18 +00002101
Andrew Trick9ccce772011-01-14 21:11:41 +00002102 if (!N->isMachineOpcode()) {
2103 if (N->getOpcode() != ISD::CopyToReg)
2104 return;
2105 } else {
2106 unsigned Opc = N->getMachineOpcode();
2107 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2108 Opc == TargetOpcode::INSERT_SUBREG ||
2109 Opc == TargetOpcode::SUBREG_TO_REG ||
2110 Opc == TargetOpcode::REG_SEQUENCE ||
2111 Opc == TargetOpcode::IMPLICIT_DEF)
2112 return;
2113 }
2114
Sanjay Patele9fa3362016-02-03 22:44:14 +00002115 for (const SDep &Pred : SU->Preds) {
2116 if (Pred.isCtrl())
Andrew Trick9ccce772011-01-14 21:11:41 +00002117 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002118 SUnit *PredSU = Pred.getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002119 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2120 // counts data deps.
2121 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00002122 continue;
2123 const SDNode *PN = PredSU->getNode();
2124 if (!PN->isMachineOpcode()) {
2125 if (PN->getOpcode() == ISD::CopyFromReg) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002126 MVT VT = PN->getSimpleValueType(0);
Andrew Trick9ccce772011-01-14 21:11:41 +00002127 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2128 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2129 }
2130 continue;
2131 }
2132 unsigned POpc = PN->getMachineOpcode();
2133 if (POpc == TargetOpcode::IMPLICIT_DEF)
2134 continue;
Andrew Trick31f25bc2011-06-27 18:01:20 +00002135 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2136 POpc == TargetOpcode::INSERT_SUBREG ||
2137 POpc == TargetOpcode::SUBREG_TO_REG) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002138 MVT VT = PN->getSimpleValueType(0);
Andrew Trick9ccce772011-01-14 21:11:41 +00002139 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2140 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2141 continue;
2142 }
2143 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2144 for (unsigned i = 0; i != NumDefs; ++i) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002145 MVT VT = PN->getSimpleValueType(i);
Andrew Trick9ccce772011-01-14 21:11:41 +00002146 if (!PN->hasAnyUseOfValue(i))
2147 continue;
2148 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2149 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2150 // Register pressure tracking is imprecise. This can happen.
2151 RegPressure[RCId] = 0;
2152 else
2153 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2154 }
2155 }
2156
2157 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2158 // may transfer data dependencies to CopyToReg.
2159 if (SU->NumSuccs && N->isMachineOpcode()) {
2160 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2161 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002162 MVT VT = N->getSimpleValueType(i);
Andrew Trick9ccce772011-01-14 21:11:41 +00002163 if (VT == MVT::Glue || VT == MVT::Other)
2164 continue;
2165 if (!N->hasAnyUseOfValue(i))
2166 continue;
2167 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2168 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2169 }
2170 }
2171
Matthias Braun8c209aa2017-01-28 02:02:38 +00002172 DEBUG(dumpRegPressure());
Andrew Trick9ccce772011-01-14 21:11:41 +00002173}
2174
2175//===----------------------------------------------------------------------===//
2176// Dynamic Node Priority for Register Pressure Reduction
2177//===----------------------------------------------------------------------===//
2178
Evan Chengb9e3db62007-03-14 22:43:40 +00002179/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00002180/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00002181static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002182 unsigned MaxHeight = 0;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002183 for (const SDep &Succ : SU->Succs) {
2184 if (Succ.isCtrl()) continue; // ignore chain succs
2185 unsigned Height = Succ.getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00002186 // If there are bunch of CopyToRegs stacked up, they should be considered
2187 // to be at the same position.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002188 if (Succ.getSUnit()->getNode() &&
2189 Succ.getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
2190 Height = closestSucc(Succ.getSUnit())+1;
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002191 if (Height > MaxHeight)
2192 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00002193 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002194 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00002195}
2196
Evan Cheng61bc51e2007-12-20 02:22:36 +00002197/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00002198/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00002199static unsigned calcMaxScratches(const SUnit *SU) {
2200 unsigned Scratches = 0;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002201 for (const SDep &Pred : SU->Preds) {
2202 if (Pred.isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00002203 Scratches++;
2204 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00002205 return Scratches;
2206}
2207
Andrew Trickb53a00d2011-04-13 00:38:32 +00002208/// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2209/// CopyFromReg from a virtual register.
2210static bool hasOnlyLiveInOpers(const SUnit *SU) {
2211 bool RetVal = false;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002212 for (const SDep &Pred : SU->Preds) {
2213 if (Pred.isCtrl()) continue;
2214 const SUnit *PredSU = Pred.getSUnit();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002215 if (PredSU->getNode() &&
2216 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2217 unsigned Reg =
2218 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2219 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2220 RetVal = true;
2221 continue;
2222 }
2223 }
2224 return false;
2225 }
2226 return RetVal;
2227}
2228
2229/// hasOnlyLiveOutUses - Return true if SU has only value successors that are
Evan Cheng6c1414f2010-10-29 18:09:28 +00002230/// CopyToReg to a virtual register. This SU def is probably a liveout and
2231/// it has no other use. It should be scheduled closer to the terminator.
2232static bool hasOnlyLiveOutUses(const SUnit *SU) {
2233 bool RetVal = false;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002234 for (const SDep &Succ : SU->Succs) {
2235 if (Succ.isCtrl()) continue;
2236 const SUnit *SuccSU = Succ.getSUnit();
Evan Cheng6c1414f2010-10-29 18:09:28 +00002237 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2238 unsigned Reg =
2239 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2240 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2241 RetVal = true;
2242 continue;
2243 }
2244 }
2245 return false;
2246 }
2247 return RetVal;
2248}
2249
Andrew Trickb53a00d2011-04-13 00:38:32 +00002250// Set isVRegCycle for a node with only live in opers and live out uses. Also
2251// set isVRegCycle for its CopyFromReg operands.
2252//
2253// This is only relevant for single-block loops, in which case the VRegCycle
2254// node is likely an induction variable in which the operand and target virtual
2255// registers should be coalesced (e.g. pre/post increment values). Setting the
2256// isVRegCycle flag helps the scheduler prioritize other uses of the same
2257// CopyFromReg so that this node becomes the virtual register "kill". This
2258// avoids interference between the values live in and out of the block and
2259// eliminates a copy inside the loop.
2260static void initVRegCycle(SUnit *SU) {
2261 if (DisableSchedVRegCycle)
2262 return;
2263
2264 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2265 return;
2266
2267 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2268
2269 SU->isVRegCycle = true;
2270
Sanjay Patele9fa3362016-02-03 22:44:14 +00002271 for (const SDep &Pred : SU->Preds) {
2272 if (Pred.isCtrl()) continue;
2273 Pred.getSUnit()->isVRegCycle = true;
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002274 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002275}
2276
Andrew Trickb53a00d2011-04-13 00:38:32 +00002277// After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2278// CopyFromReg operands. We should no longer penalize other uses of this VReg.
2279static void resetVRegCycle(SUnit *SU) {
2280 if (!SU->isVRegCycle)
2281 return;
2282
Sanjay Patele9fa3362016-02-03 22:44:14 +00002283 for (const SDep &Pred : SU->Preds) {
2284 if (Pred.isCtrl()) continue; // ignore chain preds
2285 SUnit *PredSU = Pred.getSUnit();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002286 if (PredSU->isVRegCycle) {
2287 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2288 "VRegCycle def must be CopyFromReg");
Sanjay Patele9fa3362016-02-03 22:44:14 +00002289 Pred.getSUnit()->isVRegCycle = false;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002290 }
2291 }
2292}
2293
2294// Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2295// means a node that defines the VRegCycle has not been scheduled yet.
2296static bool hasVRegCycleUse(const SUnit *SU) {
2297 // If this SU also defines the VReg, don't hoist it as a "use".
2298 if (SU->isVRegCycle)
2299 return false;
2300
Sanjay Patele9fa3362016-02-03 22:44:14 +00002301 for (const SDep &Pred : SU->Preds) {
2302 if (Pred.isCtrl()) continue; // ignore chain preds
2303 if (Pred.getSUnit()->isVRegCycle &&
2304 Pred.getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002305 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2306 return true;
Andrew Trick2ad0b372011-04-07 19:54:57 +00002307 }
2308 }
2309 return false;
2310}
2311
Andrew Trick9ccce772011-01-14 21:11:41 +00002312// Check for either a dependence (latency) or resource (hazard) stall.
2313//
2314// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2315static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2316 if ((int)SPQ->getCurCycle() < Height) return true;
2317 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2318 != ScheduleHazardRecognizer::NoHazard)
2319 return true;
2320 return false;
2321}
2322
2323// Return -1 if left has higher priority, 1 if right has higher priority.
2324// Return 0 if latency-based priority is equivalent.
2325static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2326 RegReductionPQBase *SPQ) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002327 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2328 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2329 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2330 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2331 int LHeight = (int)left->getHeight() + LPenalty;
2332 int RHeight = (int)right->getHeight() + RPenalty;
Andrew Trick9ccce772011-01-14 21:11:41 +00002333
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002334 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002335 BUHasStall(left, LHeight, SPQ);
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002336 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002337 BUHasStall(right, RHeight, SPQ);
2338
2339 // If scheduling one of the node will cause a pipeline stall, delay it.
2340 // If scheduling either one of the node will cause a pipeline stall, sort
2341 // them according to their height.
2342 if (LStall) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002343 if (!RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002344 return 1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002345 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002346 return LHeight > RHeight ? 1 : -1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002347 } else if (RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002348 return -1;
2349
Andrew Trick47ff14b2011-01-21 05:51:33 +00002350 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002351 // and latency.
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002352 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2353 right->SchedulingPref == Sched::ILP)) {
Andrew Tricka88d46e2012-06-05 03:44:34 +00002354 // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
2355 // is enabled, grouping instructions by cycle, then its height is already
2356 // covered so only its depth matters. We also reach this point if both stall
2357 // but have the same height.
2358 if (!SPQ->getHazardRec()->isEnabled()) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002359 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002360 return LHeight > RHeight ? 1 : -1;
2361 }
Andrew Tricka88d46e2012-06-05 03:44:34 +00002362 int LDepth = left->getDepth() - LPenalty;
2363 int RDepth = right->getDepth() - RPenalty;
2364 if (LDepth != RDepth) {
2365 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2366 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2367 << ") depth " << RDepth << "\n");
2368 return LDepth < RDepth ? 1 : -1;
Andrew Trick47ff14b2011-01-21 05:51:33 +00002369 }
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002370 if (left->Latency != right->Latency)
Andrew Trick9ccce772011-01-14 21:11:41 +00002371 return left->Latency > right->Latency ? 1 : -1;
2372 }
2373 return 0;
2374}
2375
2376static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002377 // Schedule physical register definitions close to their use. This is
2378 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2379 // long as shortening physreg live ranges is generally good, we can defer
2380 // creating a subtarget hook.
2381 if (!DisableSchedPhysRegJoin) {
2382 bool LHasPhysReg = left->hasPhysRegDefs;
2383 bool RHasPhysReg = right->hasPhysRegDefs;
2384 if (LHasPhysReg != RHasPhysReg) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002385 #ifndef NDEBUG
Craig Topper06b3b662013-07-15 08:02:13 +00002386 static const char *const PhysRegMsg[] = { " has no physreg",
2387 " defines a physreg" };
Andrew Trickbfbd9722011-04-14 05:15:06 +00002388 #endif
2389 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2390 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2391 << PhysRegMsg[RHasPhysReg] << "\n");
2392 return LHasPhysReg < RHasPhysReg;
2393 }
2394 }
2395
Evan Cheng2f647542011-04-26 04:57:37 +00002396 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
Evan Cheng6730f032007-01-08 23:55:53 +00002397 unsigned LPriority = SPQ->getNodePriority(left);
2398 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng1355bbd2011-04-26 21:31:35 +00002399
2400 // Be really careful about hoisting call operands above previous calls.
2401 // Only allows it if it would reduce register pressure.
2402 if (left->isCall && right->isCallOp) {
2403 unsigned RNumVals = right->getNode()->getNumValues();
2404 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2405 }
2406 if (right->isCall && left->isCallOp) {
2407 unsigned LNumVals = left->getNode()->getNumValues();
2408 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2409 }
2410
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002411 if (LPriority != RPriority)
Evan Cheng73bdf042008-03-01 00:39:47 +00002412 return LPriority > RPriority;
Andrew Trick52b3e382011-03-08 01:51:56 +00002413
Evan Cheng1355bbd2011-04-26 21:31:35 +00002414 // One or both of the nodes are calls and their sethi-ullman numbers are the
2415 // same, then keep source order.
2416 if (left->isCall || right->isCall) {
2417 unsigned LOrder = SPQ->getNodeOrdering(left);
2418 unsigned ROrder = SPQ->getNodeOrdering(right);
2419
2420 // Prefer an ordering where the lower the non-zero order number, the higher
2421 // the preference.
2422 if ((LOrder || ROrder) && LOrder != ROrder)
2423 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2424 }
2425
Evan Cheng73bdf042008-03-01 00:39:47 +00002426 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2427 // e.g.
2428 // t1 = op t2, c1
2429 // t3 = op t4, c2
2430 //
2431 // and the following instructions are both ready.
2432 // t2 = op c3
2433 // t4 = op c4
2434 //
2435 // Then schedule t2 = op first.
2436 // i.e.
2437 // t4 = op c4
2438 // t2 = op c3
2439 // t1 = op t2, c1
2440 // t3 = op t4, c2
2441 //
2442 // This creates more short live intervals.
2443 unsigned LDist = closestSucc(left);
2444 unsigned RDist = closestSucc(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002445 if (LDist != RDist)
Evan Cheng73bdf042008-03-01 00:39:47 +00002446 return LDist < RDist;
2447
Evan Cheng3a14efa2009-02-12 08:59:45 +00002448 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002449 unsigned LScratch = calcMaxScratches(left);
2450 unsigned RScratch = calcMaxScratches(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002451 if (LScratch != RScratch)
Evan Cheng73bdf042008-03-01 00:39:47 +00002452 return LScratch > RScratch;
2453
Evan Cheng1355bbd2011-04-26 21:31:35 +00002454 // Comparing latency against a call makes little sense unless the node
2455 // is register pressure-neutral.
2456 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2457 return (left->NodeQueueId > right->NodeQueueId);
2458
2459 // Do not compare latencies when one or both of the nodes are calls.
2460 if (!DisableSchedCycles &&
2461 !(left->isCall || right->isCall)) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002462 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2463 if (result != 0)
2464 return result > 0;
2465 }
2466 else {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002467 if (left->getHeight() != right->getHeight())
Andrew Trick9ccce772011-01-14 21:11:41 +00002468 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002469
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002470 if (left->getDepth() != right->getDepth())
Andrew Trick9ccce772011-01-14 21:11:41 +00002471 return left->getDepth() < right->getDepth();
2472 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002473
Andrew Trick2085a962010-12-21 22:25:04 +00002474 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002475 "NodeQueueId cannot be zero");
2476 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002477}
2478
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002479// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002480bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002481 if (int res = checkSpecialNodes(left, right))
2482 return res > 0;
2483
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002484 return BURRSort(left, right, SPQ);
2485}
2486
2487// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002488bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002489 if (int res = checkSpecialNodes(left, right))
2490 return res > 0;
2491
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002492 unsigned LOrder = SPQ->getNodeOrdering(left);
2493 unsigned ROrder = SPQ->getNodeOrdering(right);
2494
2495 // Prefer an ordering where the lower the non-zero order number, the higher
2496 // the preference.
2497 if ((LOrder || ROrder) && LOrder != ROrder)
2498 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2499
2500 return BURRSort(left, right, SPQ);
2501}
2502
Andrew Trick9ccce772011-01-14 21:11:41 +00002503// If the time between now and when the instruction will be ready can cover
2504// the spill code, then avoid adding it to the ready queue. This gives long
2505// stalls highest priority and allows hoisting across calls. It should also
2506// speed up processing the available queue.
2507bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2508 static const unsigned ReadyDelay = 3;
2509
2510 if (SPQ->MayReduceRegPressure(SU)) return true;
2511
2512 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2513
2514 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2515 != ScheduleHazardRecognizer::NoHazard)
2516 return false;
2517
2518 return true;
2519}
2520
2521// Return true if right should be scheduled with higher priority than left.
2522bool hybrid_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
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002530 bool LHigh = SPQ->HighRegPressure(left);
2531 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002532 // Avoid causing spills. If register pressure is high, schedule for
2533 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002534 if (LHigh && !RHigh) {
2535 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2536 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002537 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002538 }
2539 else if (!LHigh && RHigh) {
2540 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2541 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002542 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002543 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002544 if (!LHigh && !RHigh) {
2545 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2546 if (result != 0)
2547 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002548 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002549 return BURRSort(left, right, SPQ);
2550}
2551
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002552// Schedule as many instructions in each cycle as possible. So don't make an
2553// instruction available unless it is ready in the current cycle.
2554bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002555 if (SU->getHeight() > CurCycle) return false;
2556
2557 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2558 != ScheduleHazardRecognizer::NoHazard)
2559 return false;
2560
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002561 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002562}
2563
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002564static bool canEnableCoalescing(SUnit *SU) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002565 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2566 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2567 // CopyToReg should be close to its uses to facilitate coalescing and
2568 // avoid spilling.
2569 return true;
2570
Christian Koniged34d0e2013-03-20 15:43:00 +00002571 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2572 Opc == TargetOpcode::SUBREG_TO_REG ||
2573 Opc == TargetOpcode::INSERT_SUBREG)
2574 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2575 // close to their uses to facilitate coalescing.
2576 return true;
Andrew Trick52b3e382011-03-08 01:51:56 +00002577
2578 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2579 // If SU does not have a register def, schedule it close to its uses
2580 // because it does not lengthen any live ranges.
2581 return true;
2582
2583 return false;
2584}
2585
Andrew Trickb8390b72011-03-05 08:04:11 +00002586// list-ilp is currently an experimental scheduler that allows various
2587// heuristics to be enabled prior to the normal register reduction logic.
Andrew Trick9ccce772011-01-14 21:11:41 +00002588bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002589 if (int res = checkSpecialNodes(left, right))
2590 return res > 0;
2591
Evan Chengdebf9c52010-11-03 00:45:17 +00002592 if (left->isCall || right->isCall)
2593 // No way to compute latency of calls.
2594 return BURRSort(left, right, SPQ);
2595
Andrew Trick52b3e382011-03-08 01:51:56 +00002596 unsigned LLiveUses = 0, RLiveUses = 0;
2597 int LPDiff = 0, RPDiff = 0;
2598 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2599 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2600 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2601 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002602 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002603 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2604 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002605 return LPDiff > RPDiff;
2606 }
2607
Andrew Trick52b3e382011-03-08 01:51:56 +00002608 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002609 bool LReduce = canEnableCoalescing(left);
2610 bool RReduce = canEnableCoalescing(right);
Andrew Trick52b3e382011-03-08 01:51:56 +00002611 if (LReduce && !RReduce) return false;
2612 if (RReduce && !LReduce) return true;
2613 }
2614
2615 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2616 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2617 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002618 return LLiveUses < RLiveUses;
2619 }
2620
Andrew Trick52b3e382011-03-08 01:51:56 +00002621 if (!DisableSchedStalls) {
2622 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2623 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002624 if (LStall != RStall)
Andrew Trick52b3e382011-03-08 01:51:56 +00002625 return left->getHeight() > right->getHeight();
Andrew Trick641e2d42011-03-05 08:00:22 +00002626 }
2627
Andrew Trick25cedf32011-03-05 10:29:25 +00002628 if (!DisableSchedCriticalPath) {
2629 int spread = (int)left->getDepth() - (int)right->getDepth();
2630 if (std::abs(spread) > MaxReorderWindow) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002631 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2632 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2633 << right->getDepth() << "\n");
Andrew Trick25cedf32011-03-05 10:29:25 +00002634 return left->getDepth() < right->getDepth();
2635 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002636 }
2637
2638 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002639 int spread = (int)left->getHeight() - (int)right->getHeight();
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002640 if (std::abs(spread) > MaxReorderWindow)
Andrew Trick52b3e382011-03-08 01:51:56 +00002641 return left->getHeight() > right->getHeight();
Evan Cheng37b740c2010-07-24 00:39:05 +00002642 }
2643
2644 return BURRSort(left, right, SPQ);
2645}
2646
Andrew Trickb53a00d2011-04-13 00:38:32 +00002647void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2648 SUnits = &sunits;
2649 // Add pseudo dependency edges for two-address nodes.
Evan Chengd33b2d62011-11-10 07:43:16 +00002650 if (!Disable2AddrHack)
2651 AddPseudoTwoAddrDeps();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002652 // Reroute edges to nodes with multiple uses.
Evan Cheng8ab58a22012-03-22 19:31:17 +00002653 if (!TracksRegPressure && !SrcOrder)
Andrew Trickb53a00d2011-04-13 00:38:32 +00002654 PrescheduleNodesWithMultipleUses();
2655 // Calculate node priorities.
2656 CalculateSethiUllmanNumbers();
2657
2658 // For single block loops, mark nodes that look like canonical IV increments.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002659 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB))
2660 for (SUnit &SU : sunits)
2661 initVRegCycle(&SU);
Andrew Trickb53a00d2011-04-13 00:38:32 +00002662}
2663
Andrew Trick9ccce772011-01-14 21:11:41 +00002664//===----------------------------------------------------------------------===//
2665// Preschedule for Register Pressure
2666//===----------------------------------------------------------------------===//
2667
2668bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002669 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002670 unsigned Opc = SU->getNode()->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002671 const MCInstrDesc &MCID = TII->get(Opc);
2672 unsigned NumRes = MCID.getNumDefs();
2673 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002674 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002675 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002676 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002677 if (DU->getNodeId() != -1 &&
2678 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002679 return true;
2680 }
2681 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002682 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002683 return false;
2684}
2685
Andrew Trick832a6a192011-09-01 00:54:31 +00002686/// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2687/// successor's explicit physregs whose definition can reach DepSU.
2688/// i.e. DepSU should not be scheduled above SU.
2689static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2690 ScheduleDAGRRList *scheduleDAG,
2691 const TargetInstrInfo *TII,
2692 const TargetRegisterInfo *TRI) {
Craig Toppere5e035a32015-12-05 07:13:35 +00002693 const MCPhysReg *ImpDefs
Andrew Trick832a6a192011-09-01 00:54:31 +00002694 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002695 const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2696 if(!ImpDefs && !RegMask)
Andrew Trick832a6a192011-09-01 00:54:31 +00002697 return false;
2698
Sanjay Patele9fa3362016-02-03 22:44:14 +00002699 for (const SDep &Succ : SU->Succs) {
2700 SUnit *SuccSU = Succ.getSUnit();
2701 for (const SDep &SuccPred : SuccSU->Preds) {
2702 if (!SuccPred.isAssignedRegDep())
Andrew Trick832a6a192011-09-01 00:54:31 +00002703 continue;
2704
Sanjay Patele9fa3362016-02-03 22:44:14 +00002705 if (RegMask &&
2706 MachineOperand::clobbersPhysReg(RegMask, SuccPred.getReg()) &&
2707 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002708 return true;
2709
2710 if (ImpDefs)
Craig Toppere5e035a32015-12-05 07:13:35 +00002711 for (const MCPhysReg *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002712 // Return true if SU clobbers this physical register use and the
2713 // definition of the register reaches from DepSU. IsReachable queries
2714 // a topological forward sort of the DAG (following the successors).
Sanjay Patele9fa3362016-02-03 22:44:14 +00002715 if (TRI->regsOverlap(*ImpDef, SuccPred.getReg()) &&
2716 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002717 return true;
Andrew Trick832a6a192011-09-01 00:54:31 +00002718 }
2719 }
2720 return false;
2721}
2722
Evan Chengf9891412007-12-20 09:25:31 +00002723/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002724/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002725static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002726 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002727 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002728 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002729 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
Craig Toppere5e035a32015-12-05 07:13:35 +00002730 const MCPhysReg *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002731 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002732 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002733 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002734 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002735 continue;
Craig Toppere5e035a32015-12-05 07:13:35 +00002736 const MCPhysReg *SUImpDefs =
Dan Gohmana366da12009-03-23 16:23:01 +00002737 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002738 const uint32_t *SURegMask = getNodeRegMask(SUNode);
2739 if (!SUImpDefs && !SURegMask)
2740 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002741 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Craig Topper7f416c82014-11-16 21:17:18 +00002742 MVT VT = N->getSimpleValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002743 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002744 continue;
2745 if (!N->hasAnyUseOfValue(i))
2746 continue;
2747 unsigned Reg = ImpDefs[i - NumDefs];
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002748 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2749 return true;
2750 if (!SUImpDefs)
2751 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002752 for (;*SUImpDefs; ++SUImpDefs) {
2753 unsigned SUReg = *SUImpDefs;
2754 if (TRI->regsOverlap(Reg, SUReg))
2755 return true;
2756 }
Evan Chengf9891412007-12-20 09:25:31 +00002757 }
2758 }
2759 return false;
2760}
2761
Dan Gohman9a658d72009-03-24 00:49:12 +00002762/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2763/// are not handled well by the general register pressure reduction
2764/// heuristics. When presented with code like this:
2765///
2766/// N
2767/// / |
2768/// / |
2769/// U store
2770/// |
2771/// ...
2772///
2773/// the heuristics tend to push the store up, but since the
2774/// operand of the store has another use (U), this would increase
2775/// the length of that other use (the U->N edge).
2776///
2777/// This function transforms code like the above to route U's
2778/// dependence through the store when possible, like this:
2779///
2780/// N
2781/// ||
2782/// ||
2783/// store
2784/// |
2785/// U
2786/// |
2787/// ...
2788///
2789/// This results in the store being scheduled immediately
2790/// after N, which shortens the U->N live range, reducing
2791/// register pressure.
2792///
Andrew Trick9ccce772011-01-14 21:11:41 +00002793void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002794 // Visit all the nodes in topological order, working top-down.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002795 for (SUnit &SU : *SUnits) {
Dan Gohman9a658d72009-03-24 00:49:12 +00002796 // For now, only look at nodes with no data successors, such as stores.
2797 // These are especially important, due to the heuristics in
2798 // getNodePriority for nodes with no data successors.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002799 if (SU.NumSuccs != 0)
Dan Gohman9a658d72009-03-24 00:49:12 +00002800 continue;
2801 // For now, only look at nodes with exactly one data predecessor.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002802 if (SU.NumPreds != 1)
Dan Gohman9a658d72009-03-24 00:49:12 +00002803 continue;
2804 // Avoid prescheduling copies to virtual registers, which don't behave
2805 // like other nodes from the perspective of scheduling heuristics.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002806 if (SDNode *N = SU.getNode())
Dan Gohman9a658d72009-03-24 00:49:12 +00002807 if (N->getOpcode() == ISD::CopyToReg &&
2808 TargetRegisterInfo::isVirtualRegister
2809 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2810 continue;
2811
2812 // Locate the single data predecessor.
Craig Topperc0196b12014-04-14 00:51:57 +00002813 SUnit *PredSU = nullptr;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002814 for (const SDep &Pred : SU.Preds)
2815 if (!Pred.isCtrl()) {
2816 PredSU = Pred.getSUnit();
Dan Gohman9a658d72009-03-24 00:49:12 +00002817 break;
2818 }
2819 assert(PredSU);
2820
2821 // Don't rewrite edges that carry physregs, because that requires additional
2822 // support infrastructure.
2823 if (PredSU->hasPhysRegDefs)
2824 continue;
2825 // Short-circuit the case where SU is PredSU's only data successor.
2826 if (PredSU->NumSuccs == 1)
2827 continue;
2828 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002829 // like other nodes from the perspective of scheduling heuristics.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002830 if (SDNode *N = SU.getNode())
Dan Gohman9a658d72009-03-24 00:49:12 +00002831 if (N->getOpcode() == ISD::CopyFromReg &&
2832 TargetRegisterInfo::isVirtualRegister
2833 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2834 continue;
2835
2836 // Perform checks on the successors of PredSU.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002837 for (const SDep &PredSucc : PredSU->Succs) {
2838 SUnit *PredSuccSU = PredSucc.getSUnit();
2839 if (PredSuccSU == &SU) continue;
Dan Gohman9a658d72009-03-24 00:49:12 +00002840 // If PredSU has another successor with no data successors, for
2841 // now don't attempt to choose either over the other.
2842 if (PredSuccSU->NumSuccs == 0)
2843 goto outer_loop_continue;
2844 // Don't break physical register dependencies.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002845 if (SU.hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2846 if (canClobberPhysRegDefs(PredSuccSU, &SU, TII, TRI))
Dan Gohman9a658d72009-03-24 00:49:12 +00002847 goto outer_loop_continue;
2848 // Don't introduce graph cycles.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002849 if (scheduleDAG->IsReachable(&SU, PredSuccSU))
Dan Gohman9a658d72009-03-24 00:49:12 +00002850 goto outer_loop_continue;
2851 }
2852
2853 // Ok, the transformation is safe and the heuristics suggest it is
2854 // profitable. Update the graph.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002855 DEBUG(dbgs() << " Prescheduling SU #" << SU.NodeNum
Evan Chengbdd062d2010-05-20 06:13:19 +00002856 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002857 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002858 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2859 SDep Edge = PredSU->Succs[i];
2860 assert(!Edge.isAssignedRegDep());
2861 SUnit *SuccSU = Edge.getSUnit();
Sanjay Patele9fa3362016-02-03 22:44:14 +00002862 if (SuccSU != &SU) {
Dan Gohman9a658d72009-03-24 00:49:12 +00002863 Edge.setSUnit(PredSU);
2864 scheduleDAG->RemovePred(SuccSU, Edge);
Sanjay Patele9fa3362016-02-03 22:44:14 +00002865 scheduleDAG->AddPred(&SU, Edge);
2866 Edge.setSUnit(&SU);
Dan Gohman9a658d72009-03-24 00:49:12 +00002867 scheduleDAG->AddPred(SuccSU, Edge);
2868 --i;
2869 }
2870 }
2871 outer_loop_continue:;
2872 }
2873}
2874
Evan Chengd38c22b2006-05-11 23:55:42 +00002875/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2876/// it as a def&use operand. Add a pseudo control edge from it to the other
2877/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002878/// first (lower in the schedule). If both nodes are two-address, favor the
2879/// one that has a CopyToReg use (more likely to be a loop induction update).
2880/// If both are two-address, but one is commutable while the other is not
2881/// commutable, favor the one that's not commutable.
Duncan Sands635e4ef2011-11-09 14:20:48 +00002882void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Sanjay Patele9fa3362016-02-03 22:44:14 +00002883 for (SUnit &SU : *SUnits) {
2884 if (!SU.isTwoAddress)
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002885 continue;
2886
Sanjay Patele9fa3362016-02-03 22:44:14 +00002887 SDNode *Node = SU.getNode();
2888 if (!Node || !Node->isMachineOpcode() || SU.getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002889 continue;
2890
Sanjay Patele9fa3362016-02-03 22:44:14 +00002891 bool isLiveOut = hasOnlyLiveOutUses(&SU);
Dan Gohman17059682008-07-17 19:10:17 +00002892 unsigned Opc = Node->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002893 const MCInstrDesc &MCID = TII->get(Opc);
2894 unsigned NumRes = MCID.getNumDefs();
2895 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002896 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002897 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
Dan Gohman82016c22008-11-19 02:00:32 +00002898 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002899 SDNode *DU = SU.getNode()->getOperand(j).getNode();
Dan Gohman82016c22008-11-19 02:00:32 +00002900 if (DU->getNodeId() == -1)
2901 continue;
2902 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
Sanjay Patele9fa3362016-02-03 22:44:14 +00002903 if (!DUSU)
2904 continue;
2905 for (const SDep &Succ : DUSU->Succs) {
2906 if (Succ.isCtrl())
2907 continue;
2908 SUnit *SuccSU = Succ.getSUnit();
2909 if (SuccSU == &SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002910 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002911 // Be conservative. Ignore if nodes aren't at roughly the same
2912 // depth and height.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002913 if (SuccSU->getHeight() < SU.getHeight() &&
2914 (SU.getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002915 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002916 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2917 // constrains whatever is using the copy, instead of the copy
2918 // itself. In the case that the copy is coalesced, this
2919 // preserves the intent of the pseudo two-address heurietics.
2920 while (SuccSU->Succs.size() == 1 &&
2921 SuccSU->getNode()->isMachineOpcode() &&
2922 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002923 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002924 SuccSU = SuccSU->Succs.front().getSUnit();
2925 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002926 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2927 continue;
2928 // Don't constrain nodes with physical register defs if the
2929 // predecessor can clobber them.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002930 if (SuccSU->hasPhysRegDefs && SU.hasPhysRegClobbers) {
2931 if (canClobberPhysRegDefs(SuccSU, &SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002932 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002933 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002934 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2935 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002936 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002937 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2938 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2939 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002940 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002941 if (!canClobberReachingPhysRegUse(SuccSU, &SU, scheduleDAG, TII, TRI) &&
Andrew Trick832a6a192011-09-01 00:54:31 +00002942 (!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002943 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Sanjay Patele9fa3362016-02-03 22:44:14 +00002944 (!SU.isCommutable && SuccSU->isCommutable)) &&
2945 !scheduleDAG->IsReachable(SuccSU, &SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002946 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Sanjay Patele9fa3362016-02-03 22:44:14 +00002947 << SU.NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2948 scheduleDAG->AddPred(&SU, SDep(SuccSU, SDep::Artificial));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002949 }
2950 }
2951 }
2952 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002953}
2954
Evan Chengd38c22b2006-05-11 23:55:42 +00002955//===----------------------------------------------------------------------===//
2956// Public Constructor Functions
2957//===----------------------------------------------------------------------===//
2958
Dan Gohmandfaf6462009-02-11 04:27:20 +00002959llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002960llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2961 CodeGenOpt::Level OptLevel) {
Eric Christopheredba30c2014-10-09 06:28:06 +00002962 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2963 const TargetInstrInfo *TII = STI.getInstrInfo();
2964 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002965
Evan Chenga77f3d32010-07-21 06:09:07 +00002966 BURegReductionPriorityQueue *PQ =
Craig Topperc0196b12014-04-14 00:51:57 +00002967 new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002968 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002969 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002970 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002971}
2972
Dan Gohmandfaf6462009-02-11 04:27:20 +00002973llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002974llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2975 CodeGenOpt::Level OptLevel) {
Eric Christopheredba30c2014-10-09 06:28:06 +00002976 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2977 const TargetInstrInfo *TII = STI.getInstrInfo();
2978 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002979
Evan Chenga77f3d32010-07-21 06:09:07 +00002980 SrcRegReductionPriorityQueue *PQ =
Craig Topperc0196b12014-04-14 00:51:57 +00002981 new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002982 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002983 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002984 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002985}
2986
2987llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002988llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2989 CodeGenOpt::Level OptLevel) {
Eric Christopheredba30c2014-10-09 06:28:06 +00002990 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2991 const TargetInstrInfo *TII = STI.getInstrInfo();
2992 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
Eric Christopherb17140d2014-10-08 07:32:17 +00002993 const TargetLowering *TLI = IS->TLI;
Andrew Trick2085a962010-12-21 22:25:04 +00002994
Evan Chenga77f3d32010-07-21 06:09:07 +00002995 HybridBURRPriorityQueue *PQ =
Evan Cheng8ab58a22012-03-22 19:31:17 +00002996 new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002997
2998 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002999 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00003000 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00003001}
Evan Cheng37b740c2010-07-24 00:39:05 +00003002
3003llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00003004llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
3005 CodeGenOpt::Level OptLevel) {
Eric Christopheredba30c2014-10-09 06:28:06 +00003006 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3007 const TargetInstrInfo *TII = STI.getInstrInfo();
3008 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
Eric Christopherb17140d2014-10-08 07:32:17 +00003009 const TargetLowering *TLI = IS->TLI;
Andrew Trick2085a962010-12-21 22:25:04 +00003010
Evan Cheng37b740c2010-07-24 00:39:05 +00003011 ILPBURRPriorityQueue *PQ =
Evan Cheng8ab58a22012-03-22 19:31:17 +00003012 new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00003013 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00003014 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00003015 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00003016}