blob: 74c550ce8226224bdfea9f8b33afff3905821879 [file] [log] [blame]
Sergei Larin4d8986a2012-09-04 14:49:56 +00001//===- HexagonMachineScheduler.cpp - MI Scheduler for Hexagon -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
Sergei Larin4d8986a2012-09-04 14:49:56 +000015#include "HexagonMachineScheduler.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000016#include "HexagonInstrInfo.h"
Krzysztof Parzyszek9be66732016-07-15 17:48:09 +000017#include "HexagonSubtarget.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/CodeGen/DFAPacketizer.h"
20#include "llvm/CodeGen/MachineBasicBlock.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +000024#include "llvm/CodeGen/RegisterClassInfo.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000025#include "llvm/CodeGen/RegisterPressure.h"
26#include "llvm/CodeGen/ScheduleDAG.h"
27#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000028#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000029#include "llvm/CodeGen/TargetOpcodes.h"
30#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000031#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000032#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000033#include "llvm/IR/Function.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
Eugene Zelenko3b873362017-09-28 22:27:31 +000037#include <algorithm>
38#include <cassert>
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +000039#include <iomanip>
Eugene Zelenko3b873362017-09-28 22:27:31 +000040#include <limits>
41#include <memory>
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +000042#include <sstream>
43
Eugene Zelenko3b873362017-09-28 22:27:31 +000044using namespace llvm;
45
46#define DEBUG_TYPE "machine-scheduler"
47
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +000048static cl::opt<bool> IgnoreBBRegPressure("ignore-bb-reg-pressure",
49 cl::Hidden, cl::ZeroOrMore, cl::init(false));
50
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +000051static cl::opt<bool> UseNewerCandidate("use-newer-candidate",
52 cl::Hidden, cl::ZeroOrMore, cl::init(true));
53
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +000054static cl::opt<unsigned> SchedDebugVerboseLevel("misched-verbose-level",
55 cl::Hidden, cl::ZeroOrMore, cl::init(1));
56
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +000057// Check if the scheduler should penalize instructions that are available to
58// early due to a zero-latency dependence.
59static cl::opt<bool> CheckEarlyAvail("check-early-avail", cl::Hidden,
60 cl::ZeroOrMore, cl::init(true));
61
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +000062// This value is used to determine if a register class is a high pressure set.
63// We compute the maximum number of registers needed and divided by the total
64// available. Then, we compare the result to this value.
65static cl::opt<float> RPThreshold("hexagon-reg-pressure", cl::Hidden,
66 cl::init(0.75f), cl::desc("High register pressure threhold."));
67
68/// Return true if there is a dependence between SUd and SUu.
69static bool hasDependence(const SUnit *SUd, const SUnit *SUu,
70 const HexagonInstrInfo &QII) {
71 if (SUd->Succs.size() == 0)
72 return false;
73
74 // Enable .cur formation.
75 if (QII.mayBeCurLoad(*SUd->getInstr()))
76 return false;
77
78 if (QII.canExecuteInBundle(*SUd->getInstr(), *SUu->getInstr()))
79 return false;
80
81 for (const auto &S : SUd->Succs) {
82 // Since we do not add pseudos to packets, might as well
83 // ignore order dependencies.
84 if (S.isCtrl())
85 continue;
86
87 if (S.getSUnit() == SUu && S.getLatency() > 0)
88 return true;
89 }
90 return false;
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +000091}
92
Sergei Larin4d8986a2012-09-04 14:49:56 +000093/// Check if scheduling of this SU is possible
94/// in the current packet.
95/// It is _not_ precise (statefull), it is more like
96/// another heuristic. Many corner cases are figured
97/// empirically.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +000098bool VLIWResourceModel::isResourceAvailable(SUnit *SU, bool IsTop) {
Sergei Larin4d8986a2012-09-04 14:49:56 +000099 if (!SU || !SU->getInstr())
100 return false;
101
102 // First see if the pipeline could receive this instruction
103 // in the current cycle.
104 switch (SU->getInstr()->getOpcode()) {
105 default:
Duncan P. N. Exon Smith57022872016-02-27 19:09:00 +0000106 if (!ResourcesModel->canReserveResources(*SU->getInstr()))
Sergei Larin4d8986a2012-09-04 14:49:56 +0000107 return false;
108 case TargetOpcode::EXTRACT_SUBREG:
109 case TargetOpcode::INSERT_SUBREG:
110 case TargetOpcode::SUBREG_TO_REG:
111 case TargetOpcode::REG_SEQUENCE:
112 case TargetOpcode::IMPLICIT_DEF:
113 case TargetOpcode::COPY:
114 case TargetOpcode::INLINEASM:
115 break;
116 }
117
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000118 MachineBasicBlock *MBB = SU->getInstr()->getParent();
119 auto &QST = MBB->getParent()->getSubtarget<HexagonSubtarget>();
120 const auto &QII = *QST.getInstrInfo();
Krzysztof Parzyszek786333f2016-07-18 16:05:27 +0000121
Sergei Larin4d8986a2012-09-04 14:49:56 +0000122 // Now see if there are no other dependencies to instructions already
123 // in the packet.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000124 if (IsTop) {
125 for (unsigned i = 0, e = Packet.size(); i != e; ++i)
126 if (hasDependence(Packet[i], SU, QII))
Sergei Larin4d8986a2012-09-04 14:49:56 +0000127 return false;
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000128 } else {
129 for (unsigned i = 0, e = Packet.size(); i != e; ++i)
130 if (hasDependence(SU, Packet[i], QII))
131 return false;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000132 }
133 return true;
134}
135
136/// Keep track of available resources.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000137bool VLIWResourceModel::reserveResources(SUnit *SU, bool IsTop) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000138 bool startNewCycle = false;
Sergei Larin2db64a72012-09-14 15:07:59 +0000139 // Artificially reset state.
140 if (!SU) {
141 ResourcesModel->clearResources();
142 Packet.clear();
143 TotalPackets++;
144 return false;
145 }
Krzysztof Parzyszek4c6b65f2018-03-20 17:03:27 +0000146 // If this SU does not fit in the packet or the packet is now full
Sergei Larin4d8986a2012-09-04 14:49:56 +0000147 // start a new one.
Krzysztof Parzyszek4c6b65f2018-03-20 17:03:27 +0000148 if (!isResourceAvailable(SU, IsTop) ||
149 Packet.size() >= SchedModel->getIssueWidth()) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000150 ResourcesModel->clearResources();
151 Packet.clear();
152 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +0000153 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000154 }
155
156 switch (SU->getInstr()->getOpcode()) {
157 default:
Duncan P. N. Exon Smith57022872016-02-27 19:09:00 +0000158 ResourcesModel->reserveResources(*SU->getInstr());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000159 break;
160 case TargetOpcode::EXTRACT_SUBREG:
161 case TargetOpcode::INSERT_SUBREG:
162 case TargetOpcode::SUBREG_TO_REG:
163 case TargetOpcode::REG_SEQUENCE:
164 case TargetOpcode::IMPLICIT_DEF:
165 case TargetOpcode::KILL:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000166 case TargetOpcode::CFI_INSTRUCTION:
Sergei Larin4d8986a2012-09-04 14:49:56 +0000167 case TargetOpcode::EH_LABEL:
168 case TargetOpcode::COPY:
169 case TargetOpcode::INLINEASM:
170 break;
171 }
172 Packet.push_back(SU);
173
174#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000175 LLVM_DEBUG(dbgs() << "Packet[" << TotalPackets << "]:\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000176 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000177 LLVM_DEBUG(dbgs() << "\t[" << i << "] SU(");
178 LLVM_DEBUG(dbgs() << Packet[i]->NodeNum << ")\t");
179 LLVM_DEBUG(Packet[i]->getInstr()->dump());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000180 }
181#endif
182
Sergei Larinef4cc112012-09-10 17:31:34 +0000183 return startNewCycle;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000184}
185
Sergei Larin4d8986a2012-09-04 14:49:56 +0000186/// schedule - Called back from MachineScheduler::runOnMachineFunction
187/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
188/// only includes instructions that have DAG nodes, not scheduling boundaries.
189void VLIWMachineScheduler::schedule() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000190 LLVM_DEBUG(dbgs() << "********** MI Converging Scheduling VLIW "
191 << printMBBReference(*BB) << " " << BB->getName()
192 << " in_func " << BB->getParent()->getName()
193 << " at loop depth " << MLI->getLoopDepth(BB) << " \n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000194
Andrew Trick7a8e1002012-09-11 00:39:15 +0000195 buildDAGWithRegPressure();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000196
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000197 Topo.InitDAGTopologicalSorting();
198
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000199 // Postprocess the DAG to add platform-specific artificial dependencies.
200 postprocessDAG();
201
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000202 SmallVector<SUnit*, 8> TopRoots, BotRoots;
203 findRootsAndBiasEdges(TopRoots, BotRoots);
204
205 // Initialize the strategy before modifying the DAG.
206 SchedImpl->initialize(this);
207
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000208 LLVM_DEBUG(unsigned maxH = 0;
209 for (unsigned su = 0, e = SUnits.size(); su != e;
210 ++su) if (SUnits[su].getHeight() > maxH) maxH =
211 SUnits[su].getHeight();
212 dbgs() << "Max Height " << maxH << "\n";);
213 LLVM_DEBUG(unsigned maxD = 0;
214 for (unsigned su = 0, e = SUnits.size(); su != e;
215 ++su) if (SUnits[su].getDepth() > maxD) maxD =
216 SUnits[su].getDepth();
217 dbgs() << "Max Depth " << maxD << "\n";);
218 LLVM_DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su) SUnits[su]
219 .dumpAll(this));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000220
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000221 initQueues(TopRoots, BotRoots);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000222
Sergei Larin4d8986a2012-09-04 14:49:56 +0000223 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000224 while (true) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000225 LLVM_DEBUG(
226 dbgs() << "** VLIWMachineScheduler::schedule picking next node\n");
James Y Knighte72b0db2015-09-18 18:52:20 +0000227 SUnit *SU = SchedImpl->pickNode(IsTopNode);
228 if (!SU) break;
229
Sergei Larin4d8986a2012-09-04 14:49:56 +0000230 if (!checkSchedLimit())
231 break;
232
Andrew Trick7a8e1002012-09-11 00:39:15 +0000233 scheduleMI(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000234
Andrew Trickd7f890e2013-12-28 21:56:47 +0000235 // Notify the scheduling strategy after updating the DAG.
236 SchedImpl->schedNode(SU, IsTopNode);
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000237
238 updateQueues(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000239 }
240 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
241
Sergei Larin4d8986a2012-09-04 14:49:56 +0000242 placeDebugValues();
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000243
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000244 LLVM_DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000245 dbgs() << "*** Final schedule for "
246 << printMBBReference(*begin()->getParent()) << " ***\n";
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000247 dumpSchedule();
248 dbgs() << '\n';
249 });
Sergei Larin4d8986a2012-09-04 14:49:56 +0000250}
251
Andrew Trick7a8e1002012-09-11 00:39:15 +0000252void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
253 DAG = static_cast<VLIWMachineScheduler*>(dag);
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000254 SchedModel = DAG->getSchedModel();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000255
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000256 Top.init(DAG, SchedModel);
257 Bot.init(DAG, SchedModel);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000258
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000259 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
260 // are disabled, then these HazardRecs will be disabled.
261 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000262 const TargetSubtargetInfo &STI = DAG->MF.getSubtarget();
263 const TargetInstrInfo *TII = STI.getInstrInfo();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000264 delete Top.HazardRec;
265 delete Bot.HazardRec;
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000266 Top.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);
267 Bot.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000268
Chandler Carruthc18e39c2013-07-27 10:48:45 +0000269 delete Top.ResourceModel;
270 delete Bot.ResourceModel;
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000271 Top.ResourceModel = new VLIWResourceModel(STI, DAG->getSchedModel());
272 Bot.ResourceModel = new VLIWResourceModel(STI, DAG->getSchedModel());
Sergei Larinef4cc112012-09-10 17:31:34 +0000273
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000274 const std::vector<unsigned> &MaxPressure =
275 DAG->getRegPressure().MaxSetPressure;
276 HighPressureSets.assign(MaxPressure.size(), 0);
277 for (unsigned i = 0, e = MaxPressure.size(); i < e; ++i) {
278 unsigned Limit = DAG->getRegClassInfo()->getRegPressureSetLimit(i);
279 HighPressureSets[i] =
Krzysztof Parzyszek2c4231d2018-03-20 13:28:46 +0000280 ((float) MaxPressure[i] > ((float) Limit * RPThreshold));
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000281 }
282
Eugene Zelenko3b873362017-09-28 22:27:31 +0000283 assert((!ForceTopDown || !ForceBottomUp) &&
Sergei Larin4d8986a2012-09-04 14:49:56 +0000284 "-misched-topdown incompatible with -misched-bottomup");
285}
286
287void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
288 if (SU->isScheduled)
289 return;
290
Krzysztof Parzyszek2be7ead2016-07-18 16:15:15 +0000291 for (const SDep &PI : SU->Preds) {
292 unsigned PredReadyCycle = PI.getSUnit()->TopReadyCycle;
293 unsigned MinLatency = PI.getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000294#ifndef NDEBUG
295 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
296#endif
297 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
298 SU->TopReadyCycle = PredReadyCycle + MinLatency;
299 }
300 Top.releaseNode(SU, SU->TopReadyCycle);
301}
302
303void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
304 if (SU->isScheduled)
305 return;
306
307 assert(SU->getInstr() && "Scheduled SUnit must have instr");
308
309 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
310 I != E; ++I) {
311 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickde2109e2013-06-15 04:49:57 +0000312 unsigned MinLatency = I->getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000313#ifndef NDEBUG
314 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
315#endif
316 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
317 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
318 }
319 Bot.releaseNode(SU, SU->BotReadyCycle);
320}
321
322/// Does this SU have a hazard within the current instruction group.
323///
324/// The scheduler supports two modes of hazard recognition. The first is the
325/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
326/// supports highly complicated in-order reservation tables
327/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
328///
329/// The second is a streamlined mechanism that checks for hazards based on
330/// simple counters that the scheduler itself maintains. It explicitly checks
331/// for instruction dispatch limitations, including the number of micro-ops that
332/// can dispatch per cycle.
333///
334/// TODO: Also check whether the SU must start a new group.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000335bool ConvergingVLIWScheduler::VLIWSchedBoundary::checkHazard(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000336 if (HazardRec->isEnabled())
337 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
338
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000339 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
340 if (IssueCount + uops > SchedModel->getIssueWidth())
Sergei Larin4d8986a2012-09-04 14:49:56 +0000341 return true;
342
343 return false;
344}
345
Andrew Trickd7f890e2013-12-28 21:56:47 +0000346void ConvergingVLIWScheduler::VLIWSchedBoundary::releaseNode(SUnit *SU,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000347 unsigned ReadyCycle) {
348 if (ReadyCycle < MinReadyCycle)
349 MinReadyCycle = ReadyCycle;
350
351 // Check for interlocks first. For the purpose of other heuristics, an
352 // instruction that cannot issue appears as if it's not in the ReadyQueue.
353 if (ReadyCycle > CurrCycle || checkHazard(SU))
354
355 Pending.push(SU);
356 else
357 Available.push(SU);
358}
359
360/// Move the boundary of scheduled code by one cycle.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000361void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpCycle() {
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000362 unsigned Width = SchedModel->getIssueWidth();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000363 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
364
Eugene Zelenko3b873362017-09-28 22:27:31 +0000365 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
366 "MinReadyCycle uninitialized");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000367 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
368
369 if (!HazardRec->isEnabled()) {
370 // Bypass HazardRec virtual calls.
371 CurrCycle = NextCycle;
Sergei Larinef4cc112012-09-10 17:31:34 +0000372 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000373 // Bypass getHazardType calls in case of long latency.
374 for (; CurrCycle != NextCycle; ++CurrCycle) {
375 if (isTop())
376 HazardRec->AdvanceCycle();
377 else
378 HazardRec->RecedeCycle();
379 }
380 }
381 CheckPending = true;
382
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000383 LLVM_DEBUG(dbgs() << "*** Next cycle " << Available.getName() << " cycle "
384 << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000385}
386
387/// Move the boundary of scheduled code by one SUnit.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000388void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpNode(SUnit *SU) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000389 bool startNewCycle = false;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000390
391 // Update the reservation table.
392 if (HazardRec->isEnabled()) {
393 if (!isTop() && SU->isCall) {
394 // Calls are scheduled with their preceding instructions. For bottom-up
395 // scheduling, clear the pipeline state before emitting.
396 HazardRec->Reset();
397 }
398 HazardRec->EmitInstruction(SU);
399 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000400
401 // Update DFA model.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000402 startNewCycle = ResourceModel->reserveResources(SU, isTop());
Sergei Larinef4cc112012-09-10 17:31:34 +0000403
Sergei Larin4d8986a2012-09-04 14:49:56 +0000404 // Check the instruction group dispatch limit.
405 // TODO: Check if this SU must end a dispatch group.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000406 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Sergei Larinef4cc112012-09-10 17:31:34 +0000407 if (startNewCycle) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000408 LLVM_DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000409 bumpCycle();
410 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000411 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000412 LLVM_DEBUG(dbgs() << "*** IssueCount " << IssueCount << " at cycle "
413 << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000414}
415
416/// Release pending ready nodes in to the available queue. This makes them
417/// visible to heuristics.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000418void ConvergingVLIWScheduler::VLIWSchedBoundary::releasePending() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000419 // If the available queue is empty, it is safe to reset MinReadyCycle.
420 if (Available.empty())
Eugene Zelenko3b873362017-09-28 22:27:31 +0000421 MinReadyCycle = std::numeric_limits<unsigned>::max();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000422
423 // Check to see if any of the pending instructions are ready to issue. If
424 // so, add them to the available queue.
425 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
426 SUnit *SU = *(Pending.begin()+i);
427 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
428
429 if (ReadyCycle < MinReadyCycle)
430 MinReadyCycle = ReadyCycle;
431
432 if (ReadyCycle > CurrCycle)
433 continue;
434
435 if (checkHazard(SU))
436 continue;
437
438 Available.push(SU);
439 Pending.remove(Pending.begin()+i);
440 --i; --e;
441 }
442 CheckPending = false;
443}
444
445/// Remove SU from the ready set for this boundary.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000446void ConvergingVLIWScheduler::VLIWSchedBoundary::removeReady(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000447 if (Available.isInQueue(SU))
448 Available.remove(Available.find(SU));
449 else {
450 assert(Pending.isInQueue(SU) && "bad ready count");
451 Pending.remove(Pending.find(SU));
452 }
453}
454
455/// If this queue only has one ready candidate, return it. As a side effect,
456/// advance the cycle until at least one node is ready. If multiple instructions
457/// are ready, return NULL.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000458SUnit *ConvergingVLIWScheduler::VLIWSchedBoundary::pickOnlyChoice() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000459 if (CheckPending)
460 releasePending();
461
Krzysztof Parzyszek73be83d2018-03-20 16:22:06 +0000462 auto AdvanceCycle = [this]() {
463 if (Available.empty())
464 return true;
465 if (Available.size() == 1 && Pending.size() > 0)
466 return !ResourceModel->isResourceAvailable(*Available.begin(), isTop()) ||
467 getWeakLeft(*Available.begin(), isTop()) != 0;
468 return false;
469 };
470 for (unsigned i = 0; AdvanceCycle(); ++i) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000471 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
472 "permanent hazard"); (void)i;
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000473 ResourceModel->reserveResources(nullptr, isTop());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000474 bumpCycle();
475 releasePending();
476 }
477 if (Available.size() == 1)
478 return *Available.begin();
Craig Topper062a2ba2014-04-25 05:30:21 +0000479 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000480}
481
482#ifndef NDEBUG
Sergei Larinef4cc112012-09-10 17:31:34 +0000483void ConvergingVLIWScheduler::traceCandidate(const char *Label,
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000484 const ReadyQueue &Q, SUnit *SU, int Cost, PressureChange P) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000485 dbgs() << Label << " " << Q.getName() << " ";
486 if (P.isValid())
Andrew Trick1a831342013-08-30 03:49:48 +0000487 dbgs() << DAG->TRI->getRegPressureSetName(P.getPSet()) << ":"
488 << P.getUnitInc() << " ";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000489 else
490 dbgs() << " ";
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000491 dbgs() << "cost(" << Cost << ")\t";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000492 SU->dump(DAG);
493}
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000494
495// Very detailed queue dump, to be used with higher verbosity levels.
496void ConvergingVLIWScheduler::readyQueueVerboseDump(
497 const RegPressureTracker &RPTracker, SchedCandidate &Candidate,
498 ReadyQueue &Q) {
499 RegPressureTracker &TempTracker = const_cast<RegPressureTracker &>(RPTracker);
500
501 dbgs() << ">>> " << Q.getName() << "\n";
502 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
503 RegPressureDelta RPDelta;
504 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
505 DAG->getRegionCriticalPSets(),
506 DAG->getRegPressure().MaxSetPressure);
507 std::stringstream dbgstr;
508 dbgstr << "SU(" << std::setw(3) << (*I)->NodeNum << ")";
509 dbgs() << dbgstr.str();
510 SchedulingCost(Q, *I, Candidate, RPDelta, true);
511 dbgs() << "\t";
512 (*I)->getInstr()->dump();
513 }
514 dbgs() << "\n";
515}
Sergei Larin4d8986a2012-09-04 14:49:56 +0000516#endif
517
Nirav Dave6a38cc62017-06-08 18:49:25 +0000518/// isSingleUnscheduledPred - If SU2 is the only unscheduled predecessor
519/// of SU, return true (we may have duplicates)
520static inline bool isSingleUnscheduledPred(SUnit *SU, SUnit *SU2) {
521 if (SU->NumPredsLeft == 0)
522 return false;
523
524 for (auto &Pred : SU->Preds) {
525 // We found an available, but not scheduled, predecessor.
526 if (!Pred.getSUnit()->isScheduled && (Pred.getSUnit() != SU2))
527 return false;
Sergei Larinef4cc112012-09-10 17:31:34 +0000528 }
Nirav Dave6a38cc62017-06-08 18:49:25 +0000529
530 return true;
Sergei Larinef4cc112012-09-10 17:31:34 +0000531}
532
Nirav Dave6a38cc62017-06-08 18:49:25 +0000533/// isSingleUnscheduledSucc - If SU2 is the only unscheduled successor
534/// of SU, return true (we may have duplicates)
535static inline bool isSingleUnscheduledSucc(SUnit *SU, SUnit *SU2) {
536 if (SU->NumSuccsLeft == 0)
537 return false;
538
539 for (auto &Succ : SU->Succs) {
540 // We found an available, but not scheduled, successor.
541 if (!Succ.getSUnit()->isScheduled && (Succ.getSUnit() != SU2))
542 return false;
Sergei Larinef4cc112012-09-10 17:31:34 +0000543 }
Nirav Dave6a38cc62017-06-08 18:49:25 +0000544 return true;
Sergei Larinef4cc112012-09-10 17:31:34 +0000545}
546
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000547/// Check if the instruction changes the register pressure of a register in the
548/// high pressure set. The function returns a negative value if the pressure
549/// decreases and a positive value is the pressure increases. If the instruction
550/// doesn't use a high pressure register or doesn't change the register
551/// pressure, then return 0.
552int ConvergingVLIWScheduler::pressureChange(const SUnit *SU, bool isBotUp) {
553 PressureDiff &PD = DAG->getPressureDiff(SU);
554 for (auto &P : PD) {
555 if (!P.isValid())
556 continue;
557 // The pressure differences are computed bottom-up, so the comparision for
558 // an increase is positive in the bottom direction, but negative in the
559 // top-down direction.
560 if (HighPressureSets[P.getPSet()])
561 return (isBotUp ? P.getUnitInc() : -P.getUnitInc());
562 }
563 return 0;
564}
565
Sergei Larin4d8986a2012-09-04 14:49:56 +0000566// Constants used to denote relative importance of
567// heuristic components for cost computation.
568static const unsigned PriorityOne = 200;
Eli Friedman8f06d552013-09-11 00:41:02 +0000569static const unsigned PriorityTwo = 50;
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000570static const unsigned PriorityThree = 75;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000571static const unsigned ScaleTwo = 10;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000572
573/// Single point to compute overall scheduling cost.
574/// TODO: More heuristics will be used soon.
575int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
576 SchedCandidate &Candidate,
577 RegPressureDelta &Delta,
578 bool verbose) {
579 // Initial trivial priority.
580 int ResCount = 1;
581
582 // Do not waste time on a node that is already scheduled.
583 if (!SU || SU->isScheduled)
584 return ResCount;
585
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000586 LLVM_DEBUG(if (verbose) dbgs()
587 << ((Q.getID() == TopQID) ? "(top|" : "(bot|"));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000588 // Forced priority is high.
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000589 if (SU->isScheduleHigh) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000590 ResCount += PriorityOne;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000591 LLVM_DEBUG(dbgs() << "H|");
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000592 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000593
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000594 unsigned IsAvailableAmt = 0;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000595 // Critical path first.
Sergei Larinef4cc112012-09-10 17:31:34 +0000596 if (Q.getID() == TopQID) {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000597 if (Top.isLatencyBound(SU)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000598 LLVM_DEBUG(if (verbose) dbgs() << "LB|");
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000599 ResCount += (SU->getHeight() * ScaleTwo);
600 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000601
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000602 LLVM_DEBUG(if (verbose) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000603 std::stringstream dbgstr;
604 dbgstr << "h" << std::setw(3) << SU->getHeight() << "|";
605 dbgs() << dbgstr.str();
606 });
607
Sergei Larinef4cc112012-09-10 17:31:34 +0000608 // If resources are available for it, multiply the
609 // chance of scheduling.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000610 if (Top.ResourceModel->isResourceAvailable(SU, true)) {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000611 IsAvailableAmt = (PriorityTwo + PriorityThree);
612 ResCount += IsAvailableAmt;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000613 LLVM_DEBUG(if (verbose) dbgs() << "A|");
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000614 } else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000615 LLVM_DEBUG(if (verbose) dbgs() << " |");
Sergei Larinef4cc112012-09-10 17:31:34 +0000616 } else {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000617 if (Bot.isLatencyBound(SU)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000618 LLVM_DEBUG(if (verbose) dbgs() << "LB|");
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000619 ResCount += (SU->getDepth() * ScaleTwo);
620 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000621
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000622 LLVM_DEBUG(if (verbose) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000623 std::stringstream dbgstr;
624 dbgstr << "d" << std::setw(3) << SU->getDepth() << "|";
625 dbgs() << dbgstr.str();
626 });
627
Sergei Larinef4cc112012-09-10 17:31:34 +0000628 // If resources are available for it, multiply the
629 // chance of scheduling.
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000630 if (Bot.ResourceModel->isResourceAvailable(SU, false)) {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000631 IsAvailableAmt = (PriorityTwo + PriorityThree);
632 ResCount += IsAvailableAmt;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000633 LLVM_DEBUG(if (verbose) dbgs() << "A|");
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000634 } else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000635 LLVM_DEBUG(if (verbose) dbgs() << " |");
Sergei Larinef4cc112012-09-10 17:31:34 +0000636 }
637
638 unsigned NumNodesBlocking = 0;
639 if (Q.getID() == TopQID) {
640 // How many SUs does it block from scheduling?
641 // Look at all of the successors of this node.
642 // Count the number of nodes that
643 // this node is the sole unscheduled node for.
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000644 if (Top.isLatencyBound(SU))
645 for (const SDep &SI : SU->Succs)
646 if (isSingleUnscheduledPred(SI.getSUnit(), SU))
647 ++NumNodesBlocking;
Sergei Larinef4cc112012-09-10 17:31:34 +0000648 } else {
649 // How many unscheduled predecessors block this node?
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000650 if (Bot.isLatencyBound(SU))
651 for (const SDep &PI : SU->Preds)
652 if (isSingleUnscheduledSucc(PI.getSUnit(), SU))
653 ++NumNodesBlocking;
Sergei Larinef4cc112012-09-10 17:31:34 +0000654 }
655 ResCount += (NumNodesBlocking * ScaleTwo);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000656
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000657 LLVM_DEBUG(if (verbose) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000658 std::stringstream dbgstr;
659 dbgstr << "blk " << std::setw(2) << NumNodesBlocking << ")|";
660 dbgs() << dbgstr.str();
661 });
662
Sergei Larin4d8986a2012-09-04 14:49:56 +0000663 // Factor in reg pressure as a heuristic.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000664 if (!IgnoreBBRegPressure) {
665 // Decrease priority by the amount that register pressure exceeds the limit.
666 ResCount -= (Delta.Excess.getUnitInc()*PriorityOne);
667 // Decrease priority if register pressure exceeds the limit.
668 ResCount -= (Delta.CriticalMax.getUnitInc()*PriorityOne);
669 // Decrease priority slightly if register pressure would increase over the
670 // current maximum.
671 ResCount -= (Delta.CurrentMax.getUnitInc()*PriorityTwo);
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000672 // If there are register pressure issues, then we remove the value added for
673 // the instruction being available. The rationale is that we really don't
674 // want to schedule an instruction that causes a spill.
675 if (IsAvailableAmt && pressureChange(SU, Q.getID() != TopQID) > 0 &&
676 (Delta.Excess.getUnitInc() || Delta.CriticalMax.getUnitInc() ||
677 Delta.CurrentMax.getUnitInc()))
678 ResCount -= IsAvailableAmt;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000679 LLVM_DEBUG(if (verbose) {
680 dbgs() << "RP " << Delta.Excess.getUnitInc() << "/"
681 << Delta.CriticalMax.getUnitInc() << "/"
682 << Delta.CurrentMax.getUnitInc() << ")|";
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000683 });
684 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000685
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000686 // Give a little extra priority to a .cur instruction if there is a resource
687 // available for it.
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000688 auto &QST = DAG->MF.getSubtarget<HexagonSubtarget>();
689 auto &QII = *QST.getInstrInfo();
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +0000690 if (SU->isInstr() && QII.mayBeCurLoad(*SU->getInstr())) {
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000691 if (Q.getID() == TopQID &&
692 Top.ResourceModel->isResourceAvailable(SU, true)) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000693 ResCount += PriorityTwo;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000694 LLVM_DEBUG(if (verbose) dbgs() << "C|");
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000695 } else if (Q.getID() == BotQID &&
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000696 Bot.ResourceModel->isResourceAvailable(SU, false)) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000697 ResCount += PriorityTwo;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000698 LLVM_DEBUG(if (verbose) dbgs() << "C|");
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000699 }
700 }
701
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000702 // Give preference to a zero latency instruction if the dependent
703 // instruction is in the current packet.
Krzysztof Parzyszek5ffd8082018-03-20 14:54:01 +0000704 if (Q.getID() == TopQID && getWeakLeft(SU, true) == 0) {
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000705 for (const SDep &PI : SU->Preds) {
706 if (!PI.getSUnit()->getInstr()->isPseudo() && PI.isAssignedRegDep() &&
707 PI.getLatency() == 0 &&
708 Top.ResourceModel->isInPacket(PI.getSUnit())) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000709 ResCount += PriorityThree;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000710 LLVM_DEBUG(if (verbose) dbgs() << "Z|");
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000711 }
712 }
Krzysztof Parzyszek5ffd8082018-03-20 14:54:01 +0000713 } else if (Q.getID() == BotQID && getWeakLeft(SU, false) == 0) {
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000714 for (const SDep &SI : SU->Succs) {
715 if (!SI.getSUnit()->getInstr()->isPseudo() && SI.isAssignedRegDep() &&
716 SI.getLatency() == 0 &&
717 Bot.ResourceModel->isInPacket(SI.getSUnit())) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000718 ResCount += PriorityThree;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000719 LLVM_DEBUG(if (verbose) dbgs() << "Z|");
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000720 }
721 }
722 }
723
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000724 // If the instruction has a non-zero latency dependence with an instruction in
725 // the current packet, then it should not be scheduled yet. The case occurs
726 // when the dependent instruction is scheduled in a new packet, so the
727 // scheduler updates the current cycle and pending instructions become
728 // available.
729 if (CheckEarlyAvail) {
730 if (Q.getID() == TopQID) {
731 for (const auto &PI : SU->Preds) {
732 if (PI.getLatency() > 0 &&
733 Top.ResourceModel->isInPacket(PI.getSUnit())) {
734 ResCount -= PriorityOne;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000735 LLVM_DEBUG(if (verbose) dbgs() << "D|");
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000736 }
737 }
738 } else {
739 for (const auto &SI : SU->Succs) {
740 if (SI.getLatency() > 0 &&
741 Bot.ResourceModel->isInPacket(SI.getSUnit())) {
742 ResCount -= PriorityOne;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000743 LLVM_DEBUG(if (verbose) dbgs() << "D|");
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000744 }
745 }
746 }
747 }
748
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000749 LLVM_DEBUG(if (verbose) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000750 std::stringstream dbgstr;
751 dbgstr << "Total " << std::setw(4) << ResCount << ")";
752 dbgs() << dbgstr.str();
753 });
Sergei Larin4d8986a2012-09-04 14:49:56 +0000754
755 return ResCount;
756}
757
758/// Pick the best candidate from the top queue.
759///
760/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
761/// DAG building. To adjust for the current scheduling location we need to
762/// maintain the number of vreg uses remaining to be top-scheduled.
763ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000764pickNodeFromQueue(VLIWSchedBoundary &Zone, const RegPressureTracker &RPTracker,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000765 SchedCandidate &Candidate) {
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000766 ReadyQueue &Q = Zone.Available;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000767 LLVM_DEBUG(if (SchedDebugVerboseLevel > 1)
768 readyQueueVerboseDump(RPTracker, Candidate, Q);
769 else Q.dump(););
Sergei Larin4d8986a2012-09-04 14:49:56 +0000770
771 // getMaxPressureDelta temporarily modifies the tracker.
772 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
773
774 // BestSU remains NULL if no top candidates beat the best existing candidate.
775 CandResult FoundCandidate = NoCand;
776 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
777 RegPressureDelta RPDelta;
778 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
779 DAG->getRegionCriticalPSets(),
780 DAG->getRegPressure().MaxSetPressure);
781
782 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
783
784 // Initialize the candidate if needed.
785 if (!Candidate.SU) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000786 LLVM_DEBUG(traceCandidate("DCAND", Q, *I, CurrentCost));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000787 Candidate.SU = *I;
788 Candidate.RPDelta = RPDelta;
789 Candidate.SCost = CurrentCost;
790 FoundCandidate = NodeOrder;
791 continue;
792 }
793
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000794 // Choose node order for negative cost candidates. There is no good
795 // candidate in this case.
796 if (CurrentCost < 0 && Candidate.SCost < 0) {
797 if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
798 || (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000799 LLVM_DEBUG(traceCandidate("NCAND", Q, *I, CurrentCost));
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000800 Candidate.SU = *I;
801 Candidate.RPDelta = RPDelta;
802 Candidate.SCost = CurrentCost;
803 FoundCandidate = NodeOrder;
804 }
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000805 continue;
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000806 }
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000807
Sergei Larin4d8986a2012-09-04 14:49:56 +0000808 // Best cost.
809 if (CurrentCost > Candidate.SCost) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000810 LLVM_DEBUG(traceCandidate("CCAND", Q, *I, CurrentCost));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000811 Candidate.SU = *I;
812 Candidate.RPDelta = RPDelta;
813 Candidate.SCost = CurrentCost;
814 FoundCandidate = BestCost;
815 continue;
816 }
817
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000818 // Choose an instruction that does not depend on an artificial edge.
819 unsigned CurrWeak = getWeakLeft(*I, (Q.getID() == TopQID));
820 unsigned CandWeak = getWeakLeft(Candidate.SU, (Q.getID() == TopQID));
821 if (CurrWeak != CandWeak) {
822 if (CurrWeak < CandWeak) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000823 LLVM_DEBUG(traceCandidate("WCAND", Q, *I, CurrentCost));
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000824 Candidate.SU = *I;
825 Candidate.RPDelta = RPDelta;
826 Candidate.SCost = CurrentCost;
827 FoundCandidate = Weak;
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000828 }
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000829 continue;
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000830 }
831
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000832 if (CurrentCost == Candidate.SCost && Zone.isLatencyBound(*I)) {
833 unsigned CurrSize, CandSize;
834 if (Q.getID() == TopQID) {
835 CurrSize = (*I)->Succs.size();
836 CandSize = Candidate.SU->Succs.size();
837 } else {
838 CurrSize = (*I)->Preds.size();
839 CandSize = Candidate.SU->Preds.size();
840 }
841 if (CurrSize > CandSize) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000842 LLVM_DEBUG(traceCandidate("SPCAND", Q, *I, CurrentCost));
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000843 Candidate.SU = *I;
844 Candidate.RPDelta = RPDelta;
845 Candidate.SCost = CurrentCost;
846 FoundCandidate = BestCost;
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000847 }
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000848 // Keep the old candidate if it's a better candidate. That is, don't use
849 // the subsequent tie breaker.
850 if (CurrSize != CandSize)
851 continue;
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000852 }
853
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000854 // Tie breaker.
855 // To avoid scheduling indeterminism, we need a tie breaker
856 // for the case when cost is identical for two nodes.
857 if (UseNewerCandidate && CurrentCost == Candidate.SCost) {
858 if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)
859 || (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000860 LLVM_DEBUG(traceCandidate("TCAND", Q, *I, CurrentCost));
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000861 Candidate.SU = *I;
862 Candidate.RPDelta = RPDelta;
863 Candidate.SCost = CurrentCost;
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000864 FoundCandidate = NodeOrder;
Krzysztof Parzyszekdca38312018-03-20 12:28:43 +0000865 continue;
866 }
867 }
868
Sergei Larin4d8986a2012-09-04 14:49:56 +0000869 // Fall through to original instruction order.
870 // Only consider node order if Candidate was chosen from this Q.
871 if (FoundCandidate == NoCand)
872 continue;
873 }
874 return FoundCandidate;
875}
876
877/// Pick the best candidate node from either the top or bottom queue.
878SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
879 // Schedule as far as possible in the direction of no choice. This is most
880 // efficient, but also provides the best heuristics for CriticalPSets.
881 if (SUnit *SU = Bot.pickOnlyChoice()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000882 LLVM_DEBUG(dbgs() << "Picked only Bottom\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000883 IsTopNode = false;
884 return SU;
885 }
886 if (SUnit *SU = Top.pickOnlyChoice()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000887 LLVM_DEBUG(dbgs() << "Picked only Top\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000888 IsTopNode = true;
889 return SU;
890 }
891 SchedCandidate BotCand;
892 // Prefer bottom scheduling when heuristics are silent.
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000893 CandResult BotResult = pickNodeFromQueue(Bot,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000894 DAG->getBotRPTracker(), BotCand);
895 assert(BotResult != NoCand && "failed to find the first candidate");
896
897 // If either Q has a single candidate that provides the least increase in
898 // Excess pressure, we can immediately schedule from that Q.
899 //
900 // RegionCriticalPSets summarizes the pressure within the scheduled region and
901 // affects picking from either Q. If scheduling in one direction must
902 // increase pressure for one of the excess PSets, then schedule in that
903 // direction first to provide more freedom in the other direction.
904 if (BotResult == SingleExcess || BotResult == SingleCritical) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000905 LLVM_DEBUG(dbgs() << "Prefered Bottom Node\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000906 IsTopNode = false;
907 return BotCand.SU;
908 }
909 // Check if the top Q has a better candidate.
910 SchedCandidate TopCand;
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000911 CandResult TopResult = pickNodeFromQueue(Top,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000912 DAG->getTopRPTracker(), TopCand);
913 assert(TopResult != NoCand && "failed to find the first candidate");
914
915 if (TopResult == SingleExcess || TopResult == SingleCritical) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000916 LLVM_DEBUG(dbgs() << "Prefered Top Node\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000917 IsTopNode = true;
918 return TopCand.SU;
919 }
920 // If either Q has a single candidate that minimizes pressure above the
921 // original region's pressure pick it.
922 if (BotResult == SingleMax) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000923 LLVM_DEBUG(dbgs() << "Prefered Bottom Node SingleMax\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000924 IsTopNode = false;
925 return BotCand.SU;
926 }
927 if (TopResult == SingleMax) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000928 LLVM_DEBUG(dbgs() << "Prefered Top Node SingleMax\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000929 IsTopNode = true;
930 return TopCand.SU;
931 }
932 if (TopCand.SCost > BotCand.SCost) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000933 LLVM_DEBUG(dbgs() << "Prefered Top Node Cost\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000934 IsTopNode = true;
935 return TopCand.SU;
936 }
937 // Otherwise prefer the bottom candidate in node order.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000938 LLVM_DEBUG(dbgs() << "Prefered Bottom in Node order\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000939 IsTopNode = false;
940 return BotCand.SU;
941}
942
943/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
944SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
945 if (DAG->top() == DAG->bottom()) {
946 assert(Top.Available.empty() && Top.Pending.empty() &&
947 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topper062a2ba2014-04-25 05:30:21 +0000948 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000949 }
950 SUnit *SU;
Eugene Zelenko3b873362017-09-28 22:27:31 +0000951 if (ForceTopDown) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000952 SU = Top.pickOnlyChoice();
953 if (!SU) {
954 SchedCandidate TopCand;
955 CandResult TopResult =
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000956 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000957 assert(TopResult != NoCand && "failed to find the first candidate");
958 (void)TopResult;
959 SU = TopCand.SU;
960 }
961 IsTopNode = true;
Eugene Zelenko3b873362017-09-28 22:27:31 +0000962 } else if (ForceBottomUp) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000963 SU = Bot.pickOnlyChoice();
964 if (!SU) {
965 SchedCandidate BotCand;
966 CandResult BotResult =
Krzysztof Parzyszek65059ee2018-03-20 19:26:27 +0000967 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000968 assert(BotResult != NoCand && "failed to find the first candidate");
969 (void)BotResult;
970 SU = BotCand.SU;
971 }
972 IsTopNode = false;
973 } else {
974 SU = pickNodeBidrectional(IsTopNode);
975 }
976 if (SU->isTopReady())
977 Top.removeReady(SU);
978 if (SU->isBottomReady())
979 Bot.removeReady(SU);
980
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000981 LLVM_DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
982 << " Scheduling instruction in cycle "
983 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << " ("
984 << reportPackets() << ")\n";
985 SU->dump(DAG));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000986 return SU;
987}
988
989/// Update the scheduler's state after scheduling a node. This is the same node
Sergei Larinef4cc112012-09-10 17:31:34 +0000990/// that was just returned by pickNode(). However, VLIWMachineScheduler needs
991/// to update it's state based on the current cycle before MachineSchedStrategy
992/// does.
Sergei Larin4d8986a2012-09-04 14:49:56 +0000993void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
994 if (IsTopNode) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000995 Top.bumpNode(SU);
Krzysztof Parzyszek4c6b65f2018-03-20 17:03:27 +0000996 SU->TopReadyCycle = Top.CurrCycle;
Sergei Larinef4cc112012-09-10 17:31:34 +0000997 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000998 Bot.bumpNode(SU);
Krzysztof Parzyszek4c6b65f2018-03-20 17:03:27 +0000999 SU->BotReadyCycle = Bot.CurrCycle;
Sergei Larin4d8986a2012-09-04 14:49:56 +00001000 }
1001}