blob: 36dfaa4233f93babb2bc05d0d0a5f60b81b0f2d9 [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
15#define DEBUG_TYPE "misched"
16
17#include "HexagonMachineScheduler.h"
Sergei Larin4d8986a2012-09-04 14:49:56 +000018#include <queue>
19
20using namespace llvm;
21
Sergei Larin2db64a72012-09-14 15:07:59 +000022/// Platform specific modifications to DAG.
23void VLIWMachineScheduler::postprocessDAG() {
24 SUnit* LastSequentialCall = NULL;
25 // Currently we only catch the situation when compare gets scheduled
26 // before preceding call.
27 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
28 // Remember the call.
29 if (SUnits[su].getInstr()->isCall())
30 LastSequentialCall = &(SUnits[su]);
31 // Look for a compare that defines a predicate.
32 else if (SUnits[su].getInstr()->isCompare() && LastSequentialCall)
Andrew Trickbaeaabb2012-11-06 03:13:46 +000033 SUnits[su].addPred(SDep(LastSequentialCall, SDep::Barrier));
Sergei Larin2db64a72012-09-14 15:07:59 +000034 }
35}
36
Sergei Larin4d8986a2012-09-04 14:49:56 +000037/// Check if scheduling of this SU is possible
38/// in the current packet.
39/// It is _not_ precise (statefull), it is more like
40/// another heuristic. Many corner cases are figured
41/// empirically.
42bool VLIWResourceModel::isResourceAvailable(SUnit *SU) {
43 if (!SU || !SU->getInstr())
44 return false;
45
46 // First see if the pipeline could receive this instruction
47 // in the current cycle.
48 switch (SU->getInstr()->getOpcode()) {
49 default:
50 if (!ResourcesModel->canReserveResources(SU->getInstr()))
51 return false;
52 case TargetOpcode::EXTRACT_SUBREG:
53 case TargetOpcode::INSERT_SUBREG:
54 case TargetOpcode::SUBREG_TO_REG:
55 case TargetOpcode::REG_SEQUENCE:
56 case TargetOpcode::IMPLICIT_DEF:
57 case TargetOpcode::COPY:
58 case TargetOpcode::INLINEASM:
59 break;
60 }
61
62 // Now see if there are no other dependencies to instructions already
63 // in the packet.
64 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
65 if (Packet[i]->Succs.size() == 0)
66 continue;
67 for (SUnit::const_succ_iterator I = Packet[i]->Succs.begin(),
68 E = Packet[i]->Succs.end(); I != E; ++I) {
69 // Since we do not add pseudos to packets, might as well
70 // ignore order dependencies.
71 if (I->isCtrl())
72 continue;
73
74 if (I->getSUnit() == SU)
75 return false;
76 }
77 }
78 return true;
79}
80
81/// Keep track of available resources.
Sergei Larinef4cc112012-09-10 17:31:34 +000082bool VLIWResourceModel::reserveResources(SUnit *SU) {
83 bool startNewCycle = false;
Sergei Larin2db64a72012-09-14 15:07:59 +000084 // Artificially reset state.
85 if (!SU) {
86 ResourcesModel->clearResources();
87 Packet.clear();
88 TotalPackets++;
89 return false;
90 }
Sergei Larin4d8986a2012-09-04 14:49:56 +000091 // If this SU does not fit in the packet
92 // start a new one.
93 if (!isResourceAvailable(SU)) {
94 ResourcesModel->clearResources();
95 Packet.clear();
96 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +000097 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +000098 }
99
100 switch (SU->getInstr()->getOpcode()) {
101 default:
102 ResourcesModel->reserveResources(SU->getInstr());
103 break;
104 case TargetOpcode::EXTRACT_SUBREG:
105 case TargetOpcode::INSERT_SUBREG:
106 case TargetOpcode::SUBREG_TO_REG:
107 case TargetOpcode::REG_SEQUENCE:
108 case TargetOpcode::IMPLICIT_DEF:
109 case TargetOpcode::KILL:
110 case TargetOpcode::PROLOG_LABEL:
111 case TargetOpcode::EH_LABEL:
112 case TargetOpcode::COPY:
113 case TargetOpcode::INLINEASM:
114 break;
115 }
116 Packet.push_back(SU);
117
118#ifndef NDEBUG
119 DEBUG(dbgs() << "Packet[" << TotalPackets << "]:\n");
120 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
121 DEBUG(dbgs() << "\t[" << i << "] SU(");
Sergei Larinef4cc112012-09-10 17:31:34 +0000122 DEBUG(dbgs() << Packet[i]->NodeNum << ")\t");
123 DEBUG(Packet[i]->getInstr()->dump());
Sergei Larin4d8986a2012-09-04 14:49:56 +0000124 }
125#endif
126
127 // If packet is now full, reset the state so in the next cycle
128 // we start fresh.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000129 if (Packet.size() >= SchedModel->getIssueWidth()) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000130 ResourcesModel->clearResources();
131 Packet.clear();
132 TotalPackets++;
Sergei Larinef4cc112012-09-10 17:31:34 +0000133 startNewCycle = true;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000134 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000135
136 return startNewCycle;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000137}
138
Sergei Larin4d8986a2012-09-04 14:49:56 +0000139/// schedule - Called back from MachineScheduler::runOnMachineFunction
140/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
141/// only includes instructions that have DAG nodes, not scheduling boundaries.
142void VLIWMachineScheduler::schedule() {
143 DEBUG(dbgs()
144 << "********** MI Converging Scheduling VLIW BB#" << BB->getNumber()
145 << " " << BB->getName()
146 << " in_func " << BB->getParent()->getFunction()->getName()
Benjamin Kramer61f67082012-09-14 12:19:58 +0000147 << " at loop depth " << MLI.getLoopDepth(BB)
Sergei Larin4d8986a2012-09-04 14:49:56 +0000148 << " \n");
149
Andrew Trick7a8e1002012-09-11 00:39:15 +0000150 buildDAGWithRegPressure();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000151
Sergei Larin2db64a72012-09-14 15:07:59 +0000152 // Postprocess the DAG to add platform specific artificial dependencies.
153 postprocessDAG();
154
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000155 SmallVector<SUnit*, 8> TopRoots, BotRoots;
156 findRootsAndBiasEdges(TopRoots, BotRoots);
157
158 // Initialize the strategy before modifying the DAG.
159 SchedImpl->initialize(this);
160
Sergei Larinef4cc112012-09-10 17:31:34 +0000161 // To view Height/Depth correctly, they should be accessed at least once.
162 DEBUG(unsigned maxH = 0;
163 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
164 if (SUnits[su].getHeight() > maxH)
165 maxH = SUnits[su].getHeight();
166 dbgs() << "Max Height " << maxH << "\n";);
167 DEBUG(unsigned maxD = 0;
168 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
169 if (SUnits[su].getDepth() > maxD)
170 maxD = SUnits[su].getDepth();
171 dbgs() << "Max Depth " << maxD << "\n";);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000172 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
173 SUnits[su].dumpAll(this));
174
Andrew Tricke2c3f5c2013-01-25 06:33:57 +0000175 initQueues(TopRoots, BotRoots);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000176
Sergei Larin4d8986a2012-09-04 14:49:56 +0000177 bool IsTopNode = false;
178 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
179 if (!checkSchedLimit())
180 break;
181
Andrew Trick7a8e1002012-09-11 00:39:15 +0000182 scheduleMI(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000183
Andrew Trick7a8e1002012-09-11 00:39:15 +0000184 updateQueues(SU, IsTopNode);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000185 }
186 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
187
Sergei Larin4d8986a2012-09-04 14:49:56 +0000188 placeDebugValues();
189}
190
Andrew Trick7a8e1002012-09-11 00:39:15 +0000191void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
192 DAG = static_cast<VLIWMachineScheduler*>(dag);
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000193 SchedModel = DAG->getSchedModel();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000194 TRI = DAG->TRI;
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000195 Top.init(DAG, SchedModel);
196 Bot.init(DAG, SchedModel);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000197
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000198 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
199 // are disabled, then these HazardRecs will be disabled.
200 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000201 const TargetMachine &TM = DAG->MF.getTarget();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000202 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
203 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
204
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000205 Top.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
206 Bot.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
Sergei Larinef4cc112012-09-10 17:31:34 +0000207
Andrew Trick7a8e1002012-09-11 00:39:15 +0000208 assert((!llvm::ForceTopDown || !llvm::ForceBottomUp) &&
Sergei Larin4d8986a2012-09-04 14:49:56 +0000209 "-misched-topdown incompatible with -misched-bottomup");
210}
211
212void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
213 if (SU->isScheduled)
214 return;
215
216 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
217 I != E; ++I) {
218 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
219 unsigned MinLatency = I->getMinLatency();
220#ifndef NDEBUG
221 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
222#endif
223 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
224 SU->TopReadyCycle = PredReadyCycle + MinLatency;
225 }
226 Top.releaseNode(SU, SU->TopReadyCycle);
227}
228
229void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
230 if (SU->isScheduled)
231 return;
232
233 assert(SU->getInstr() && "Scheduled SUnit must have instr");
234
235 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
236 I != E; ++I) {
237 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
238 unsigned MinLatency = I->getMinLatency();
239#ifndef NDEBUG
240 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
241#endif
242 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
243 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
244 }
245 Bot.releaseNode(SU, SU->BotReadyCycle);
246}
247
248/// Does this SU have a hazard within the current instruction group.
249///
250/// The scheduler supports two modes of hazard recognition. The first is the
251/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
252/// supports highly complicated in-order reservation tables
253/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
254///
255/// The second is a streamlined mechanism that checks for hazards based on
256/// simple counters that the scheduler itself maintains. It explicitly checks
257/// for instruction dispatch limitations, including the number of micro-ops that
258/// can dispatch per cycle.
259///
260/// TODO: Also check whether the SU must start a new group.
261bool ConvergingVLIWScheduler::SchedBoundary::checkHazard(SUnit *SU) {
262 if (HazardRec->isEnabled())
263 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
264
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000265 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
266 if (IssueCount + uops > SchedModel->getIssueWidth())
Sergei Larin4d8986a2012-09-04 14:49:56 +0000267 return true;
268
269 return false;
270}
271
272void ConvergingVLIWScheduler::SchedBoundary::releaseNode(SUnit *SU,
273 unsigned ReadyCycle) {
274 if (ReadyCycle < MinReadyCycle)
275 MinReadyCycle = ReadyCycle;
276
277 // Check for interlocks first. For the purpose of other heuristics, an
278 // instruction that cannot issue appears as if it's not in the ReadyQueue.
279 if (ReadyCycle > CurrCycle || checkHazard(SU))
280
281 Pending.push(SU);
282 else
283 Available.push(SU);
284}
285
286/// Move the boundary of scheduled code by one cycle.
287void ConvergingVLIWScheduler::SchedBoundary::bumpCycle() {
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000288 unsigned Width = SchedModel->getIssueWidth();
Sergei Larin4d8986a2012-09-04 14:49:56 +0000289 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
290
291 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
292 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
293
294 if (!HazardRec->isEnabled()) {
295 // Bypass HazardRec virtual calls.
296 CurrCycle = NextCycle;
Sergei Larinef4cc112012-09-10 17:31:34 +0000297 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000298 // Bypass getHazardType calls in case of long latency.
299 for (; CurrCycle != NextCycle; ++CurrCycle) {
300 if (isTop())
301 HazardRec->AdvanceCycle();
302 else
303 HazardRec->RecedeCycle();
304 }
305 }
306 CheckPending = true;
307
308 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
309 << CurrCycle << '\n');
310}
311
312/// Move the boundary of scheduled code by one SUnit.
313void ConvergingVLIWScheduler::SchedBoundary::bumpNode(SUnit *SU) {
Sergei Larinef4cc112012-09-10 17:31:34 +0000314 bool startNewCycle = false;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000315
316 // Update the reservation table.
317 if (HazardRec->isEnabled()) {
318 if (!isTop() && SU->isCall) {
319 // Calls are scheduled with their preceding instructions. For bottom-up
320 // scheduling, clear the pipeline state before emitting.
321 HazardRec->Reset();
322 }
323 HazardRec->EmitInstruction(SU);
324 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000325
326 // Update DFA model.
327 startNewCycle = ResourceModel->reserveResources(SU);
328
Sergei Larin4d8986a2012-09-04 14:49:56 +0000329 // Check the instruction group dispatch limit.
330 // TODO: Check if this SU must end a dispatch group.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000331 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
Sergei Larinef4cc112012-09-10 17:31:34 +0000332 if (startNewCycle) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000333 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
334 bumpCycle();
335 }
Sergei Larinef4cc112012-09-10 17:31:34 +0000336 else
337 DEBUG(dbgs() << "*** IssueCount " << IssueCount
338 << " at cycle " << CurrCycle << '\n');
Sergei Larin4d8986a2012-09-04 14:49:56 +0000339}
340
341/// Release pending ready nodes in to the available queue. This makes them
342/// visible to heuristics.
343void ConvergingVLIWScheduler::SchedBoundary::releasePending() {
344 // If the available queue is empty, it is safe to reset MinReadyCycle.
345 if (Available.empty())
346 MinReadyCycle = UINT_MAX;
347
348 // Check to see if any of the pending instructions are ready to issue. If
349 // so, add them to the available queue.
350 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
351 SUnit *SU = *(Pending.begin()+i);
352 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
353
354 if (ReadyCycle < MinReadyCycle)
355 MinReadyCycle = ReadyCycle;
356
357 if (ReadyCycle > CurrCycle)
358 continue;
359
360 if (checkHazard(SU))
361 continue;
362
363 Available.push(SU);
364 Pending.remove(Pending.begin()+i);
365 --i; --e;
366 }
367 CheckPending = false;
368}
369
370/// Remove SU from the ready set for this boundary.
371void ConvergingVLIWScheduler::SchedBoundary::removeReady(SUnit *SU) {
372 if (Available.isInQueue(SU))
373 Available.remove(Available.find(SU));
374 else {
375 assert(Pending.isInQueue(SU) && "bad ready count");
376 Pending.remove(Pending.find(SU));
377 }
378}
379
380/// If this queue only has one ready candidate, return it. As a side effect,
381/// advance the cycle until at least one node is ready. If multiple instructions
382/// are ready, return NULL.
383SUnit *ConvergingVLIWScheduler::SchedBoundary::pickOnlyChoice() {
384 if (CheckPending)
385 releasePending();
386
387 for (unsigned i = 0; Available.empty(); ++i) {
388 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
389 "permanent hazard"); (void)i;
Sergei Larin2db64a72012-09-14 15:07:59 +0000390 ResourceModel->reserveResources(0);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000391 bumpCycle();
392 releasePending();
393 }
394 if (Available.size() == 1)
395 return *Available.begin();
396 return NULL;
397}
398
399#ifndef NDEBUG
Sergei Larinef4cc112012-09-10 17:31:34 +0000400void ConvergingVLIWScheduler::traceCandidate(const char *Label,
401 const ReadyQueue &Q,
402 SUnit *SU, PressureElement P) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000403 dbgs() << Label << " " << Q.getName() << " ";
404 if (P.isValid())
405 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
406 << " ";
407 else
408 dbgs() << " ";
409 SU->dump(DAG);
410}
411#endif
412
Sergei Larinef4cc112012-09-10 17:31:34 +0000413/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
414/// of SU, return it, otherwise return null.
415static SUnit *getSingleUnscheduledPred(SUnit *SU) {
416 SUnit *OnlyAvailablePred = 0;
417 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
418 I != E; ++I) {
419 SUnit &Pred = *I->getSUnit();
420 if (!Pred.isScheduled) {
421 // We found an available, but not scheduled, predecessor. If it's the
422 // only one we have found, keep track of it... otherwise give up.
423 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
424 return 0;
425 OnlyAvailablePred = &Pred;
426 }
427 }
428 return OnlyAvailablePred;
429}
430
431/// getSingleUnscheduledSucc - If there is exactly one unscheduled successor
432/// of SU, return it, otherwise return null.
433static SUnit *getSingleUnscheduledSucc(SUnit *SU) {
434 SUnit *OnlyAvailableSucc = 0;
435 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
436 I != E; ++I) {
437 SUnit &Succ = *I->getSUnit();
438 if (!Succ.isScheduled) {
439 // We found an available, but not scheduled, successor. If it's the
440 // only one we have found, keep track of it... otherwise give up.
441 if (OnlyAvailableSucc && OnlyAvailableSucc != &Succ)
442 return 0;
443 OnlyAvailableSucc = &Succ;
444 }
445 }
446 return OnlyAvailableSucc;
447}
448
Sergei Larin4d8986a2012-09-04 14:49:56 +0000449// Constants used to denote relative importance of
450// heuristic components for cost computation.
451static const unsigned PriorityOne = 200;
Sergei Larinef4cc112012-09-10 17:31:34 +0000452static const unsigned PriorityTwo = 100;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000453static const unsigned PriorityThree = 50;
Sergei Larinef4cc112012-09-10 17:31:34 +0000454static const unsigned PriorityFour = 20;
Sergei Larin4d8986a2012-09-04 14:49:56 +0000455static const unsigned ScaleTwo = 10;
456static const unsigned FactorOne = 2;
457
458/// Single point to compute overall scheduling cost.
459/// TODO: More heuristics will be used soon.
460int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
461 SchedCandidate &Candidate,
462 RegPressureDelta &Delta,
463 bool verbose) {
464 // Initial trivial priority.
465 int ResCount = 1;
466
467 // Do not waste time on a node that is already scheduled.
468 if (!SU || SU->isScheduled)
469 return ResCount;
470
471 // Forced priority is high.
472 if (SU->isScheduleHigh)
473 ResCount += PriorityOne;
474
475 // Critical path first.
Sergei Larinef4cc112012-09-10 17:31:34 +0000476 if (Q.getID() == TopQID) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000477 ResCount += (SU->getHeight() * ScaleTwo);
Sergei Larinef4cc112012-09-10 17:31:34 +0000478
479 // If resources are available for it, multiply the
480 // chance of scheduling.
481 if (Top.ResourceModel->isResourceAvailable(SU))
482 ResCount <<= FactorOne;
483 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000484 ResCount += (SU->getDepth() * ScaleTwo);
485
Sergei Larinef4cc112012-09-10 17:31:34 +0000486 // If resources are available for it, multiply the
487 // chance of scheduling.
488 if (Bot.ResourceModel->isResourceAvailable(SU))
489 ResCount <<= FactorOne;
490 }
491
492 unsigned NumNodesBlocking = 0;
493 if (Q.getID() == TopQID) {
494 // How many SUs does it block from scheduling?
495 // Look at all of the successors of this node.
496 // Count the number of nodes that
497 // this node is the sole unscheduled node for.
498 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
499 I != E; ++I)
500 if (getSingleUnscheduledPred(I->getSUnit()) == SU)
501 ++NumNodesBlocking;
502 } else {
503 // How many unscheduled predecessors block this node?
504 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
505 I != E; ++I)
506 if (getSingleUnscheduledSucc(I->getSUnit()) == SU)
507 ++NumNodesBlocking;
508 }
509 ResCount += (NumNodesBlocking * ScaleTwo);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000510
511 // Factor in reg pressure as a heuristic.
Sergei Larinef4cc112012-09-10 17:31:34 +0000512 ResCount -= (Delta.Excess.UnitIncrease*PriorityThree);
513 ResCount -= (Delta.CriticalMax.UnitIncrease*PriorityThree);
Sergei Larin4d8986a2012-09-04 14:49:56 +0000514
515 DEBUG(if (verbose) dbgs() << " Total(" << ResCount << ")");
516
517 return ResCount;
518}
519
520/// Pick the best candidate from the top queue.
521///
522/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
523/// DAG building. To adjust for the current scheduling location we need to
524/// maintain the number of vreg uses remaining to be top-scheduled.
525ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
526pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
527 SchedCandidate &Candidate) {
528 DEBUG(Q.dump());
529
530 // getMaxPressureDelta temporarily modifies the tracker.
531 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
532
533 // BestSU remains NULL if no top candidates beat the best existing candidate.
534 CandResult FoundCandidate = NoCand;
535 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
536 RegPressureDelta RPDelta;
537 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
538 DAG->getRegionCriticalPSets(),
539 DAG->getRegPressure().MaxSetPressure);
540
541 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
542
543 // Initialize the candidate if needed.
544 if (!Candidate.SU) {
545 Candidate.SU = *I;
546 Candidate.RPDelta = RPDelta;
547 Candidate.SCost = CurrentCost;
548 FoundCandidate = NodeOrder;
549 continue;
550 }
551
Sergei Larin4d8986a2012-09-04 14:49:56 +0000552 // Best cost.
553 if (CurrentCost > Candidate.SCost) {
554 DEBUG(traceCandidate("CCAND", Q, *I));
555 Candidate.SU = *I;
556 Candidate.RPDelta = RPDelta;
557 Candidate.SCost = CurrentCost;
558 FoundCandidate = BestCost;
559 continue;
560 }
561
562 // Fall through to original instruction order.
563 // Only consider node order if Candidate was chosen from this Q.
564 if (FoundCandidate == NoCand)
565 continue;
566 }
567 return FoundCandidate;
568}
569
570/// Pick the best candidate node from either the top or bottom queue.
571SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
572 // Schedule as far as possible in the direction of no choice. This is most
573 // efficient, but also provides the best heuristics for CriticalPSets.
574 if (SUnit *SU = Bot.pickOnlyChoice()) {
575 IsTopNode = false;
576 return SU;
577 }
578 if (SUnit *SU = Top.pickOnlyChoice()) {
579 IsTopNode = true;
580 return SU;
581 }
582 SchedCandidate BotCand;
583 // Prefer bottom scheduling when heuristics are silent.
584 CandResult BotResult = pickNodeFromQueue(Bot.Available,
585 DAG->getBotRPTracker(), BotCand);
586 assert(BotResult != NoCand && "failed to find the first candidate");
587
588 // If either Q has a single candidate that provides the least increase in
589 // Excess pressure, we can immediately schedule from that Q.
590 //
591 // RegionCriticalPSets summarizes the pressure within the scheduled region and
592 // affects picking from either Q. If scheduling in one direction must
593 // increase pressure for one of the excess PSets, then schedule in that
594 // direction first to provide more freedom in the other direction.
595 if (BotResult == SingleExcess || BotResult == SingleCritical) {
596 IsTopNode = false;
597 return BotCand.SU;
598 }
599 // Check if the top Q has a better candidate.
600 SchedCandidate TopCand;
601 CandResult TopResult = pickNodeFromQueue(Top.Available,
602 DAG->getTopRPTracker(), TopCand);
603 assert(TopResult != NoCand && "failed to find the first candidate");
604
605 if (TopResult == SingleExcess || TopResult == SingleCritical) {
606 IsTopNode = true;
607 return TopCand.SU;
608 }
609 // If either Q has a single candidate that minimizes pressure above the
610 // original region's pressure pick it.
611 if (BotResult == SingleMax) {
612 IsTopNode = false;
613 return BotCand.SU;
614 }
615 if (TopResult == SingleMax) {
616 IsTopNode = true;
617 return TopCand.SU;
618 }
619 if (TopCand.SCost > BotCand.SCost) {
620 IsTopNode = true;
621 return TopCand.SU;
622 }
623 // Otherwise prefer the bottom candidate in node order.
624 IsTopNode = false;
625 return BotCand.SU;
626}
627
628/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
629SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
630 if (DAG->top() == DAG->bottom()) {
631 assert(Top.Available.empty() && Top.Pending.empty() &&
632 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
633 return NULL;
634 }
635 SUnit *SU;
Andrew Trick7a8e1002012-09-11 00:39:15 +0000636 if (llvm::ForceTopDown) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000637 SU = Top.pickOnlyChoice();
638 if (!SU) {
639 SchedCandidate TopCand;
640 CandResult TopResult =
641 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
642 assert(TopResult != NoCand && "failed to find the first candidate");
643 (void)TopResult;
644 SU = TopCand.SU;
645 }
646 IsTopNode = true;
Andrew Trick7a8e1002012-09-11 00:39:15 +0000647 } else if (llvm::ForceBottomUp) {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000648 SU = Bot.pickOnlyChoice();
649 if (!SU) {
650 SchedCandidate BotCand;
651 CandResult BotResult =
652 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
653 assert(BotResult != NoCand && "failed to find the first candidate");
654 (void)BotResult;
655 SU = BotCand.SU;
656 }
657 IsTopNode = false;
658 } else {
659 SU = pickNodeBidrectional(IsTopNode);
660 }
661 if (SU->isTopReady())
662 Top.removeReady(SU);
663 if (SU->isBottomReady())
664 Bot.removeReady(SU);
665
666 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
667 << " Scheduling Instruction in cycle "
668 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
669 SU->dump(DAG));
670 return SU;
671}
672
673/// Update the scheduler's state after scheduling a node. This is the same node
Sergei Larinef4cc112012-09-10 17:31:34 +0000674/// that was just returned by pickNode(). However, VLIWMachineScheduler needs
675/// to update it's state based on the current cycle before MachineSchedStrategy
676/// does.
Sergei Larin4d8986a2012-09-04 14:49:56 +0000677void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
678 if (IsTopNode) {
679 SU->TopReadyCycle = Top.CurrCycle;
680 Top.bumpNode(SU);
Sergei Larinef4cc112012-09-10 17:31:34 +0000681 } else {
Sergei Larin4d8986a2012-09-04 14:49:56 +0000682 SU->BotReadyCycle = Bot.CurrCycle;
683 Bot.bumpNode(SU);
684 }
685}
686