1 //===- HexagonMachineScheduler.cpp - MI Scheduler for Hexagon -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "misched"
17 #include "HexagonMachineScheduler.h"
23 /// Platform specific modifications to DAG.
24 void 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) {
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)
34 SUnits[su].addPred(SDep(LastSequentialCall, SDep::Barrier));
38 /// 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
43 bool VLIWResourceModel::isResourceAvailable(SUnit *SU) {
44 if (!SU || !SU->getInstr())
47 // First see if the pipeline could receive this instruction
48 // in the current cycle.
49 switch (SU->getInstr()->getOpcode()) {
51 if (!ResourcesModel->canReserveResources(SU->getInstr()))
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:
63 // Now see if there are no other dependencies to instructions already
65 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
66 if (Packet[i]->Succs.size() == 0)
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.
75 if (I->getSUnit() == SU)
82 /// Keep track of available resources.
83 bool VLIWResourceModel::reserveResources(SUnit *SU) {
84 bool startNewCycle = false;
85 // Artificially reset state.
87 ResourcesModel->clearResources();
92 // If this SU does not fit in the packet
94 if (!isResourceAvailable(SU)) {
95 ResourcesModel->clearResources();
101 switch (SU->getInstr()->getOpcode()) {
103 ResourcesModel->reserveResources(SU->getInstr());
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:
117 Packet.push_back(SU);
120 DEBUG(dbgs() << "Packet[" << TotalPackets << "]:\n");
121 for (unsigned i = 0, e = Packet.size(); i != e; ++i) {
122 DEBUG(dbgs() << "\t[" << i << "] SU(");
123 DEBUG(dbgs() << Packet[i]->NodeNum << ")\t");
124 DEBUG(Packet[i]->getInstr()->dump());
128 // If packet is now full, reset the state so in the next cycle
130 if (Packet.size() >= SchedModel->getIssueWidth()) {
131 ResourcesModel->clearResources();
134 startNewCycle = true;
137 return startNewCycle;
140 /// 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.
143 void VLIWMachineScheduler::schedule() {
145 << "********** MI Converging Scheduling VLIW BB#" << BB->getNumber()
146 << " " << BB->getName()
147 << " in_func " << BB->getParent()->getFunction()->getName()
148 << " at loop depth " << MLI.getLoopDepth(BB)
151 buildDAGWithRegPressure();
153 // Postprocess the DAG to add platform specific artificial dependencies.
156 // To view Height/Depth correctly, they should be accessed at least once.
157 DEBUG(unsigned maxH = 0;
158 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
159 if (SUnits[su].getHeight() > maxH)
160 maxH = SUnits[su].getHeight();
161 dbgs() << "Max Height " << maxH << "\n";);
162 DEBUG(unsigned maxD = 0;
163 for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
164 if (SUnits[su].getDepth() > maxD)
165 maxD = SUnits[su].getDepth();
166 dbgs() << "Max Depth " << maxD << "\n";);
167 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
168 SUnits[su].dumpAll(this));
172 bool IsTopNode = false;
173 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
174 if (!checkSchedLimit())
177 scheduleMI(SU, IsTopNode);
179 updateQueues(SU, IsTopNode);
181 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
186 void ConvergingVLIWScheduler::initialize(ScheduleDAGMI *dag) {
187 DAG = static_cast<VLIWMachineScheduler*>(dag);
188 SchedModel = DAG->getSchedModel();
190 Top.init(DAG, SchedModel);
191 Bot.init(DAG, SchedModel);
193 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
194 // are disabled, then these HazardRecs will be disabled.
195 const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();
196 const TargetMachine &TM = DAG->MF.getTarget();
197 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
198 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
200 Top.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
201 Bot.ResourceModel = new VLIWResourceModel(TM, DAG->getSchedModel());
203 assert((!llvm::ForceTopDown || !llvm::ForceBottomUp) &&
204 "-misched-topdown incompatible with -misched-bottomup");
207 void ConvergingVLIWScheduler::releaseTopNode(SUnit *SU) {
211 for (SUnit::succ_iterator I = SU->Preds.begin(), E = SU->Preds.end();
213 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
214 unsigned MinLatency = I->getMinLatency();
216 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
218 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
219 SU->TopReadyCycle = PredReadyCycle + MinLatency;
221 Top.releaseNode(SU, SU->TopReadyCycle);
224 void ConvergingVLIWScheduler::releaseBottomNode(SUnit *SU) {
228 assert(SU->getInstr() && "Scheduled SUnit must have instr");
230 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
232 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
233 unsigned MinLatency = I->getMinLatency();
235 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
237 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
238 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
240 Bot.releaseNode(SU, SU->BotReadyCycle);
243 /// Does this SU have a hazard within the current instruction group.
245 /// The scheduler supports two modes of hazard recognition. The first is the
246 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
247 /// supports highly complicated in-order reservation tables
248 /// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
250 /// The second is a streamlined mechanism that checks for hazards based on
251 /// simple counters that the scheduler itself maintains. It explicitly checks
252 /// for instruction dispatch limitations, including the number of micro-ops that
253 /// can dispatch per cycle.
255 /// TODO: Also check whether the SU must start a new group.
256 bool ConvergingVLIWScheduler::SchedBoundary::checkHazard(SUnit *SU) {
257 if (HazardRec->isEnabled())
258 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
260 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
261 if (IssueCount + uops > SchedModel->getIssueWidth())
267 void ConvergingVLIWScheduler::SchedBoundary::releaseNode(SUnit *SU,
268 unsigned ReadyCycle) {
269 if (ReadyCycle < MinReadyCycle)
270 MinReadyCycle = ReadyCycle;
272 // Check for interlocks first. For the purpose of other heuristics, an
273 // instruction that cannot issue appears as if it's not in the ReadyQueue.
274 if (ReadyCycle > CurrCycle || checkHazard(SU))
281 /// Move the boundary of scheduled code by one cycle.
282 void ConvergingVLIWScheduler::SchedBoundary::bumpCycle() {
283 unsigned Width = SchedModel->getIssueWidth();
284 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
286 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
287 unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);
289 if (!HazardRec->isEnabled()) {
290 // Bypass HazardRec virtual calls.
291 CurrCycle = NextCycle;
293 // Bypass getHazardType calls in case of long latency.
294 for (; CurrCycle != NextCycle; ++CurrCycle) {
296 HazardRec->AdvanceCycle();
298 HazardRec->RecedeCycle();
303 DEBUG(dbgs() << "*** " << Available.getName() << " cycle "
304 << CurrCycle << '\n');
307 /// Move the boundary of scheduled code by one SUnit.
308 void ConvergingVLIWScheduler::SchedBoundary::bumpNode(SUnit *SU) {
309 bool startNewCycle = false;
311 // Update the reservation table.
312 if (HazardRec->isEnabled()) {
313 if (!isTop() && SU->isCall) {
314 // Calls are scheduled with their preceding instructions. For bottom-up
315 // scheduling, clear the pipeline state before emitting.
318 HazardRec->EmitInstruction(SU);
322 startNewCycle = ResourceModel->reserveResources(SU);
324 // Check the instruction group dispatch limit.
325 // TODO: Check if this SU must end a dispatch group.
326 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
328 DEBUG(dbgs() << "*** Max instrs at cycle " << CurrCycle << '\n');
332 DEBUG(dbgs() << "*** IssueCount " << IssueCount
333 << " at cycle " << CurrCycle << '\n');
336 /// Release pending ready nodes in to the available queue. This makes them
337 /// visible to heuristics.
338 void ConvergingVLIWScheduler::SchedBoundary::releasePending() {
339 // If the available queue is empty, it is safe to reset MinReadyCycle.
340 if (Available.empty())
341 MinReadyCycle = UINT_MAX;
343 // Check to see if any of the pending instructions are ready to issue. If
344 // so, add them to the available queue.
345 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
346 SUnit *SU = *(Pending.begin()+i);
347 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
349 if (ReadyCycle < MinReadyCycle)
350 MinReadyCycle = ReadyCycle;
352 if (ReadyCycle > CurrCycle)
359 Pending.remove(Pending.begin()+i);
362 CheckPending = false;
365 /// Remove SU from the ready set for this boundary.
366 void ConvergingVLIWScheduler::SchedBoundary::removeReady(SUnit *SU) {
367 if (Available.isInQueue(SU))
368 Available.remove(Available.find(SU));
370 assert(Pending.isInQueue(SU) && "bad ready count");
371 Pending.remove(Pending.find(SU));
375 /// If this queue only has one ready candidate, return it. As a side effect,
376 /// advance the cycle until at least one node is ready. If multiple instructions
377 /// are ready, return NULL.
378 SUnit *ConvergingVLIWScheduler::SchedBoundary::pickOnlyChoice() {
382 for (unsigned i = 0; Available.empty(); ++i) {
383 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
384 "permanent hazard"); (void)i;
385 ResourceModel->reserveResources(0);
389 if (Available.size() == 1)
390 return *Available.begin();
395 void ConvergingVLIWScheduler::traceCandidate(const char *Label,
397 SUnit *SU, PressureElement P) {
398 dbgs() << Label << " " << Q.getName() << " ";
400 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
408 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
409 /// of SU, return it, otherwise return null.
410 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
411 SUnit *OnlyAvailablePred = 0;
412 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
414 SUnit &Pred = *I->getSUnit();
415 if (!Pred.isScheduled) {
416 // We found an available, but not scheduled, predecessor. If it's the
417 // only one we have found, keep track of it... otherwise give up.
418 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
420 OnlyAvailablePred = &Pred;
423 return OnlyAvailablePred;
426 /// getSingleUnscheduledSucc - If there is exactly one unscheduled successor
427 /// of SU, return it, otherwise return null.
428 static SUnit *getSingleUnscheduledSucc(SUnit *SU) {
429 SUnit *OnlyAvailableSucc = 0;
430 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
432 SUnit &Succ = *I->getSUnit();
433 if (!Succ.isScheduled) {
434 // We found an available, but not scheduled, successor. If it's the
435 // only one we have found, keep track of it... otherwise give up.
436 if (OnlyAvailableSucc && OnlyAvailableSucc != &Succ)
438 OnlyAvailableSucc = &Succ;
441 return OnlyAvailableSucc;
444 // Constants used to denote relative importance of
445 // heuristic components for cost computation.
446 static const unsigned PriorityOne = 200;
447 static const unsigned PriorityTwo = 100;
448 static const unsigned PriorityThree = 50;
449 static const unsigned PriorityFour = 20;
450 static const unsigned ScaleTwo = 10;
451 static const unsigned FactorOne = 2;
453 /// Single point to compute overall scheduling cost.
454 /// TODO: More heuristics will be used soon.
455 int ConvergingVLIWScheduler::SchedulingCost(ReadyQueue &Q, SUnit *SU,
456 SchedCandidate &Candidate,
457 RegPressureDelta &Delta,
459 // Initial trivial priority.
462 // Do not waste time on a node that is already scheduled.
463 if (!SU || SU->isScheduled)
466 // Forced priority is high.
467 if (SU->isScheduleHigh)
468 ResCount += PriorityOne;
470 // Critical path first.
471 if (Q.getID() == TopQID) {
472 ResCount += (SU->getHeight() * ScaleTwo);
474 // If resources are available for it, multiply the
475 // chance of scheduling.
476 if (Top.ResourceModel->isResourceAvailable(SU))
477 ResCount <<= FactorOne;
479 ResCount += (SU->getDepth() * ScaleTwo);
481 // If resources are available for it, multiply the
482 // chance of scheduling.
483 if (Bot.ResourceModel->isResourceAvailable(SU))
484 ResCount <<= FactorOne;
487 unsigned NumNodesBlocking = 0;
488 if (Q.getID() == TopQID) {
489 // How many SUs does it block from scheduling?
490 // Look at all of the successors of this node.
491 // Count the number of nodes that
492 // this node is the sole unscheduled node for.
493 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
495 if (getSingleUnscheduledPred(I->getSUnit()) == SU)
498 // How many unscheduled predecessors block this node?
499 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
501 if (getSingleUnscheduledSucc(I->getSUnit()) == SU)
504 ResCount += (NumNodesBlocking * ScaleTwo);
506 // Factor in reg pressure as a heuristic.
507 ResCount -= (Delta.Excess.UnitIncrease*PriorityThree);
508 ResCount -= (Delta.CriticalMax.UnitIncrease*PriorityThree);
510 DEBUG(if (verbose) dbgs() << " Total(" << ResCount << ")");
515 /// Pick the best candidate from the top queue.
517 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
518 /// DAG building. To adjust for the current scheduling location we need to
519 /// maintain the number of vreg uses remaining to be top-scheduled.
520 ConvergingVLIWScheduler::CandResult ConvergingVLIWScheduler::
521 pickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,
522 SchedCandidate &Candidate) {
525 // getMaxPressureDelta temporarily modifies the tracker.
526 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
528 // BestSU remains NULL if no top candidates beat the best existing candidate.
529 CandResult FoundCandidate = NoCand;
530 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
531 RegPressureDelta RPDelta;
532 TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,
533 DAG->getRegionCriticalPSets(),
534 DAG->getRegPressure().MaxSetPressure);
536 int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);
538 // Initialize the candidate if needed.
541 Candidate.RPDelta = RPDelta;
542 Candidate.SCost = CurrentCost;
543 FoundCandidate = NodeOrder;
548 if (CurrentCost > Candidate.SCost) {
549 DEBUG(traceCandidate("CCAND", Q, *I));
551 Candidate.RPDelta = RPDelta;
552 Candidate.SCost = CurrentCost;
553 FoundCandidate = BestCost;
557 // Fall through to original instruction order.
558 // Only consider node order if Candidate was chosen from this Q.
559 if (FoundCandidate == NoCand)
562 return FoundCandidate;
565 /// Pick the best candidate node from either the top or bottom queue.
566 SUnit *ConvergingVLIWScheduler::pickNodeBidrectional(bool &IsTopNode) {
567 // Schedule as far as possible in the direction of no choice. This is most
568 // efficient, but also provides the best heuristics for CriticalPSets.
569 if (SUnit *SU = Bot.pickOnlyChoice()) {
573 if (SUnit *SU = Top.pickOnlyChoice()) {
577 SchedCandidate BotCand;
578 // Prefer bottom scheduling when heuristics are silent.
579 CandResult BotResult = pickNodeFromQueue(Bot.Available,
580 DAG->getBotRPTracker(), BotCand);
581 assert(BotResult != NoCand && "failed to find the first candidate");
583 // If either Q has a single candidate that provides the least increase in
584 // Excess pressure, we can immediately schedule from that Q.
586 // RegionCriticalPSets summarizes the pressure within the scheduled region and
587 // affects picking from either Q. If scheduling in one direction must
588 // increase pressure for one of the excess PSets, then schedule in that
589 // direction first to provide more freedom in the other direction.
590 if (BotResult == SingleExcess || BotResult == SingleCritical) {
594 // Check if the top Q has a better candidate.
595 SchedCandidate TopCand;
596 CandResult TopResult = pickNodeFromQueue(Top.Available,
597 DAG->getTopRPTracker(), TopCand);
598 assert(TopResult != NoCand && "failed to find the first candidate");
600 if (TopResult == SingleExcess || TopResult == SingleCritical) {
604 // If either Q has a single candidate that minimizes pressure above the
605 // original region's pressure pick it.
606 if (BotResult == SingleMax) {
610 if (TopResult == SingleMax) {
614 if (TopCand.SCost > BotCand.SCost) {
618 // Otherwise prefer the bottom candidate in node order.
623 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
624 SUnit *ConvergingVLIWScheduler::pickNode(bool &IsTopNode) {
625 if (DAG->top() == DAG->bottom()) {
626 assert(Top.Available.empty() && Top.Pending.empty() &&
627 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
631 if (llvm::ForceTopDown) {
632 SU = Top.pickOnlyChoice();
634 SchedCandidate TopCand;
635 CandResult TopResult =
636 pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);
637 assert(TopResult != NoCand && "failed to find the first candidate");
642 } else if (llvm::ForceBottomUp) {
643 SU = Bot.pickOnlyChoice();
645 SchedCandidate BotCand;
646 CandResult BotResult =
647 pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);
648 assert(BotResult != NoCand && "failed to find the first candidate");
654 SU = pickNodeBidrectional(IsTopNode);
656 if (SU->isTopReady())
658 if (SU->isBottomReady())
661 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
662 << " Scheduling Instruction in cycle "
663 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
668 /// Update the scheduler's state after scheduling a node. This is the same node
669 /// that was just returned by pickNode(). However, VLIWMachineScheduler needs
670 /// to update it's state based on the current cycle before MachineSchedStrategy
672 void ConvergingVLIWScheduler::schedNode(SUnit *SU, bool IsTopNode) {
674 SU->TopReadyCycle = Top.CurrCycle;
677 SU->BotReadyCycle = Bot.CurrCycle;