blob: b70a6b13b5a469c6bc3d316705bc4478fb6f4b84 [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"
Krzysztof Parzyszek9be66732016-07-15 17:48:09 +000016#include "HexagonSubtarget.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000017#include "llvm/CodeGen/MachineLoopInfo.h"
Krzysztof Parzyszek9be66732016-07-15 17:48:09 +000018#include "llvm/CodeGen/ScheduleDAGMutation.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000019#include "llvm/IR/Function.h"
Sergei Larin4d8986a2012-09-04 14:49:56 +000020
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +000021#include <iomanip>
22#include <sstream>
23
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +000024static cl::opt<bool> IgnoreBBRegPressure("ignore-bb-reg-pressure",
25 cl::Hidden, cl::ZeroOrMore, cl::init(false));
26
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000027static cl::opt<bool> SchedPredsCloser("sched-preds-closer",
28 cl::Hidden, cl::ZeroOrMore, cl::init(true));
29
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +000030static cl::opt<unsigned> SchedDebugVerboseLevel("misched-verbose-level",
31 cl::Hidden, cl::ZeroOrMore, cl::init(1));
32
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +000033static cl::opt<bool> TopUseShorterTie("top-use-shorter-tie",
34 cl::Hidden, cl::ZeroOrMore, cl::init(false));
35
36static cl::opt<bool> BotUseShorterTie("bot-use-shorter-tie",
37 cl::Hidden, cl::ZeroOrMore, cl::init(false));
38
39static cl::opt<bool> DisableTCTie("disable-tc-tie",
40 cl::Hidden, cl::ZeroOrMore, cl::init(false));
41
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000042static cl::opt<bool> SchedRetvalOptimization("sched-retval-optimization",
43 cl::Hidden, cl::ZeroOrMore, cl::init(true));
44
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +000045// Check if the scheduler should penalize instructions that are available to
46// early due to a zero-latency dependence.
47static cl::opt<bool> CheckEarlyAvail("check-early-avail", cl::Hidden,
48 cl::ZeroOrMore, cl::init(true));
49
Sergei Larin4d8986a2012-09-04 14:49:56 +000050using namespace llvm;
51
Chandler Carruth84e68b22014-04-22 02:41:26 +000052#define DEBUG_TYPE "misched"
53
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000054class HexagonCallMutation : public ScheduleDAGMutation {
55public:
56 void apply(ScheduleDAGInstrs *DAG) override;
57private:
58 bool shouldTFRICallBind(const HexagonInstrInfo &HII,
59 const SUnit &Inst1, const SUnit &Inst2) const;
60};
61
62// Check if a call and subsequent A2_tfrpi instructions should maintain
63// scheduling affinity. We are looking for the TFRI to be consumed in
64// the next instruction. This should help reduce the instances of
65// double register pairs being allocated and scheduled before a call
66// when not used until after the call. This situation is exacerbated
67// by the fact that we allocate the pair from the callee saves list,
68// leading to excess spills and restores.
69bool HexagonCallMutation::shouldTFRICallBind(const HexagonInstrInfo &HII,
70 const SUnit &Inst1, const SUnit &Inst2) const {
71 if (Inst1.getInstr()->getOpcode() != Hexagon::A2_tfrpi)
72 return false;
73
74 // TypeXTYPE are 64 bit operations.
75 if (HII.getType(Inst2.getInstr()) == HexagonII::TypeXTYPE)
76 return true;
77 return false;
78}
79
80void HexagonCallMutation::apply(ScheduleDAGInstrs *DAG) {
Craig Topper062a2ba2014-04-25 05:30:21 +000081 SUnit* LastSequentialCall = nullptr;
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000082 unsigned VRegHoldingRet = 0;
83 unsigned RetRegister;
84 SUnit* LastUseOfRet = nullptr;
85 auto &TRI = *DAG->MF.getSubtarget().getRegisterInfo();
86 auto &HII = *DAG->MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
87
Sergei Larin2db64a72012-09-14 15:07:59 +000088 // Currently we only catch the situation when compare gets scheduled
89 // before preceding call.
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000090 for (unsigned su = 0, e = DAG->SUnits.size(); su != e; ++su) {
Sergei Larin2db64a72012-09-14 15:07:59 +000091 // Remember the call.
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000092 if (DAG->SUnits[su].getInstr()->isCall())
93 LastSequentialCall = &DAG->SUnits[su];
Sergei Larin2db64a72012-09-14 15:07:59 +000094 // Look for a compare that defines a predicate.
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +000095 else if (DAG->SUnits[su].getInstr()->isCompare() && LastSequentialCall)
96 DAG->SUnits[su].addPred(SDep(LastSequentialCall, SDep::Barrier));
97 // Look for call and tfri* instructions.
98 else if (SchedPredsCloser && LastSequentialCall && su > 1 && su < e-1 &&
99 shouldTFRICallBind(HII, DAG->SUnits[su], DAG->SUnits[su+1]))
100 DAG->SUnits[su].addPred(SDep(&DAG->SUnits[su-1], SDep::Barrier));
101 // Prevent redundant register copies between two calls, which are caused by
102 // both the return value and the argument for the next call being in %R0.
103 // Example:
104 // 1: <call1>
105 // 2: %VregX = COPY %R0
106 // 3: <use of %VregX>
107 // 4: %R0 = ...
108 // 5: <call2>
109 // The scheduler would often swap 3 and 4, so an additional register is
110 // needed. This code inserts a Barrier dependence between 3 & 4 to prevent
111 // this. The same applies for %D0 and %V0/%W0, which are also handled.
112 else if (SchedRetvalOptimization) {
113 const MachineInstr *MI = DAG->SUnits[su].getInstr();
114 if (MI->isCopy() && (MI->readsRegister(Hexagon::R0, &TRI) ||
115 MI->readsRegister(Hexagon::V0, &TRI))) {
116 // %vregX = COPY %R0
117 VRegHoldingRet = MI->getOperand(0).getReg();
118 RetRegister = MI->getOperand(1).getReg();
119 LastUseOfRet = nullptr;
120 } else if (VRegHoldingRet && MI->readsVirtualRegister(VRegHoldingRet))
121 // <use of %vregX>
122 LastUseOfRet = &DAG->SUnits[su];
123 else if (LastUseOfRet && MI->definesRegister(RetRegister, &TRI))
124 // %R0 = ...
125 DAG->SUnits[su].addPred(SDep(LastUseOfRet, SDep::Barrier));
126 }
Sergei Larin2db64a72012-09-14 15:07:59 +0000127 }
128}
129
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +0000130
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000131/// Save the last formed packet
132void VLIWResourceModel::savePacket() {
133 OldPacket = Packet;
134}
135
Sergei Larin4d8986a2012-09-04 14:49:56 +0000136/// Check if scheduling of this SU is possible
137/// in the current packet.
138/// It is _not_ precise (statefull), it is more like
139/// another heuristic. Many corner cases are figured
140/// empirically.
141bool VLIWResourceModel::isResourceAvailable(SUnit *SU) {
142 if (!SU || !SU->getInstr())
143 return false;
144
145 // First see if the pipeline could receive this instruction
146 // in the current cycle.
147 switch (SU->getInstr()->getOpcode()) {
148 default:
Duncan P. N. Exon Smith57022872016-02-27 19:09:00 +0000149 if (!ResourcesModel->canReserveResources(*SU->getInstr()))
Sergei Larin4d8986a2012-09-04 14:49:56 +0000150 return false;
151 case TargetOpcode::EXTRACT_SUBREG:
152 case TargetOpcode::INSERT_SUBREG:
153 case TargetOpcode::SUBREG_TO_REG:
154 case TargetOpcode::REG_SEQUENCE:
155 case TargetOpcode::IMPLICIT_DEF:
156 case TargetOpcode::COPY:
157 case TargetOpcode::INLINEASM:
158 break;
159 }
160
161 // Now see if there are no other dependencies to instructions already
162 // in the packet.
163 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
164 if (Packet[i]->Succs.size() == 0)
165 continue;
166 for (SUnit::const_succ_iterator I = Packet[i]->Succs.begin(),
167 E = Packet[i]->Succs.end(); I != E; ++I) {
168 // Since we do not add pseudos to packets, might as well
169 // ignore order dependencies.
170 if (I->isCtrl())
171 continue;
172
173 if (I->getSUnit() == SU)
174 return false;
175 }
176 }
177 return true;
178}
179
180/// Keep track of available resources.
Sergei Larinef4cc112012-09-10 17:31:34 +0000181bool VLIWResourceModel::reserveResources(SUnit *SU) {
182 bool startNewCycle = false;
Sergei Larin2db64a72012-09-14 15:07:59 +0000183 // Artificially reset state.
184 if (!SU) {
185 ResourcesModel->clearResources();
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000186 savePacket();
Sergei Larin2db64a72012-09-14 15:07:59 +0000187 Packet.clear();
188 TotalPackets++;
189 return false;
190 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000191 // If this SU does not fit in the packet
192 // start a new one.
193 if (!isResourceAvailable(SU)) {
194 ResourcesModel->clearResources();
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000195 savePacket();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000196 Packet.clear();
197 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +0000198 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000199 }
200
201 switch (SU->getInstr()->getOpcode()) {
202 default:
Duncan P. N. Exon Smith57022872016-02-27 19:09:00 +0000203 ResourcesModel->reserveResources(*SU->getInstr());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000204 break;
205 case TargetOpcode::EXTRACT_SUBREG:
206 case TargetOpcode::INSERT_SUBREG:
207 case TargetOpcode::SUBREG_TO_REG:
208 case TargetOpcode::REG_SEQUENCE:
209 case TargetOpcode::IMPLICIT_DEF:
210 case TargetOpcode::KILL:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000211 case TargetOpcode::CFI_INSTRUCTION:
Sergei Larin4d8986a2012-09-04 14:49:56 +0000212 case TargetOpcode::EH_LABEL:
213 case TargetOpcode::COPY:
214 case TargetOpcode::INLINEASM:
215 break;
216 }
217 Packet.push_back(SU);
218
219#ifndef NDEBUG
220 DEBUG(dbgs() << "Packet[" << TotalPackets << "]:\n");
221 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
222 DEBUG(dbgs() << "\t[" << i << "] SU(");
Sergei Larinef4cc112012-09-10 17:31:34 +0000223 DEBUG(dbgs() << Packet[i]->NodeNum << ")\t");
224 DEBUG(Packet[i]->getInstr()->dump());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000225 }
226#endif
227
228 // If packet is now full, reset the state so in the next cycle
229 // we start fresh.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000230 if (Packet.size() >= SchedModel->getIssueWidth()) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000231 ResourcesModel->clearResources();
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000232 savePacket();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000233 Packet.clear();
234 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +0000235 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000236 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000237
238 return startNewCycle;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000239}
240
Sergei Larin4d8986a2012-09-04 14:49:56 +0000241/// schedule - Called back from MachineScheduler::runOnMachineFunction
242/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
243/// only includes instructions that have DAG nodes, not scheduling boundaries.
244void VLIWMachineScheduler::schedule() {
245 DEBUG(dbgs()
246 << "********** MI Converging Scheduling VLIW BB#" << BB->getNumber()
247 << " " << BB->getName()
248 << " in_func " << BB->getParent()->getFunction()->getName()
Alexey Samsonov8968e6d2014-08-20 19:36:05 +0000249 << " at loop depth " << MLI->getLoopDepth(BB)
Sergei Larin4d8986a2012-09-04 14:49:56 +0000250 << " \n");
251
Andrew Trick7a8e1002012-09-11 00:39:15 +0000252 buildDAGWithRegPressure();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000253
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000254 SmallVector<SUnit*, 8> TopRoots, BotRoots;
255 findRootsAndBiasEdges(TopRoots, BotRoots);
256
257 // Initialize the strategy before modifying the DAG.
258 SchedImpl->initialize(this);
259
Sergei Larinef4cc112012-09-10 17:31:34 +0000260 // To view Height/Depth correctly, they should be accessed at least once.
Andrew Trick63474622013-03-02 01:43:08 +0000261 //
262 // FIXME: SUnit::dumpAll always recompute depth and height now. The max
263 // depth/height could be computed directly from the roots and leaves.
Sergei Larinef4cc112012-09-10 17:31:34 +0000264 DEBUG(unsigned maxH = 0;
265 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
266 if (SUnits[su].getHeight() > maxH)
267 maxH = SUnits[su].getHeight();
268 dbgs() << "Max Height " << maxH << "\n";);
269 DEBUG(unsigned maxD = 0;
270 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
271 if (SUnits[su].getDepth() > maxD)
272 maxD = SUnits[su].getDepth();
273 dbgs() << "Max Depth " << maxD << "\n";);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000274 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
275 SUnits[su].dumpAll(this));
276
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000277 initQueues(TopRoots, BotRoots);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000278
Sergei Larin4d8986a2012-09-04 14:49:56 +0000279 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000280 while (true) {
281 DEBUG(dbgs() << "** VLIWMachineScheduler::schedule picking next node\n");
282 SUnit *SU = SchedImpl->pickNode(IsTopNode);
283 if (!SU) break;
284
Sergei Larin4d8986a2012-09-04 14:49:56 +0000285 if (!checkSchedLimit())
286 break;
287
Andrew Trick7a8e1002012-09-11 00:39:15 +0000288 scheduleMI(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000289
Andrew Trick7a8e1002012-09-11 00:39:15 +0000290 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000291
292 // Notify the scheduling strategy after updating the DAG.
293 SchedImpl->schedNode(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000294 }
295 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
296
Sergei Larin4d8986a2012-09-04 14:49:56 +0000297 placeDebugValues();
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000298
299 DEBUG({
300 unsigned BBNum = begin()->getParent()->getNumber();
301 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
302 dumpSchedule();
303 dbgs() << '\n';
304 });
Sergei Larin4d8986a2012-09-04 14:49:56 +0000305}
306
Andrew Trick7a8e1002012-09-11 00:39:15 +0000307void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
308 DAG = static_cast<VLIWMachineScheduler*>(dag);
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000309 SchedModel = DAG->getSchedModel();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000310
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000311 Top.init(DAG, SchedModel);
312 Bot.init(DAG, SchedModel);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000313
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000314 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
315 // are disabled, then these HazardRecs will be disabled.
316 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000317 const TargetSubtargetInfo &STI = DAG->MF.getSubtarget();
318 const TargetInstrInfo *TII = STI.getInstrInfo();
Andrew Trick553e0fe2013-02-13 19:22:27 +0000319 delete Top.HazardRec;
320 delete Bot.HazardRec;
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000321 Top.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);
322 Bot.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000323
Chandler Carruthc18e39c2013-07-27 10:48:45 +0000324 delete Top.ResourceModel;
325 delete Bot.ResourceModel;
Eric Christopherf8b8e4a2015-02-02 22:11:40 +0000326 Top.ResourceModel = new VLIWResourceModel(STI, DAG->getSchedModel());
327 Bot.ResourceModel = new VLIWResourceModel(STI, DAG->getSchedModel());
Sergei Larinef4cc112012-09-10 17:31:34 +0000328
Andrew Trick7a8e1002012-09-11 00:39:15 +0000329 assert((!llvm::ForceTopDown || !llvm::ForceBottomUp) &&
Sergei Larin4d8986a2012-09-04 14:49:56 +0000330 "-misched-topdown incompatible with -misched-bottomup");
Krzysztof Parzyszek9be66732016-07-15 17:48:09 +0000331
332 DAG->addMutation(make_unique<HexagonSubtarget::HexagonDAGMutation>());
Krzysztof Parzyszek36b0f932016-07-15 19:09:37 +0000333 DAG->addMutation(make_unique<HexagonCallMutation>());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000334}
335
336void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
337 if (SU->isScheduled)
338 return;
339
340 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
341 I != E; ++I) {
342 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
Andrew Trickde2109e2013-06-15 04:49:57 +0000343 unsigned MinLatency = I->getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000344#ifndef NDEBUG
345 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
346#endif
347 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
348 SU->TopReadyCycle = PredReadyCycle + MinLatency;
349 }
350 Top.releaseNode(SU, SU->TopReadyCycle);
351}
352
353void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
354 if (SU->isScheduled)
355 return;
356
357 assert(SU->getInstr() && "Scheduled SUnit must have instr");
358
359 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
360 I != E; ++I) {
361 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
Andrew Trickde2109e2013-06-15 04:49:57 +0000362 unsigned MinLatency = I->getLatency();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000363#ifndef NDEBUG
364 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
365#endif
366 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
367 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
368 }
369 Bot.releaseNode(SU, SU->BotReadyCycle);
370}
371
372/// Does this SU have a hazard within the current instruction group.
373///
374/// The scheduler supports two modes of hazard recognition. The first is the
375/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
376/// supports highly complicated in-order reservation tables
377/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
378///
379/// The second is a streamlined mechanism that checks for hazards based on
380/// simple counters that the scheduler itself maintains. It explicitly checks
381/// for instruction dispatch limitations, including the number of micro-ops that
382/// can dispatch per cycle.
383///
384/// TODO: Also check whether the SU must start a new group.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000385bool ConvergingVLIWScheduler::VLIWSchedBoundary::checkHazard(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000386 if (HazardRec->isEnabled())
387 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
388
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000389 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
390 if (IssueCount + uops > SchedModel->getIssueWidth())
Sergei Larin4d8986a2012-09-04 14:49:56 +0000391 return true;
392
393 return false;
394}
395
Andrew Trickd7f890e2013-12-28 21:56:47 +0000396void ConvergingVLIWScheduler::VLIWSchedBoundary::releaseNode(SUnit *SU,
Sergei Larin4d8986a2012-09-04 14:49:56 +0000397 unsigned ReadyCycle) {
398 if (ReadyCycle < MinReadyCycle)
399 MinReadyCycle = ReadyCycle;
400
401 // Check for interlocks first. For the purpose of other heuristics, an
402 // instruction that cannot issue appears as if it's not in the ReadyQueue.
403 if (ReadyCycle > CurrCycle || checkHazard(SU))
404
405 Pending.push(SU);
406 else
407 Available.push(SU);
408}
409
410/// Move the boundary of scheduled code by one cycle.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000411void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpCycle() {
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000412 unsigned Width = SchedModel->getIssueWidth();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000413 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
414
415 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
416 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
417
418 if (!HazardRec->isEnabled()) {
419 // Bypass HazardRec virtual calls.
420 CurrCycle = NextCycle;
Sergei Larinef4cc112012-09-10 17:31:34 +0000421 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000422 // Bypass getHazardType calls in case of long latency.
423 for (; CurrCycle != NextCycle; ++CurrCycle) {
424 if (isTop())
425 HazardRec->AdvanceCycle();
426 else
427 HazardRec->RecedeCycle();
428 }
429 }
430 CheckPending = true;
431
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000432 DEBUG(dbgs() << "*** Next cycle " << Available.getName() << " cycle "
433 << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000434}
435
436/// Move the boundary of scheduled code by one SUnit.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000437void ConvergingVLIWScheduler::VLIWSchedBoundary::bumpNode(SUnit *SU) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000438 bool startNewCycle = false;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000439
440 // Update the reservation table.
441 if (HazardRec->isEnabled()) {
442 if (!isTop() && SU->isCall) {
443 // Calls are scheduled with their preceding instructions. For bottom-up
444 // scheduling, clear the pipeline state before emitting.
445 HazardRec->Reset();
446 }
447 HazardRec->EmitInstruction(SU);
448 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000449
450 // Update DFA model.
451 startNewCycle = ResourceModel->reserveResources(SU);
452
Sergei Larin4d8986a2012-09-04 14:49:56 +0000453 // Check the instruction group dispatch limit.
454 // TODO: Check if this SU must end a dispatch group.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000455 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Sergei Larinef4cc112012-09-10 17:31:34 +0000456 if (startNewCycle) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000457 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
458 bumpCycle();
459 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000460 else
461 DEBUG(dbgs() << "*** IssueCount " << IssueCount
462 << " at cycle " << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000463}
464
465/// Release pending ready nodes in to the available queue. This makes them
466/// visible to heuristics.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000467void ConvergingVLIWScheduler::VLIWSchedBoundary::releasePending() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000468 // If the available queue is empty, it is safe to reset MinReadyCycle.
469 if (Available.empty())
470 MinReadyCycle = UINT_MAX;
471
472 // Check to see if any of the pending instructions are ready to issue. If
473 // so, add them to the available queue.
474 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
475 SUnit *SU = *(Pending.begin()+i);
476 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
477
478 if (ReadyCycle < MinReadyCycle)
479 MinReadyCycle = ReadyCycle;
480
481 if (ReadyCycle > CurrCycle)
482 continue;
483
484 if (checkHazard(SU))
485 continue;
486
487 Available.push(SU);
488 Pending.remove(Pending.begin()+i);
489 --i; --e;
490 }
491 CheckPending = false;
492}
493
494/// Remove SU from the ready set for this boundary.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000495void ConvergingVLIWScheduler::VLIWSchedBoundary::removeReady(SUnit *SU) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000496 if (Available.isInQueue(SU))
497 Available.remove(Available.find(SU));
498 else {
499 assert(Pending.isInQueue(SU) && "bad ready count");
500 Pending.remove(Pending.find(SU));
501 }
502}
503
504/// If this queue only has one ready candidate, return it. As a side effect,
505/// advance the cycle until at least one node is ready. If multiple instructions
506/// are ready, return NULL.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000507SUnit *ConvergingVLIWScheduler::VLIWSchedBoundary::pickOnlyChoice() {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000508 if (CheckPending)
509 releasePending();
510
511 for (unsigned i = 0; Available.empty(); ++i) {
512 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
513 "permanent hazard"); (void)i;
Craig Topper062a2ba2014-04-25 05:30:21 +0000514 ResourceModel->reserveResources(nullptr);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000515 bumpCycle();
516 releasePending();
517 }
518 if (Available.size() == 1)
519 return *Available.begin();
Craig Topper062a2ba2014-04-25 05:30:21 +0000520 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000521}
522
523#ifndef NDEBUG
Sergei Larinef4cc112012-09-10 17:31:34 +0000524void ConvergingVLIWScheduler::traceCandidate(const char *Label,
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000525 const ReadyQueue &Q, SUnit *SU, int Cost, PressureChange P) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000526 dbgs() << Label << " " << Q.getName() << " ";
527 if (P.isValid())
Andrew Trick1a831342013-08-30 03:49:48 +0000528 dbgs() << DAG->TRI->getRegPressureSetName(P.getPSet()) << ":"
529 << P.getUnitInc() << " ";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000530 else
531 dbgs() << " ";
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000532 dbgs() << "cost(" << Cost << ")\t";
Sergei Larin4d8986a2012-09-04 14:49:56 +0000533 SU->dump(DAG);
534}
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000535
536// Very detailed queue dump, to be used with higher verbosity levels.
537void ConvergingVLIWScheduler::readyQueueVerboseDump(
538 const RegPressureTracker &RPTracker, SchedCandidate &Candidate,
539 ReadyQueue &Q) {
540 RegPressureTracker &TempTracker = const_cast<RegPressureTracker &>(RPTracker);
541
542 dbgs() << ">>> " << Q.getName() << "\n";
543 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
544 RegPressureDelta RPDelta;
545 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
546 DAG->getRegionCriticalPSets(),
547 DAG->getRegPressure().MaxSetPressure);
548 std::stringstream dbgstr;
549 dbgstr << "SU(" << std::setw(3) << (*I)->NodeNum << ")";
550 dbgs() << dbgstr.str();
551 SchedulingCost(Q, *I, Candidate, RPDelta, true);
552 dbgs() << "\t";
553 (*I)->getInstr()->dump();
554 }
555 dbgs() << "\n";
556}
Sergei Larin4d8986a2012-09-04 14:49:56 +0000557#endif
558
Sergei Larinef4cc112012-09-10 17:31:34 +0000559/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
560/// of SU, return it, otherwise return null.
561static SUnit *getSingleUnscheduledPred(SUnit *SU) {
Craig Topper062a2ba2014-04-25 05:30:21 +0000562 SUnit *OnlyAvailablePred = nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000563 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
564 I != E; ++I) {
565 SUnit &Pred = *I->getSUnit();
566 if (!Pred.isScheduled) {
567 // We found an available, but not scheduled, predecessor. If it's the
568 // only one we have found, keep track of it... otherwise give up.
569 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
Craig Topper062a2ba2014-04-25 05:30:21 +0000570 return nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000571 OnlyAvailablePred = &Pred;
572 }
573 }
574 return OnlyAvailablePred;
575}
576
577/// getSingleUnscheduledSucc - If there is exactly one unscheduled successor
578/// of SU, return it, otherwise return null.
579static SUnit *getSingleUnscheduledSucc(SUnit *SU) {
Craig Topper062a2ba2014-04-25 05:30:21 +0000580 SUnit *OnlyAvailableSucc = nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000581 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
582 I != E; ++I) {
583 SUnit &Succ = *I->getSUnit();
584 if (!Succ.isScheduled) {
585 // We found an available, but not scheduled, successor. If it's the
586 // only one we have found, keep track of it... otherwise give up.
587 if (OnlyAvailableSucc && OnlyAvailableSucc != &Succ)
Craig Topper062a2ba2014-04-25 05:30:21 +0000588 return nullptr;
Sergei Larinef4cc112012-09-10 17:31:34 +0000589 OnlyAvailableSucc = &Succ;
590 }
591 }
592 return OnlyAvailableSucc;
593}
594
Sergei Larin4d8986a2012-09-04 14:49:56 +0000595// Constants used to denote relative importance of
596// heuristic components for cost computation.
597static const unsigned PriorityOne = 200;
Eli Friedman8f06d552013-09-11 00:41:02 +0000598static const unsigned PriorityTwo = 50;
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000599static const unsigned PriorityThree = 75;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000600static const unsigned ScaleTwo = 10;
601static const unsigned FactorOne = 2;
602
603/// Single point to compute overall scheduling cost.
604/// TODO: More heuristics will be used soon.
605int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
606 SchedCandidate &Candidate,
607 RegPressureDelta &Delta,
608 bool verbose) {
609 // Initial trivial priority.
610 int ResCount = 1;
611
612 // Do not waste time on a node that is already scheduled.
613 if (!SU || SU->isScheduled)
614 return ResCount;
615
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000616 MachineInstr *Instr = SU->getInstr();
617
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000618 DEBUG(if (verbose) dbgs() << ((Q.getID() == TopQID) ? "(top|" : "(bot|"));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000619 // Forced priority is high.
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000620 if (SU->isScheduleHigh) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000621 ResCount += PriorityOne;
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000622 DEBUG(dbgs() << "H|");
623 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000624
625 // Critical path first.
Sergei Larinef4cc112012-09-10 17:31:34 +0000626 if (Q.getID() == TopQID) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000627 ResCount += (SU->getHeight() * ScaleTwo);
Sergei Larinef4cc112012-09-10 17:31:34 +0000628
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000629 DEBUG(if (verbose) {
630 std::stringstream dbgstr;
631 dbgstr << "h" << std::setw(3) << SU->getHeight() << "|";
632 dbgs() << dbgstr.str();
633 });
634
Sergei Larinef4cc112012-09-10 17:31:34 +0000635 // If resources are available for it, multiply the
636 // chance of scheduling.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000637 if (Top.ResourceModel->isResourceAvailable(SU)) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000638 ResCount <<= FactorOne;
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000639 ResCount += PriorityThree;
640 DEBUG(if (verbose) dbgs() << "A|");
641 } else
642 DEBUG(if (verbose) dbgs() << " |");
Sergei Larinef4cc112012-09-10 17:31:34 +0000643 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000644 ResCount += (SU->getDepth() * ScaleTwo);
645
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000646 DEBUG(if (verbose) {
647 std::stringstream dbgstr;
648 dbgstr << "d" << std::setw(3) << SU->getDepth() << "|";
649 dbgs() << dbgstr.str();
650 });
651
Sergei Larinef4cc112012-09-10 17:31:34 +0000652 // If resources are available for it, multiply the
653 // chance of scheduling.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000654 if (Bot.ResourceModel->isResourceAvailable(SU)) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000655 ResCount <<= FactorOne;
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000656 ResCount += PriorityThree;
657 DEBUG(if (verbose) dbgs() << "A|");
658 } else
659 DEBUG(if (verbose) dbgs() << " |");
Sergei Larinef4cc112012-09-10 17:31:34 +0000660 }
661
662 unsigned NumNodesBlocking = 0;
663 if (Q.getID() == TopQID) {
664 // How many SUs does it block from scheduling?
665 // Look at all of the successors of this node.
666 // Count the number of nodes that
667 // this node is the sole unscheduled node for.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000668 for (const SDep &SI : SU->Succs)
669 if (getSingleUnscheduledPred(SI.getSUnit()) == SU)
Sergei Larinef4cc112012-09-10 17:31:34 +0000670 ++NumNodesBlocking;
671 } else {
672 // How many unscheduled predecessors block this node?
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000673 for (const SDep &PI : SU->Preds)
674 if (getSingleUnscheduledSucc(PI.getSUnit()) == SU)
Sergei Larinef4cc112012-09-10 17:31:34 +0000675 ++NumNodesBlocking;
676 }
677 ResCount += (NumNodesBlocking * ScaleTwo);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000678
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000679 DEBUG(if (verbose) {
680 std::stringstream dbgstr;
681 dbgstr << "blk " << std::setw(2) << NumNodesBlocking << ")|";
682 dbgs() << dbgstr.str();
683 });
684
Sergei Larin4d8986a2012-09-04 14:49:56 +0000685 // Factor in reg pressure as a heuristic.
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000686 if (!IgnoreBBRegPressure) {
687 // Decrease priority by the amount that register pressure exceeds the limit.
688 ResCount -= (Delta.Excess.getUnitInc()*PriorityOne);
689 // Decrease priority if register pressure exceeds the limit.
690 ResCount -= (Delta.CriticalMax.getUnitInc()*PriorityOne);
691 // Decrease priority slightly if register pressure would increase over the
692 // current maximum.
693 ResCount -= (Delta.CurrentMax.getUnitInc()*PriorityTwo);
694 DEBUG(if (verbose) {
695 dbgs() << "RP " << Delta.Excess.getUnitInc() << "/"
696 << Delta.CriticalMax.getUnitInc() <<"/"
697 << Delta.CurrentMax.getUnitInc() << ")|";
698 });
699 }
Sergei Larin4d8986a2012-09-04 14:49:56 +0000700
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000701 // Give a little extra priority to a .cur instruction if there is a resource
702 // available for it.
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000703 auto &QST = DAG->MF.getSubtarget<HexagonSubtarget>();
704 auto &QII = *QST.getInstrInfo();
705
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000706 // Give a little extra priority to a .cur instruction if there is a resource
707 // available for it.
708 if (SU->isInstr() && QII.mayBeCurLoad(SU->getInstr())) {
709 if (Q.getID() == TopQID && Top.ResourceModel->isResourceAvailable(SU)) {
710 ResCount += PriorityTwo;
711 DEBUG(if (verbose) dbgs() << "C|");
712 } else if (Q.getID() == BotQID &&
713 Bot.ResourceModel->isResourceAvailable(SU)) {
714 ResCount += PriorityTwo;
715 DEBUG(if (verbose) dbgs() << "C|");
716 }
717 }
718
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000719 // Give preference to a zero latency instruction if the dependent
720 // instruction is in the current packet.
721 if (Q.getID() == TopQID) {
722 for (const SDep &PI : SU->Preds) {
723 if (!PI.getSUnit()->getInstr()->isPseudo() && PI.isAssignedRegDep() &&
724 PI.getLatency() == 0 &&
725 Top.ResourceModel->isInPacket(PI.getSUnit())) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000726 ResCount += PriorityThree;
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000727 DEBUG(if (verbose) dbgs() << "Z|");
728 }
729 }
730 } else {
731 for (const SDep &SI : SU->Succs) {
732 if (!SI.getSUnit()->getInstr()->isPseudo() && SI.isAssignedRegDep() &&
733 SI.getLatency() == 0 &&
734 Bot.ResourceModel->isInPacket(SI.getSUnit())) {
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000735 ResCount += PriorityThree;
Krzysztof Parzyszek408e3002016-07-15 21:34:02 +0000736 DEBUG(if (verbose) dbgs() << "Z|");
737 }
738 }
739 }
740
Krzysztof Parzyszek6c715e12016-07-15 20:16:03 +0000741 // Give less preference to an instruction that will cause a stall with
742 // an instruction in the previous packet.
743 if (QII.isV60VectorInstruction(Instr)) {
744 // Check for stalls in the previous packet.
745 if (Q.getID() == TopQID) {
746 for (auto J : Top.ResourceModel->OldPacket)
747 if (QII.producesStall(J->getInstr(), Instr))
748 ResCount -= PriorityOne;
749 } else {
750 for (auto J : Bot.ResourceModel->OldPacket)
751 if (QII.producesStall(Instr, J->getInstr()))
752 ResCount -= PriorityOne;
753 }
754 }
755
Krzysztof Parzyszek3467e9d2016-07-18 14:52:13 +0000756 // If the instruction has a non-zero latency dependence with an instruction in
757 // the current packet, then it should not be scheduled yet. The case occurs
758 // when the dependent instruction is scheduled in a new packet, so the
759 // scheduler updates the current cycle and pending instructions become
760 // available.
761 if (CheckEarlyAvail) {
762 if (Q.getID() == TopQID) {
763 for (const auto &PI : SU->Preds) {
764 if (PI.getLatency() > 0 &&
765 Top.ResourceModel->isInPacket(PI.getSUnit())) {
766 ResCount -= PriorityOne;
767 DEBUG(if (verbose) dbgs() << "D|");
768 }
769 }
770 } else {
771 for (const auto &SI : SU->Succs) {
772 if (SI.getLatency() > 0 &&
773 Bot.ResourceModel->isInPacket(SI.getSUnit())) {
774 ResCount -= PriorityOne;
775 DEBUG(if (verbose) dbgs() << "D|");
776 }
777 }
778 }
779 }
780
781 // Give less preference to an instruction that will cause a stall with
782 // an instruction in the previous packet.
783 if (QII.isV60VectorInstruction(Instr)) {
784 // Check for stalls in the previous packet.
785 if (Q.getID() == TopQID) {
786 for (auto J : Top.ResourceModel->OldPacket)
787 if (QII.producesStall(J->getInstr(), Instr))
788 ResCount -= PriorityOne;
789 } else {
790 for (auto J : Bot.ResourceModel->OldPacket)
791 if (QII.producesStall(Instr, J->getInstr()))
792 ResCount -= PriorityOne;
793 }
794 }
795
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000796 DEBUG(if (verbose) {
797 std::stringstream dbgstr;
798 dbgstr << "Total " << std::setw(4) << ResCount << ")";
799 dbgs() << dbgstr.str();
800 });
Sergei Larin4d8986a2012-09-04 14:49:56 +0000801
802 return ResCount;
803}
804
805/// Pick the best candidate from the top queue.
806///
807/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
808/// DAG building. To adjust for the current scheduling location we need to
809/// maintain the number of vreg uses remaining to be top-scheduled.
810ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
811pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
812 SchedCandidate &Candidate) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000813 DEBUG(if (SchedDebugVerboseLevel > 1)
814 readyQueueVerboseDump(RPTracker, Candidate, Q);
815 else Q.dump(););
Sergei Larin4d8986a2012-09-04 14:49:56 +0000816
817 // getMaxPressureDelta temporarily modifies the tracker.
818 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
819
820 // BestSU remains NULL if no top candidates beat the best existing candidate.
821 CandResult FoundCandidate = NoCand;
822 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
823 RegPressureDelta RPDelta;
824 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
825 DAG->getRegionCriticalPSets(),
826 DAG->getRegPressure().MaxSetPressure);
827
828 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
829
830 // Initialize the candidate if needed.
831 if (!Candidate.SU) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000832 DEBUG(traceCandidate("DCAND", Q, *I, CurrentCost));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000833 Candidate.SU = *I;
834 Candidate.RPDelta = RPDelta;
835 Candidate.SCost = CurrentCost;
836 FoundCandidate = NodeOrder;
837 continue;
838 }
839
Sergei Larin4d8986a2012-09-04 14:49:56 +0000840 // Best cost.
841 if (CurrentCost > Candidate.SCost) {
Krzysztof Parzyszekf05dc4d2016-07-18 15:47:25 +0000842 DEBUG(traceCandidate("CCAND", Q, *I, CurrentCost));
Sergei Larin4d8986a2012-09-04 14:49:56 +0000843 Candidate.SU = *I;
844 Candidate.RPDelta = RPDelta;
845 Candidate.SCost = CurrentCost;
846 FoundCandidate = BestCost;
847 continue;
848 }
849
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000850 // Tie breaker using Timing Class.
851 if (!DisableTCTie) {
852 auto &QST = DAG->MF.getSubtarget<HexagonSubtarget>();
853 auto &QII = *QST.getInstrInfo();
854
855 const MachineInstr *MI = (*I)->getInstr();
856 const MachineInstr *CandI = Candidate.SU->getInstr();
857 const InstrItineraryData *InstrItins = QST.getInstrItineraryData();
858
859 unsigned InstrLatency = QII.getInstrTimingClassLatency(InstrItins, MI);
860 unsigned CandLatency = QII.getInstrTimingClassLatency(InstrItins, CandI);
861 DEBUG(dbgs() << "TC Tie Breaker Cand: "
862 << CandLatency << " Instr:" << InstrLatency << "\n"
863 << *MI << *CandI << "\n");
864 if (Q.getID() == TopQID && CurrentCost == Candidate.SCost) {
865 if (InstrLatency < CandLatency && TopUseShorterTie) {
866 Candidate.SU = *I;
867 Candidate.RPDelta = RPDelta;
868 Candidate.SCost = CurrentCost;
869 FoundCandidate = BestCost;
870 DEBUG(dbgs() << "Used top shorter tie breaker\n");
871 continue;
872 } else if (InstrLatency > CandLatency && !TopUseShorterTie) {
873 Candidate.SU = *I;
874 Candidate.RPDelta = RPDelta;
875 Candidate.SCost = CurrentCost;
876 FoundCandidate = BestCost;
877 DEBUG(dbgs() << "Used top longer tie breaker\n");
878 continue;
879 }
880 } else if (Q.getID() == BotQID && CurrentCost == Candidate.SCost) {
881 if (InstrLatency < CandLatency && BotUseShorterTie) {
882 Candidate.SU = *I;
883 Candidate.RPDelta = RPDelta;
884 Candidate.SCost = CurrentCost;
885 FoundCandidate = BestCost;
886 DEBUG(dbgs() << "Used Bot shorter tie breaker\n");
887 continue;
888 } else if (InstrLatency > CandLatency && !BotUseShorterTie) {
889 Candidate.SU = *I;
890 Candidate.RPDelta = RPDelta;
891 Candidate.SCost = CurrentCost;
892 FoundCandidate = BestCost;
893 DEBUG(dbgs() << "Used Bot longer tie breaker\n");
894 continue;
895 }
896 }
897 }
898
Krzysztof Parzyszek748d3ef2016-07-18 14:23:10 +0000899 if (CurrentCost == Candidate.SCost) {
900 if ((Q.getID() == TopQID &&
901 (*I)->Succs.size() > Candidate.SU->Succs.size()) ||
902 (Q.getID() == BotQID &&
903 (*I)->Preds.size() < Candidate.SU->Preds.size())) {
904 DEBUG(traceCandidate("SPCAND", Q, *I, CurrentCost));
905 Candidate.SU = *I;
906 Candidate.RPDelta = RPDelta;
907 Candidate.SCost = CurrentCost;
908 FoundCandidate = BestCost;
909 continue;
910 }
911 }
912
Sergei Larin4d8986a2012-09-04 14:49:56 +0000913 // Fall through to original instruction order.
914 // Only consider node order if Candidate was chosen from this Q.
915 if (FoundCandidate == NoCand)
916 continue;
917 }
918 return FoundCandidate;
919}
920
921/// Pick the best candidate node from either the top or bottom queue.
922SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
923 // Schedule as far as possible in the direction of no choice. This is most
924 // efficient, but also provides the best heuristics for CriticalPSets.
925 if (SUnit *SU = Bot.pickOnlyChoice()) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000926 DEBUG(dbgs() << "Picked only Bottom\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000927 IsTopNode = false;
928 return SU;
929 }
930 if (SUnit *SU = Top.pickOnlyChoice()) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000931 DEBUG(dbgs() << "Picked only Top\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000932 IsTopNode = true;
933 return SU;
934 }
935 SchedCandidate BotCand;
936 // Prefer bottom scheduling when heuristics are silent.
937 CandResult BotResult = pickNodeFromQueue(Bot.Available,
938 DAG->getBotRPTracker(), BotCand);
939 assert(BotResult != NoCand && "failed to find the first candidate");
940
941 // If either Q has a single candidate that provides the least increase in
942 // Excess pressure, we can immediately schedule from that Q.
943 //
944 // RegionCriticalPSets summarizes the pressure within the scheduled region and
945 // affects picking from either Q. If scheduling in one direction must
946 // increase pressure for one of the excess PSets, then schedule in that
947 // direction first to provide more freedom in the other direction.
948 if (BotResult == SingleExcess || BotResult == SingleCritical) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000949 DEBUG(dbgs() << "Prefered Bottom Node\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000950 IsTopNode = false;
951 return BotCand.SU;
952 }
953 // Check if the top Q has a better candidate.
954 SchedCandidate TopCand;
955 CandResult TopResult = pickNodeFromQueue(Top.Available,
956 DAG->getTopRPTracker(), TopCand);
957 assert(TopResult != NoCand && "failed to find the first candidate");
958
959 if (TopResult == SingleExcess || TopResult == SingleCritical) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000960 DEBUG(dbgs() << "Prefered Top Node\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000961 IsTopNode = true;
962 return TopCand.SU;
963 }
964 // If either Q has a single candidate that minimizes pressure above the
965 // original region's pressure pick it.
966 if (BotResult == SingleMax) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000967 DEBUG(dbgs() << "Prefered Bottom Node SingleMax\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000968 IsTopNode = false;
969 return BotCand.SU;
970 }
971 if (TopResult == SingleMax) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000972 DEBUG(dbgs() << "Prefered Top Node SingleMax\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000973 IsTopNode = true;
974 return TopCand.SU;
975 }
976 if (TopCand.SCost > BotCand.SCost) {
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000977 DEBUG(dbgs() << "Prefered Top Node Cost\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000978 IsTopNode = true;
979 return TopCand.SU;
980 }
981 // Otherwise prefer the bottom candidate in node order.
Krzysztof Parzyszek393b3792016-07-18 15:17:10 +0000982 DEBUG(dbgs() << "Prefered Bottom in Node order\n");
Sergei Larin4d8986a2012-09-04 14:49:56 +0000983 IsTopNode = false;
984 return BotCand.SU;
985}
986
987/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
988SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
989 if (DAG->top() == DAG->bottom()) {
990 assert(Top.Available.empty() && Top.Pending.empty() &&
991 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topper062a2ba2014-04-25 05:30:21 +0000992 return nullptr;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000993 }
994 SUnit *SU;
Andrew Trick7a8e1002012-09-11 00:39:15 +0000995 if (llvm::ForceTopDown) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000996 SU = Top.pickOnlyChoice();
997 if (!SU) {
998 SchedCandidate TopCand;
999 CandResult TopResult =
1000 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
1001 assert(TopResult != NoCand && "failed to find the first candidate");
1002 (void)TopResult;
1003 SU = TopCand.SU;
1004 }
1005 IsTopNode = true;
Andrew Trick7a8e1002012-09-11 00:39:15 +00001006 } else if (llvm::ForceBottomUp) {
Sergei Larin4d8986a2012-09-04 14:49:56 +00001007 SU = Bot.pickOnlyChoice();
1008 if (!SU) {
1009 SchedCandidate BotCand;
1010 CandResult BotResult =
1011 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
1012 assert(BotResult != NoCand && "failed to find the first candidate");
1013 (void)BotResult;
1014 SU = BotCand.SU;
1015 }
1016 IsTopNode = false;
1017 } else {
1018 SU = pickNodeBidrectional(IsTopNode);
1019 }
1020 if (SU->isTopReady())
1021 Top.removeReady(SU);
1022 if (SU->isBottomReady())
1023 Bot.removeReady(SU);
1024
1025 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
1026 << " Scheduling Instruction in cycle "
1027 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
1028 SU->dump(DAG));
1029 return SU;
1030}
1031
1032/// Update the scheduler's state after scheduling a node. This is the same node
Sergei Larinef4cc112012-09-10 17:31:34 +00001033/// that was just returned by pickNode(). However, VLIWMachineScheduler needs
1034/// to update it's state based on the current cycle before MachineSchedStrategy
1035/// does.
Sergei Larin4d8986a2012-09-04 14:49:56 +00001036void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
1037 if (IsTopNode) {
1038 SU->TopReadyCycle = Top.CurrCycle;
1039 Top.bumpNode(SU);
Sergei Larinef4cc112012-09-10 17:31:34 +00001040 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +00001041 SU->BotReadyCycle = Bot.CurrCycle;
1042 Bot.bumpNode(SU);
1043 }
1044}