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