Follow-up typo correction from building the wrong branch.
[oota-llvm.git] / lib / CodeGen / MachineScheduler.cpp
1 //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
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 "llvm/CodeGen/MachineScheduler.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/PriorityQueue.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegisterClassInfo.h"
24 #include "llvm/CodeGen/ScheduleDFS.h"
25 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <queue>
31
32 using namespace llvm;
33
34 namespace llvm {
35 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36                            cl::desc("Force top-down list scheduling"));
37 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38                             cl::desc("Force bottom-up list scheduling"));
39 }
40
41 #ifndef NDEBUG
42 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43   cl::desc("Pop up a window to show MISched dags after they are processed"));
44
45 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46   cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
47 #else
48 static bool ViewMISchedDAGs = false;
49 #endif // NDEBUG
50
51 // Experimental heuristics
52 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
53   cl::desc("Enable load clustering."), cl::init(true));
54
55 // Experimental heuristics
56 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
57   cl::desc("Enable scheduling for macro fusion."), cl::init(true));
58
59 //===----------------------------------------------------------------------===//
60 // Machine Instruction Scheduling Pass and Registry
61 //===----------------------------------------------------------------------===//
62
63 MachineSchedContext::MachineSchedContext():
64     MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
65   RegClassInfo = new RegisterClassInfo();
66 }
67
68 MachineSchedContext::~MachineSchedContext() {
69   delete RegClassInfo;
70 }
71
72 namespace {
73 /// MachineScheduler runs after coalescing and before register allocation.
74 class MachineScheduler : public MachineSchedContext,
75                          public MachineFunctionPass {
76 public:
77   MachineScheduler();
78
79   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
80
81   virtual void releaseMemory() {}
82
83   virtual bool runOnMachineFunction(MachineFunction&);
84
85   virtual void print(raw_ostream &O, const Module* = 0) const;
86
87   static char ID; // Class identification, replacement for typeinfo
88 };
89 } // namespace
90
91 char MachineScheduler::ID = 0;
92
93 char &llvm::MachineSchedulerID = MachineScheduler::ID;
94
95 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
96                       "Machine Instruction Scheduler", false, false)
97 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
98 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
99 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
100 INITIALIZE_PASS_END(MachineScheduler, "misched",
101                     "Machine Instruction Scheduler", false, false)
102
103 MachineScheduler::MachineScheduler()
104 : MachineFunctionPass(ID) {
105   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
106 }
107
108 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
109   AU.setPreservesCFG();
110   AU.addRequiredID(MachineDominatorsID);
111   AU.addRequired<MachineLoopInfo>();
112   AU.addRequired<AliasAnalysis>();
113   AU.addRequired<TargetPassConfig>();
114   AU.addRequired<SlotIndexes>();
115   AU.addPreserved<SlotIndexes>();
116   AU.addRequired<LiveIntervals>();
117   AU.addPreserved<LiveIntervals>();
118   MachineFunctionPass::getAnalysisUsage(AU);
119 }
120
121 MachinePassRegistry MachineSchedRegistry::Registry;
122
123 /// A dummy default scheduler factory indicates whether the scheduler
124 /// is overridden on the command line.
125 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
126   return 0;
127 }
128
129 /// MachineSchedOpt allows command line selection of the scheduler.
130 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
131                RegisterPassParser<MachineSchedRegistry> >
132 MachineSchedOpt("misched",
133                 cl::init(&useDefaultMachineSched), cl::Hidden,
134                 cl::desc("Machine instruction scheduler to use"));
135
136 static MachineSchedRegistry
137 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
138                      useDefaultMachineSched);
139
140 /// Forward declare the standard machine scheduler. This will be used as the
141 /// default scheduler if the target does not set a default.
142 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
143
144
145 /// Decrement this iterator until reaching the top or a non-debug instr.
146 static MachineBasicBlock::iterator
147 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
148   assert(I != Beg && "reached the top of the region, cannot decrement");
149   while (--I != Beg) {
150     if (!I->isDebugValue())
151       break;
152   }
153   return I;
154 }
155
156 /// If this iterator is a debug value, increment until reaching the End or a
157 /// non-debug instruction.
158 static MachineBasicBlock::iterator
159 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
160   for(; I != End; ++I) {
161     if (!I->isDebugValue())
162       break;
163   }
164   return I;
165 }
166
167 /// Top-level MachineScheduler pass driver.
168 ///
169 /// Visit blocks in function order. Divide each block into scheduling regions
170 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
171 /// consistent with the DAG builder, which traverses the interior of the
172 /// scheduling regions bottom-up.
173 ///
174 /// This design avoids exposing scheduling boundaries to the DAG builder,
175 /// simplifying the DAG builder's support for "special" target instructions.
176 /// At the same time the design allows target schedulers to operate across
177 /// scheduling boundaries, for example to bundle the boudary instructions
178 /// without reordering them. This creates complexity, because the target
179 /// scheduler must update the RegionBegin and RegionEnd positions cached by
180 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
181 /// design would be to split blocks at scheduling boundaries, but LLVM has a
182 /// general bias against block splitting purely for implementation simplicity.
183 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
184   DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
185
186   // Initialize the context of the pass.
187   MF = &mf;
188   MLI = &getAnalysis<MachineLoopInfo>();
189   MDT = &getAnalysis<MachineDominatorTree>();
190   PassConfig = &getAnalysis<TargetPassConfig>();
191   AA = &getAnalysis<AliasAnalysis>();
192
193   LIS = &getAnalysis<LiveIntervals>();
194   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
195
196   RegClassInfo->runOnMachineFunction(*MF);
197
198   // Select the scheduler, or set the default.
199   MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
200   if (Ctor == useDefaultMachineSched) {
201     // Get the default scheduler set by the target.
202     Ctor = MachineSchedRegistry::getDefault();
203     if (!Ctor) {
204       Ctor = createConvergingSched;
205       MachineSchedRegistry::setDefault(Ctor);
206     }
207   }
208   // Instantiate the selected scheduler.
209   OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
210
211   // Visit all machine basic blocks.
212   //
213   // TODO: Visit blocks in global postorder or postorder within the bottom-up
214   // loop tree. Then we can optionally compute global RegPressure.
215   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
216        MBB != MBBEnd; ++MBB) {
217
218     Scheduler->startBlock(MBB);
219
220     // Break the block into scheduling regions [I, RegionEnd), and schedule each
221     // region as soon as it is discovered. RegionEnd points the scheduling
222     // boundary at the bottom of the region. The DAG does not include RegionEnd,
223     // but the region does (i.e. the next RegionEnd is above the previous
224     // RegionBegin). If the current block has no terminator then RegionEnd ==
225     // MBB->end() for the bottom region.
226     //
227     // The Scheduler may insert instructions during either schedule() or
228     // exitRegion(), even for empty regions. So the local iterators 'I' and
229     // 'RegionEnd' are invalid across these calls.
230     unsigned RemainingInstrs = MBB->size();
231     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
232         RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
233
234       // Avoid decrementing RegionEnd for blocks with no terminator.
235       if (RegionEnd != MBB->end()
236           || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
237         --RegionEnd;
238         // Count the boundary instruction.
239         --RemainingInstrs;
240       }
241
242       // The next region starts above the previous region. Look backward in the
243       // instruction stream until we find the nearest boundary.
244       MachineBasicBlock::iterator I = RegionEnd;
245       for(;I != MBB->begin(); --I, --RemainingInstrs) {
246         if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
247           break;
248       }
249       // Notify the scheduler of the region, even if we may skip scheduling
250       // it. Perhaps it still needs to be bundled.
251       Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
252
253       // Skip empty scheduling regions (0 or 1 schedulable instructions).
254       if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
255         // Close the current region. Bundle the terminator if needed.
256         // This invalidates 'RegionEnd' and 'I'.
257         Scheduler->exitRegion();
258         continue;
259       }
260       DEBUG(dbgs() << "********** MI Scheduling **********\n");
261       DEBUG(dbgs() << MF->getName()
262             << ":BB#" << MBB->getNumber() << "\n  From: " << *I << "    To: ";
263             if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
264             else dbgs() << "End";
265             dbgs() << " Remaining: " << RemainingInstrs << "\n");
266
267       // Schedule a region: possibly reorder instructions.
268       // This invalidates 'RegionEnd' and 'I'.
269       Scheduler->schedule();
270
271       // Close the current region.
272       Scheduler->exitRegion();
273
274       // Scheduling has invalidated the current iterator 'I'. Ask the
275       // scheduler for the top of it's scheduled region.
276       RegionEnd = Scheduler->begin();
277     }
278     assert(RemainingInstrs == 0 && "Instruction count mismatch!");
279     Scheduler->finishBlock();
280   }
281   Scheduler->finalizeSchedule();
282   DEBUG(LIS->print(dbgs()));
283   return true;
284 }
285
286 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
287   // unimplemented
288 }
289
290 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
291 void ReadyQueue::dump() {
292   dbgs() << Name << ": ";
293   for (unsigned i = 0, e = Queue.size(); i < e; ++i)
294     dbgs() << Queue[i]->NodeNum << " ";
295   dbgs() << "\n";
296 }
297 #endif
298
299 //===----------------------------------------------------------------------===//
300 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
301 // preservation.
302 //===----------------------------------------------------------------------===//
303
304 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
305   if (SuccSU != &ExitSU) {
306     // Do not use WillCreateCycle, it assumes SD scheduling.
307     // If Pred is reachable from Succ, then the edge creates a cycle.
308     if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
309       return false;
310     Topo.AddPred(SuccSU, PredDep.getSUnit());
311   }
312   SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
313   // Return true regardless of whether a new edge needed to be inserted.
314   return true;
315 }
316
317 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
318 /// NumPredsLeft reaches zero, release the successor node.
319 ///
320 /// FIXME: Adjust SuccSU height based on MinLatency.
321 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
322   SUnit *SuccSU = SuccEdge->getSUnit();
323
324   if (SuccEdge->isWeak()) {
325     --SuccSU->WeakPredsLeft;
326     if (SuccEdge->isCluster())
327       NextClusterSucc = SuccSU;
328     return;
329   }
330 #ifndef NDEBUG
331   if (SuccSU->NumPredsLeft == 0) {
332     dbgs() << "*** Scheduling failed! ***\n";
333     SuccSU->dump(this);
334     dbgs() << " has been released too many times!\n";
335     llvm_unreachable(0);
336   }
337 #endif
338   --SuccSU->NumPredsLeft;
339   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
340     SchedImpl->releaseTopNode(SuccSU);
341 }
342
343 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
344 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
345   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
346        I != E; ++I) {
347     releaseSucc(SU, &*I);
348   }
349 }
350
351 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
352 /// NumSuccsLeft reaches zero, release the predecessor node.
353 ///
354 /// FIXME: Adjust PredSU height based on MinLatency.
355 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
356   SUnit *PredSU = PredEdge->getSUnit();
357
358   if (PredEdge->isWeak()) {
359     --PredSU->WeakSuccsLeft;
360     if (PredEdge->isCluster())
361       NextClusterPred = PredSU;
362     return;
363   }
364 #ifndef NDEBUG
365   if (PredSU->NumSuccsLeft == 0) {
366     dbgs() << "*** Scheduling failed! ***\n";
367     PredSU->dump(this);
368     dbgs() << " has been released too many times!\n";
369     llvm_unreachable(0);
370   }
371 #endif
372   --PredSU->NumSuccsLeft;
373   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
374     SchedImpl->releaseBottomNode(PredSU);
375 }
376
377 /// releasePredecessors - Call releasePred on each of SU's predecessors.
378 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
379   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
380        I != E; ++I) {
381     releasePred(SU, &*I);
382   }
383 }
384
385 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
386                                     MachineBasicBlock::iterator InsertPos) {
387   // Advance RegionBegin if the first instruction moves down.
388   if (&*RegionBegin == MI)
389     ++RegionBegin;
390
391   // Update the instruction stream.
392   BB->splice(InsertPos, BB, MI);
393
394   // Update LiveIntervals
395   LIS->handleMove(MI, /*UpdateFlags=*/true);
396
397   // Recede RegionBegin if an instruction moves above the first.
398   if (RegionBegin == InsertPos)
399     RegionBegin = MI;
400 }
401
402 bool ScheduleDAGMI::checkSchedLimit() {
403 #ifndef NDEBUG
404   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
405     CurrentTop = CurrentBottom;
406     return false;
407   }
408   ++NumInstrsScheduled;
409 #endif
410   return true;
411 }
412
413 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
414 /// crossing a scheduling boundary. [begin, end) includes all instructions in
415 /// the region, including the boundary itself and single-instruction regions
416 /// that don't get scheduled.
417 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
418                                 MachineBasicBlock::iterator begin,
419                                 MachineBasicBlock::iterator end,
420                                 unsigned endcount)
421 {
422   ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
423
424   // For convenience remember the end of the liveness region.
425   LiveRegionEnd =
426     (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
427 }
428
429 // Setup the register pressure trackers for the top scheduled top and bottom
430 // scheduled regions.
431 void ScheduleDAGMI::initRegPressure() {
432   TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
433   BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
434
435   // Close the RPTracker to finalize live ins.
436   RPTracker.closeRegion();
437
438   DEBUG(RPTracker.getPressure().dump(TRI));
439
440   // Initialize the live ins and live outs.
441   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
442   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
443
444   // Close one end of the tracker so we can call
445   // getMaxUpward/DownwardPressureDelta before advancing across any
446   // instructions. This converts currently live regs into live ins/outs.
447   TopRPTracker.closeTop();
448   BotRPTracker.closeBottom();
449
450   // Account for liveness generated by the region boundary.
451   if (LiveRegionEnd != RegionEnd)
452     BotRPTracker.recede();
453
454   assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
455
456   // Cache the list of excess pressure sets in this region. This will also track
457   // the max pressure in the scheduled code for these sets.
458   RegionCriticalPSets.clear();
459   std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
460   for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
461     unsigned Limit = TRI->getRegPressureSetLimit(i);
462     DEBUG(dbgs() << TRI->getRegPressureSetName(i)
463           << "Limit " << Limit
464           << " Actual " << RegionPressure[i] << "\n");
465     if (RegionPressure[i] > Limit)
466       RegionCriticalPSets.push_back(PressureElement(i, 0));
467   }
468   DEBUG(dbgs() << "Excess PSets: ";
469         for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
470           dbgs() << TRI->getRegPressureSetName(
471             RegionCriticalPSets[i].PSetID) << " ";
472         dbgs() << "\n");
473 }
474
475 // FIXME: When the pressure tracker deals in pressure differences then we won't
476 // iterate over all RegionCriticalPSets[i].
477 void ScheduleDAGMI::
478 updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
479   for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
480     unsigned ID = RegionCriticalPSets[i].PSetID;
481     int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
482     if ((int)NewMaxPressure[ID] > MaxUnits)
483       MaxUnits = NewMaxPressure[ID];
484   }
485 }
486
487 /// schedule - Called back from MachineScheduler::runOnMachineFunction
488 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
489 /// only includes instructions that have DAG nodes, not scheduling boundaries.
490 ///
491 /// This is a skeletal driver, with all the functionality pushed into helpers,
492 /// so that it can be easilly extended by experimental schedulers. Generally,
493 /// implementing MachineSchedStrategy should be sufficient to implement a new
494 /// scheduling algorithm. However, if a scheduler further subclasses
495 /// ScheduleDAGMI then it will want to override this virtual method in order to
496 /// update any specialized state.
497 void ScheduleDAGMI::schedule() {
498   buildDAGWithRegPressure();
499
500   Topo.InitDAGTopologicalSorting();
501
502   postprocessDAG();
503
504   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
505           SUnits[su].dumpAll(this));
506
507   if (ViewMISchedDAGs) viewGraph();
508
509   initQueues();
510
511   bool IsTopNode = false;
512   while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
513     assert(!SU->isScheduled && "Node already scheduled");
514     if (!checkSchedLimit())
515       break;
516
517     scheduleMI(SU, IsTopNode);
518
519     updateQueues(SU, IsTopNode);
520   }
521   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
522
523   placeDebugValues();
524
525   DEBUG({
526       unsigned BBNum = begin()->getParent()->getNumber();
527       dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
528       dumpSchedule();
529       dbgs() << '\n';
530     });
531 }
532
533 /// Build the DAG and setup three register pressure trackers.
534 void ScheduleDAGMI::buildDAGWithRegPressure() {
535   // Initialize the register pressure tracker used by buildSchedGraph.
536   RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
537
538   // Account for liveness generate by the region boundary.
539   if (LiveRegionEnd != RegionEnd)
540     RPTracker.recede();
541
542   // Build the DAG, and compute current register pressure.
543   buildSchedGraph(AA, &RPTracker);
544   if (ViewMISchedDAGs) viewGraph();
545
546   // Initialize top/bottom trackers after computing region pressure.
547   initRegPressure();
548 }
549
550 /// Apply each ScheduleDAGMutation step in order.
551 void ScheduleDAGMI::postprocessDAG() {
552   for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
553     Mutations[i]->apply(this);
554   }
555 }
556
557 // Release all DAG roots for scheduling.
558 //
559 // Nodes with unreleased weak edges can still be roots.
560 void ScheduleDAGMI::releaseRoots() {
561   SmallVector<SUnit*, 16> BotRoots;
562
563   for (std::vector<SUnit>::iterator
564          I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
565     SUnit *SU = &(*I);
566     // A SUnit is ready to top schedule if it has no predecessors.
567     if (!I->NumPredsLeft && SU != &EntrySU)
568       SchedImpl->releaseTopNode(SU);
569     // A SUnit is ready to bottom schedule if it has no successors.
570     if (!I->NumSuccsLeft && SU != &ExitSU)
571       BotRoots.push_back(SU);
572   }
573   // Release bottom roots in reverse order so the higher priority nodes appear
574   // first. This is more natural and slightly more efficient.
575   for (SmallVectorImpl<SUnit*>::const_reverse_iterator
576          I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
577     SchedImpl->releaseBottomNode(*I);
578 }
579
580 /// Identify DAG roots and setup scheduler queues.
581 void ScheduleDAGMI::initQueues() {
582   NextClusterSucc = NULL;
583   NextClusterPred = NULL;
584
585   // Initialize the strategy before modifying the DAG.
586   SchedImpl->initialize(this);
587
588   // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
589   releaseRoots();
590
591   releaseSuccessors(&EntrySU);
592   releasePredecessors(&ExitSU);
593
594   SchedImpl->registerRoots();
595
596   // Advance past initial DebugValues.
597   assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
598   CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
599   TopRPTracker.setPos(CurrentTop);
600
601   CurrentBottom = RegionEnd;
602 }
603
604 /// Move an instruction and update register pressure.
605 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
606   // Move the instruction to its new location in the instruction stream.
607   MachineInstr *MI = SU->getInstr();
608
609   if (IsTopNode) {
610     assert(SU->isTopReady() && "node still has unscheduled dependencies");
611     if (&*CurrentTop == MI)
612       CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
613     else {
614       moveInstruction(MI, CurrentTop);
615       TopRPTracker.setPos(MI);
616     }
617
618     // Update top scheduled pressure.
619     TopRPTracker.advance();
620     assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
621     updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
622   }
623   else {
624     assert(SU->isBottomReady() && "node still has unscheduled dependencies");
625     MachineBasicBlock::iterator priorII =
626       priorNonDebug(CurrentBottom, CurrentTop);
627     if (&*priorII == MI)
628       CurrentBottom = priorII;
629     else {
630       if (&*CurrentTop == MI) {
631         CurrentTop = nextIfDebug(++CurrentTop, priorII);
632         TopRPTracker.setPos(CurrentTop);
633       }
634       moveInstruction(MI, CurrentBottom);
635       CurrentBottom = MI;
636     }
637     // Update bottom scheduled pressure.
638     BotRPTracker.recede();
639     assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
640     updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
641   }
642 }
643
644 /// Update scheduler queues after scheduling an instruction.
645 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
646   // Release dependent instructions for scheduling.
647   if (IsTopNode)
648     releaseSuccessors(SU);
649   else
650     releasePredecessors(SU);
651
652   SU->isScheduled = true;
653
654   // Notify the scheduling strategy after updating the DAG.
655   SchedImpl->schedNode(SU, IsTopNode);
656 }
657
658 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
659 void ScheduleDAGMI::placeDebugValues() {
660   // If first instruction was a DBG_VALUE then put it back.
661   if (FirstDbgValue) {
662     BB->splice(RegionBegin, BB, FirstDbgValue);
663     RegionBegin = FirstDbgValue;
664   }
665
666   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
667          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
668     std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
669     MachineInstr *DbgValue = P.first;
670     MachineBasicBlock::iterator OrigPrevMI = P.second;
671     if (&*RegionBegin == DbgValue)
672       ++RegionBegin;
673     BB->splice(++OrigPrevMI, BB, DbgValue);
674     if (OrigPrevMI == llvm::prior(RegionEnd))
675       RegionEnd = DbgValue;
676   }
677   DbgValues.clear();
678   FirstDbgValue = NULL;
679 }
680
681 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
682 void ScheduleDAGMI::dumpSchedule() const {
683   for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
684     if (SUnit *SU = getSUnit(&(*MI)))
685       SU->dump(this);
686     else
687       dbgs() << "Missing SUnit\n";
688   }
689 }
690 #endif
691
692 //===----------------------------------------------------------------------===//
693 // LoadClusterMutation - DAG post-processing to cluster loads.
694 //===----------------------------------------------------------------------===//
695
696 namespace {
697 /// \brief Post-process the DAG to create cluster edges between neighboring
698 /// loads.
699 class LoadClusterMutation : public ScheduleDAGMutation {
700   struct LoadInfo {
701     SUnit *SU;
702     unsigned BaseReg;
703     unsigned Offset;
704     LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
705       : SU(su), BaseReg(reg), Offset(ofs) {}
706   };
707   static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
708                            const LoadClusterMutation::LoadInfo &RHS);
709
710   const TargetInstrInfo *TII;
711   const TargetRegisterInfo *TRI;
712 public:
713   LoadClusterMutation(const TargetInstrInfo *tii,
714                       const TargetRegisterInfo *tri)
715     : TII(tii), TRI(tri) {}
716
717   virtual void apply(ScheduleDAGMI *DAG);
718 protected:
719   void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
720 };
721 } // anonymous
722
723 bool LoadClusterMutation::LoadInfoLess(
724   const LoadClusterMutation::LoadInfo &LHS,
725   const LoadClusterMutation::LoadInfo &RHS) {
726   if (LHS.BaseReg != RHS.BaseReg)
727     return LHS.BaseReg < RHS.BaseReg;
728   return LHS.Offset < RHS.Offset;
729 }
730
731 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
732                                                   ScheduleDAGMI *DAG) {
733   SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
734   for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
735     SUnit *SU = Loads[Idx];
736     unsigned BaseReg;
737     unsigned Offset;
738     if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
739       LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
740   }
741   if (LoadRecords.size() < 2)
742     return;
743   std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
744   unsigned ClusterLength = 1;
745   for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
746     if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
747       ClusterLength = 1;
748       continue;
749     }
750
751     SUnit *SUa = LoadRecords[Idx].SU;
752     SUnit *SUb = LoadRecords[Idx+1].SU;
753     if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
754         && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
755
756       DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
757             << SUb->NodeNum << ")\n");
758       // Copy successor edges from SUa to SUb. Interleaving computation
759       // dependent on SUa can prevent load combining due to register reuse.
760       // Predecessor edges do not need to be copied from SUb to SUa since nearby
761       // loads should have effectively the same inputs.
762       for (SUnit::const_succ_iterator
763              SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
764         if (SI->getSUnit() == SUb)
765           continue;
766         DEBUG(dbgs() << "  Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
767         DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
768       }
769       ++ClusterLength;
770     }
771     else
772       ClusterLength = 1;
773   }
774 }
775
776 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
777 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
778   // Map DAG NodeNum to store chain ID.
779   DenseMap<unsigned, unsigned> StoreChainIDs;
780   // Map each store chain to a set of dependent loads.
781   SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
782   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
783     SUnit *SU = &DAG->SUnits[Idx];
784     if (!SU->getInstr()->mayLoad())
785       continue;
786     unsigned ChainPredID = DAG->SUnits.size();
787     for (SUnit::const_pred_iterator
788            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
789       if (PI->isCtrl()) {
790         ChainPredID = PI->getSUnit()->NodeNum;
791         break;
792       }
793     }
794     // Check if this chain-like pred has been seen
795     // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
796     unsigned NumChains = StoreChainDependents.size();
797     std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
798       StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
799     if (Result.second)
800       StoreChainDependents.resize(NumChains + 1);
801     StoreChainDependents[Result.first->second].push_back(SU);
802   }
803   // Iterate over the store chains.
804   for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
805     clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
806 }
807
808 //===----------------------------------------------------------------------===//
809 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
810 //===----------------------------------------------------------------------===//
811
812 namespace {
813 /// \brief Post-process the DAG to create cluster edges between instructions
814 /// that may be fused by the processor into a single operation.
815 class MacroFusion : public ScheduleDAGMutation {
816   const TargetInstrInfo *TII;
817 public:
818   MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
819
820   virtual void apply(ScheduleDAGMI *DAG);
821 };
822 } // anonymous
823
824 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
825 /// fused operations.
826 void MacroFusion::apply(ScheduleDAGMI *DAG) {
827   // For now, assume targets can only fuse with the branch.
828   MachineInstr *Branch = DAG->ExitSU.getInstr();
829   if (!Branch)
830     return;
831
832   for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
833     SUnit *SU = &DAG->SUnits[--Idx];
834     if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
835       continue;
836
837     // Create a single weak edge from SU to ExitSU. The only effect is to cause
838     // bottom-up scheduling to heavily prioritize the clustered SU.  There is no
839     // need to copy predecessor edges from ExitSU to SU, since top-down
840     // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
841     // of SU, we could create an artificial edge from the deepest root, but it
842     // hasn't been needed yet.
843     bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
844     (void)Success;
845     assert(Success && "No DAG nodes should be reachable from ExitSU");
846
847     DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
848     break;
849   }
850 }
851
852 //===----------------------------------------------------------------------===//
853 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
854 //===----------------------------------------------------------------------===//
855
856 namespace {
857 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
858 /// the schedule.
859 class ConvergingScheduler : public MachineSchedStrategy {
860 public:
861   /// Represent the type of SchedCandidate found within a single queue.
862   /// pickNodeBidirectional depends on these listed by decreasing priority.
863   enum CandReason {
864     NoCand, SingleExcess, SingleCritical, Cluster,
865     ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
866     TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
867     NodeOrder};
868
869 #ifndef NDEBUG
870   static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
871 #endif
872
873   /// Policy for scheduling the next instruction in the candidate's zone.
874   struct CandPolicy {
875     bool ReduceLatency;
876     unsigned ReduceResIdx;
877     unsigned DemandResIdx;
878
879     CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
880   };
881
882   /// Status of an instruction's critical resource consumption.
883   struct SchedResourceDelta {
884     // Count critical resources in the scheduled region required by SU.
885     unsigned CritResources;
886
887     // Count critical resources from another region consumed by SU.
888     unsigned DemandedResources;
889
890     SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
891
892     bool operator==(const SchedResourceDelta &RHS) const {
893       return CritResources == RHS.CritResources
894         && DemandedResources == RHS.DemandedResources;
895     }
896     bool operator!=(const SchedResourceDelta &RHS) const {
897       return !operator==(RHS);
898     }
899   };
900
901   /// Store the state used by ConvergingScheduler heuristics, required for the
902   /// lifetime of one invocation of pickNode().
903   struct SchedCandidate {
904     CandPolicy Policy;
905
906     // The best SUnit candidate.
907     SUnit *SU;
908
909     // The reason for this candidate.
910     CandReason Reason;
911
912     // Register pressure values for the best candidate.
913     RegPressureDelta RPDelta;
914
915     // Critical resource consumption of the best candidate.
916     SchedResourceDelta ResDelta;
917
918     SchedCandidate(const CandPolicy &policy)
919     : Policy(policy), SU(NULL), Reason(NoCand) {}
920
921     bool isValid() const { return SU; }
922
923     // Copy the status of another candidate without changing policy.
924     void setBest(SchedCandidate &Best) {
925       assert(Best.Reason != NoCand && "uninitialized Sched candidate");
926       SU = Best.SU;
927       Reason = Best.Reason;
928       RPDelta = Best.RPDelta;
929       ResDelta = Best.ResDelta;
930     }
931
932     void initResourceDelta(const ScheduleDAGMI *DAG,
933                            const TargetSchedModel *SchedModel);
934   };
935
936   /// Summarize the unscheduled region.
937   struct SchedRemainder {
938     // Critical path through the DAG in expected latency.
939     unsigned CriticalPath;
940
941     // Unscheduled resources
942     SmallVector<unsigned, 16> RemainingCounts;
943     // Critical resource for the unscheduled zone.
944     unsigned CritResIdx;
945     // Number of micro-ops left to schedule.
946     unsigned RemainingMicroOps;
947
948     void reset() {
949       CriticalPath = 0;
950       RemainingCounts.clear();
951       CritResIdx = 0;
952       RemainingMicroOps = 0;
953     }
954
955     SchedRemainder() { reset(); }
956
957     void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
958
959     unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
960       if (!SchedModel->hasInstrSchedModel())
961         return 0;
962
963       return std::max(
964         RemainingMicroOps * SchedModel->getMicroOpFactor(),
965         RemainingCounts[CritResIdx]);
966     }
967   };
968
969   /// Each Scheduling boundary is associated with ready queues. It tracks the
970   /// current cycle in the direction of movement, and maintains the state
971   /// of "hazards" and other interlocks at the current cycle.
972   struct SchedBoundary {
973     ScheduleDAGMI *DAG;
974     const TargetSchedModel *SchedModel;
975     SchedRemainder *Rem;
976
977     ReadyQueue Available;
978     ReadyQueue Pending;
979     bool CheckPending;
980
981     // For heuristics, keep a list of the nodes that immediately depend on the
982     // most recently scheduled node.
983     SmallPtrSet<const SUnit*, 8> NextSUs;
984
985     ScheduleHazardRecognizer *HazardRec;
986
987     unsigned CurrCycle;
988     unsigned IssueCount;
989
990     /// MinReadyCycle - Cycle of the soonest available instruction.
991     unsigned MinReadyCycle;
992
993     // The expected latency of the critical path in this scheduled zone.
994     unsigned ExpectedLatency;
995
996     // Resources used in the scheduled zone beyond this boundary.
997     SmallVector<unsigned, 16> ResourceCounts;
998
999     // Cache the critical resources ID in this scheduled zone.
1000     unsigned CritResIdx;
1001
1002     // Is the scheduled region resource limited vs. latency limited.
1003     bool IsResourceLimited;
1004
1005     unsigned ExpectedCount;
1006
1007 #ifndef NDEBUG
1008     // Remember the greatest min operand latency.
1009     unsigned MaxMinLatency;
1010 #endif
1011
1012     void reset() {
1013       Available.clear();
1014       Pending.clear();
1015       CheckPending = false;
1016       NextSUs.clear();
1017       HazardRec = 0;
1018       CurrCycle = 0;
1019       IssueCount = 0;
1020       MinReadyCycle = UINT_MAX;
1021       ExpectedLatency = 0;
1022       ResourceCounts.resize(1);
1023       assert(!ResourceCounts[0] && "nonzero count for bad resource");
1024       CritResIdx = 0;
1025       IsResourceLimited = false;
1026       ExpectedCount = 0;
1027 #ifndef NDEBUG
1028       MaxMinLatency = 0;
1029 #endif
1030       // Reserve a zero-count for invalid CritResIdx.
1031       ResourceCounts.resize(1);
1032     }
1033
1034     /// Pending queues extend the ready queues with the same ID and the
1035     /// PendingFlag set.
1036     SchedBoundary(unsigned ID, const Twine &Name):
1037       DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1038       Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
1039       reset();
1040     }
1041
1042     ~SchedBoundary() { delete HazardRec; }
1043
1044     void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1045               SchedRemainder *rem);
1046
1047     bool isTop() const {
1048       return Available.getID() == ConvergingScheduler::TopQID;
1049     }
1050
1051     unsigned getUnscheduledLatency(SUnit *SU) const {
1052       if (isTop())
1053         return SU->getHeight();
1054       return SU->getDepth() + SU->Latency;
1055     }
1056
1057     unsigned getCriticalCount() const {
1058       return ResourceCounts[CritResIdx];
1059     }
1060
1061     bool checkHazard(SUnit *SU);
1062
1063     void setLatencyPolicy(CandPolicy &Policy);
1064
1065     void releaseNode(SUnit *SU, unsigned ReadyCycle);
1066
1067     void bumpCycle();
1068
1069     void countResource(unsigned PIdx, unsigned Cycles);
1070
1071     void bumpNode(SUnit *SU);
1072
1073     void releasePending();
1074
1075     void removeReady(SUnit *SU);
1076
1077     SUnit *pickOnlyChoice();
1078   };
1079
1080 private:
1081   ScheduleDAGMI *DAG;
1082   const TargetSchedModel *SchedModel;
1083   const TargetRegisterInfo *TRI;
1084
1085   // State of the top and bottom scheduled instruction boundaries.
1086   SchedRemainder Rem;
1087   SchedBoundary Top;
1088   SchedBoundary Bot;
1089
1090 public:
1091   /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
1092   enum {
1093     TopQID = 1,
1094     BotQID = 2,
1095     LogMaxQID = 2
1096   };
1097
1098   ConvergingScheduler():
1099     DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
1100
1101   virtual void initialize(ScheduleDAGMI *dag);
1102
1103   virtual SUnit *pickNode(bool &IsTopNode);
1104
1105   virtual void schedNode(SUnit *SU, bool IsTopNode);
1106
1107   virtual void releaseTopNode(SUnit *SU);
1108
1109   virtual void releaseBottomNode(SUnit *SU);
1110
1111   virtual void registerRoots();
1112
1113 protected:
1114   void balanceZones(
1115     ConvergingScheduler::SchedBoundary &CriticalZone,
1116     ConvergingScheduler::SchedCandidate &CriticalCand,
1117     ConvergingScheduler::SchedBoundary &OppositeZone,
1118     ConvergingScheduler::SchedCandidate &OppositeCand);
1119
1120   void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1121                            ConvergingScheduler::SchedCandidate &BotCand);
1122
1123   void tryCandidate(SchedCandidate &Cand,
1124                     SchedCandidate &TryCand,
1125                     SchedBoundary &Zone,
1126                     const RegPressureTracker &RPTracker,
1127                     RegPressureTracker &TempTracker);
1128
1129   SUnit *pickNodeBidirectional(bool &IsTopNode);
1130
1131   void pickNodeFromQueue(SchedBoundary &Zone,
1132                          const RegPressureTracker &RPTracker,
1133                          SchedCandidate &Candidate);
1134
1135 #ifndef NDEBUG
1136   void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
1137 #endif
1138 };
1139 } // namespace
1140
1141 void ConvergingScheduler::SchedRemainder::
1142 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1143   reset();
1144   if (!SchedModel->hasInstrSchedModel())
1145     return;
1146   RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1147   for (std::vector<SUnit>::iterator
1148          I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1149     const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1150     RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1151     for (TargetSchedModel::ProcResIter
1152            PI = SchedModel->getWriteProcResBegin(SC),
1153            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1154       unsigned PIdx = PI->ProcResourceIdx;
1155       unsigned Factor = SchedModel->getResourceFactor(PIdx);
1156       RemainingCounts[PIdx] += (Factor * PI->Cycles);
1157     }
1158   }
1159   for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1160        PIdx != PEnd; ++PIdx) {
1161     if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1162         >= (int)SchedModel->getLatencyFactor()) {
1163       CritResIdx = PIdx;
1164     }
1165   }
1166 }
1167
1168 void ConvergingScheduler::SchedBoundary::
1169 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1170   reset();
1171   DAG = dag;
1172   SchedModel = smodel;
1173   Rem = rem;
1174   if (SchedModel->hasInstrSchedModel())
1175     ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1176 }
1177
1178 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1179   DAG = dag;
1180   SchedModel = DAG->getSchedModel();
1181   TRI = DAG->TRI;
1182   Rem.init(DAG, SchedModel);
1183   Top.init(DAG, SchedModel, &Rem);
1184   Bot.init(DAG, SchedModel, &Rem);
1185
1186   // Initialize resource counts.
1187
1188   // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1189   // are disabled, then these HazardRecs will be disabled.
1190   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
1191   const TargetMachine &TM = DAG->MF.getTarget();
1192   Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1193   Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1194
1195   assert((!ForceTopDown || !ForceBottomUp) &&
1196          "-misched-topdown incompatible with -misched-bottomup");
1197 }
1198
1199 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
1200   if (SU->isScheduled)
1201     return;
1202
1203   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1204        I != E; ++I) {
1205     unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1206     unsigned MinLatency = I->getMinLatency();
1207 #ifndef NDEBUG
1208     Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
1209 #endif
1210     if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1211       SU->TopReadyCycle = PredReadyCycle + MinLatency;
1212   }
1213   Top.releaseNode(SU, SU->TopReadyCycle);
1214 }
1215
1216 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
1217   if (SU->isScheduled)
1218     return;
1219
1220   assert(SU->getInstr() && "Scheduled SUnit must have instr");
1221
1222   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1223        I != E; ++I) {
1224     if (I->isWeak())
1225       continue;
1226     unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1227     unsigned MinLatency = I->getMinLatency();
1228 #ifndef NDEBUG
1229     Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
1230 #endif
1231     if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1232       SU->BotReadyCycle = SuccReadyCycle + MinLatency;
1233   }
1234   Bot.releaseNode(SU, SU->BotReadyCycle);
1235 }
1236
1237 void ConvergingScheduler::registerRoots() {
1238   Rem.CriticalPath = DAG->ExitSU.getDepth();
1239   // Some roots may not feed into ExitSU. Check all of them in case.
1240   for (std::vector<SUnit*>::const_iterator
1241          I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1242     if ((*I)->getDepth() > Rem.CriticalPath)
1243       Rem.CriticalPath = (*I)->getDepth();
1244   }
1245   DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1246 }
1247
1248 /// Does this SU have a hazard within the current instruction group.
1249 ///
1250 /// The scheduler supports two modes of hazard recognition. The first is the
1251 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1252 /// supports highly complicated in-order reservation tables
1253 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1254 ///
1255 /// The second is a streamlined mechanism that checks for hazards based on
1256 /// simple counters that the scheduler itself maintains. It explicitly checks
1257 /// for instruction dispatch limitations, including the number of micro-ops that
1258 /// can dispatch per cycle.
1259 ///
1260 /// TODO: Also check whether the SU must start a new group.
1261 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1262   if (HazardRec->isEnabled())
1263     return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1264
1265   unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1266   if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1267     DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") uops="
1268           << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1269     return true;
1270   }
1271   return false;
1272 }
1273
1274 /// Compute the remaining latency to determine whether ILP should be increased.
1275 void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1276   // FIXME: compile time. In all, we visit four queues here one we should only
1277   // need to visit the one that was last popped if we cache the result.
1278   unsigned RemLatency = 0;
1279   for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1280        I != E; ++I) {
1281     unsigned L = getUnscheduledLatency(*I);
1282     if (L > RemLatency)
1283       RemLatency = L;
1284   }
1285   for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1286        I != E; ++I) {
1287     unsigned L = getUnscheduledLatency(*I);
1288     if (L > RemLatency)
1289       RemLatency = L;
1290   }
1291   unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1292   if (RemLatency + ExpectedLatency >= CriticalPathLimit
1293       && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1294     Policy.ReduceLatency = true;
1295     DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
1296   }
1297 }
1298
1299 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1300                                                      unsigned ReadyCycle) {
1301
1302   if (ReadyCycle < MinReadyCycle)
1303     MinReadyCycle = ReadyCycle;
1304
1305   // Check for interlocks first. For the purpose of other heuristics, an
1306   // instruction that cannot issue appears as if it's not in the ReadyQueue.
1307   if (ReadyCycle > CurrCycle || checkHazard(SU))
1308     Pending.push(SU);
1309   else
1310     Available.push(SU);
1311
1312   // Record this node as an immediate dependent of the scheduled node.
1313   NextSUs.insert(SU);
1314 }
1315
1316 /// Move the boundary of scheduled code by one cycle.
1317 void ConvergingScheduler::SchedBoundary::bumpCycle() {
1318   unsigned Width = SchedModel->getIssueWidth();
1319   IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
1320
1321   unsigned NextCycle = CurrCycle + 1;
1322   assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1323   if (MinReadyCycle > NextCycle) {
1324     IssueCount = 0;
1325     NextCycle = MinReadyCycle;
1326   }
1327
1328   if (!HazardRec->isEnabled()) {
1329     // Bypass HazardRec virtual calls.
1330     CurrCycle = NextCycle;
1331   }
1332   else {
1333     // Bypass getHazardType calls in case of long latency.
1334     for (; CurrCycle != NextCycle; ++CurrCycle) {
1335       if (isTop())
1336         HazardRec->AdvanceCycle();
1337       else
1338         HazardRec->RecedeCycle();
1339     }
1340   }
1341   CheckPending = true;
1342   IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1343
1344   DEBUG(dbgs() << "  *** " << Available.getName() << " cycle "
1345         << CurrCycle << '\n');
1346 }
1347
1348 /// Add the given processor resource to this scheduled zone.
1349 void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1350                                                        unsigned Cycles) {
1351   unsigned Factor = SchedModel->getResourceFactor(PIdx);
1352   DEBUG(dbgs() << "  " << SchedModel->getProcResource(PIdx)->Name
1353         << " +(" << Cycles << "x" << Factor
1354         << ") / " << SchedModel->getLatencyFactor() << '\n');
1355
1356   unsigned Count = Factor * Cycles;
1357   ResourceCounts[PIdx] += Count;
1358   assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1359   Rem->RemainingCounts[PIdx] -= Count;
1360
1361   // Check if this resource exceeds the current critical resource by a full
1362   // cycle. If so, it becomes the critical resource.
1363   if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1364       >= (int)SchedModel->getLatencyFactor()) {
1365     CritResIdx = PIdx;
1366     DEBUG(dbgs() << "  *** Critical resource "
1367           << SchedModel->getProcResource(PIdx)->Name << " x"
1368           << ResourceCounts[PIdx] << '\n');
1369   }
1370 }
1371
1372 /// Move the boundary of scheduled code by one SUnit.
1373 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
1374   // Update the reservation table.
1375   if (HazardRec->isEnabled()) {
1376     if (!isTop() && SU->isCall) {
1377       // Calls are scheduled with their preceding instructions. For bottom-up
1378       // scheduling, clear the pipeline state before emitting.
1379       HazardRec->Reset();
1380     }
1381     HazardRec->EmitInstruction(SU);
1382   }
1383   // Update resource counts and critical resource.
1384   if (SchedModel->hasInstrSchedModel()) {
1385     const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1386     Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1387     for (TargetSchedModel::ProcResIter
1388            PI = SchedModel->getWriteProcResBegin(SC),
1389            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1390       countResource(PI->ProcResourceIdx, PI->Cycles);
1391     }
1392   }
1393   if (isTop()) {
1394     if (SU->getDepth() > ExpectedLatency)
1395       ExpectedLatency = SU->getDepth();
1396   }
1397   else {
1398     if (SU->getHeight() > ExpectedLatency)
1399       ExpectedLatency = SU->getHeight();
1400   }
1401
1402   IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1403
1404   // Check the instruction group dispatch limit.
1405   // TODO: Check if this SU must end a dispatch group.
1406   IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
1407
1408   // checkHazard prevents scheduling multiple instructions per cycle that exceed
1409   // issue width. However, we commonly reach the maximum. In this case
1410   // opportunistically bump the cycle to avoid uselessly checking everything in
1411   // the readyQ. Furthermore, a single instruction may produce more than one
1412   // cycle's worth of micro-ops.
1413   if (IssueCount >= SchedModel->getIssueWidth()) {
1414     DEBUG(dbgs() << "  *** Max instrs at cycle " << CurrCycle << '\n');
1415     bumpCycle();
1416   }
1417 }
1418
1419 /// Release pending ready nodes in to the available queue. This makes them
1420 /// visible to heuristics.
1421 void ConvergingScheduler::SchedBoundary::releasePending() {
1422   // If the available queue is empty, it is safe to reset MinReadyCycle.
1423   if (Available.empty())
1424     MinReadyCycle = UINT_MAX;
1425
1426   // Check to see if any of the pending instructions are ready to issue.  If
1427   // so, add them to the available queue.
1428   for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1429     SUnit *SU = *(Pending.begin()+i);
1430     unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1431
1432     if (ReadyCycle < MinReadyCycle)
1433       MinReadyCycle = ReadyCycle;
1434
1435     if (ReadyCycle > CurrCycle)
1436       continue;
1437
1438     if (checkHazard(SU))
1439       continue;
1440
1441     Available.push(SU);
1442     Pending.remove(Pending.begin()+i);
1443     --i; --e;
1444   }
1445   DEBUG(if (!Pending.empty()) Pending.dump());
1446   CheckPending = false;
1447 }
1448
1449 /// Remove SU from the ready set for this boundary.
1450 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1451   if (Available.isInQueue(SU))
1452     Available.remove(Available.find(SU));
1453   else {
1454     assert(Pending.isInQueue(SU) && "bad ready count");
1455     Pending.remove(Pending.find(SU));
1456   }
1457 }
1458
1459 /// If this queue only has one ready candidate, return it. As a side effect,
1460 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1461 /// one node is ready. If multiple instructions are ready, return NULL.
1462 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1463   if (CheckPending)
1464     releasePending();
1465
1466   if (IssueCount > 0) {
1467     // Defer any ready instrs that now have a hazard.
1468     for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1469       if (checkHazard(*I)) {
1470         Pending.push(*I);
1471         I = Available.remove(I);
1472         continue;
1473       }
1474       ++I;
1475     }
1476   }
1477   for (unsigned i = 0; Available.empty(); ++i) {
1478     assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1479            "permanent hazard"); (void)i;
1480     bumpCycle();
1481     releasePending();
1482   }
1483   if (Available.size() == 1)
1484     return *Available.begin();
1485   return NULL;
1486 }
1487
1488 /// Record the candidate policy for opposite zones with different critical
1489 /// resources.
1490 ///
1491 /// If the CriticalZone is latency limited, don't force a policy for the
1492 /// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
1493 void ConvergingScheduler::balanceZones(
1494   ConvergingScheduler::SchedBoundary &CriticalZone,
1495   ConvergingScheduler::SchedCandidate &CriticalCand,
1496   ConvergingScheduler::SchedBoundary &OppositeZone,
1497   ConvergingScheduler::SchedCandidate &OppositeCand) {
1498
1499   if (!CriticalZone.IsResourceLimited)
1500     return;
1501   assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
1502
1503   SchedRemainder *Rem = CriticalZone.Rem;
1504
1505   // If the critical zone is overconsuming a resource relative to the
1506   // remainder, try to reduce it.
1507   unsigned RemainingCritCount =
1508     Rem->RemainingCounts[CriticalZone.CritResIdx];
1509   if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
1510       > (int)SchedModel->getLatencyFactor()) {
1511     CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1512     DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1513           << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1514           << '\n');
1515   }
1516   // If the other zone is underconsuming a resource relative to the full zone,
1517   // try to increase it.
1518   unsigned OppositeCount =
1519     OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1520   if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1521       > (int)SchedModel->getLatencyFactor()) {
1522     OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1523     DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1524           << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1525           << '\n');
1526   }
1527 }
1528
1529 /// Determine if the scheduled zones exceed resource limits or critical path and
1530 /// set each candidate's ReduceHeight policy accordingly.
1531 void ConvergingScheduler::checkResourceLimits(
1532   ConvergingScheduler::SchedCandidate &TopCand,
1533   ConvergingScheduler::SchedCandidate &BotCand) {
1534
1535   // Set ReduceLatency to true if needed.
1536   Bot.setLatencyPolicy(BotCand.Policy);
1537   Top.setLatencyPolicy(TopCand.Policy);
1538
1539   // Handle resource-limited regions.
1540   if (Top.IsResourceLimited && Bot.IsResourceLimited
1541       && Top.CritResIdx == Bot.CritResIdx) {
1542     // If the scheduled critical resource in both zones is no longer the
1543     // critical remaining resource, attempt to reduce resource height both ways.
1544     if (Top.CritResIdx != Rem.CritResIdx) {
1545       TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1546       BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1547       DEBUG(dbgs() << "Reduce scheduled "
1548             << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1549     }
1550     return;
1551   }
1552   // Handle latency-limited regions.
1553   if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1554     // If the total scheduled expected latency exceeds the region's critical
1555     // path then reduce latency both ways.
1556     //
1557     // Just because a zone is not resource limited does not mean it is latency
1558     // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1559     // to exceed expected latency.
1560     if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1561         && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1562       TopCand.Policy.ReduceLatency = true;
1563       BotCand.Policy.ReduceLatency = true;
1564       DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1565             << " + " << Bot.ExpectedLatency << '\n');
1566     }
1567     return;
1568   }
1569   // The critical resource is different in each zone, so request balancing.
1570
1571   // Compute the cost of each zone.
1572   Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1573   Top.ExpectedCount = std::max(
1574     Top.getCriticalCount(),
1575     Top.ExpectedCount * SchedModel->getLatencyFactor());
1576   Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1577   Bot.ExpectedCount = std::max(
1578     Bot.getCriticalCount(),
1579     Bot.ExpectedCount * SchedModel->getLatencyFactor());
1580
1581   balanceZones(Top, TopCand, Bot, BotCand);
1582   balanceZones(Bot, BotCand, Top, TopCand);
1583 }
1584
1585 void ConvergingScheduler::SchedCandidate::
1586 initResourceDelta(const ScheduleDAGMI *DAG,
1587                   const TargetSchedModel *SchedModel) {
1588   if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1589     return;
1590
1591   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1592   for (TargetSchedModel::ProcResIter
1593          PI = SchedModel->getWriteProcResBegin(SC),
1594          PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1595     if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1596       ResDelta.CritResources += PI->Cycles;
1597     if (PI->ProcResourceIdx == Policy.DemandResIdx)
1598       ResDelta.DemandedResources += PI->Cycles;
1599   }
1600 }
1601
1602 /// Return true if this heuristic determines order.
1603 static bool tryLess(unsigned TryVal, unsigned CandVal,
1604                     ConvergingScheduler::SchedCandidate &TryCand,
1605                     ConvergingScheduler::SchedCandidate &Cand,
1606                     ConvergingScheduler::CandReason Reason) {
1607   if (TryVal < CandVal) {
1608     TryCand.Reason = Reason;
1609     return true;
1610   }
1611   if (TryVal > CandVal) {
1612     if (Cand.Reason > Reason)
1613       Cand.Reason = Reason;
1614     return true;
1615   }
1616   return false;
1617 }
1618
1619 static bool tryGreater(unsigned TryVal, unsigned CandVal,
1620                        ConvergingScheduler::SchedCandidate &TryCand,
1621                        ConvergingScheduler::SchedCandidate &Cand,
1622                        ConvergingScheduler::CandReason Reason) {
1623   if (TryVal > CandVal) {
1624     TryCand.Reason = Reason;
1625     return true;
1626   }
1627   if (TryVal < CandVal) {
1628     if (Cand.Reason > Reason)
1629       Cand.Reason = Reason;
1630     return true;
1631   }
1632   return false;
1633 }
1634
1635 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1636   return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1637 }
1638
1639 /// Apply a set of heursitics to a new candidate. Heuristics are currently
1640 /// hierarchical. This may be more efficient than a graduated cost model because
1641 /// we don't need to evaluate all aspects of the model for each node in the
1642 /// queue. But it's really done to make the heuristics easier to debug and
1643 /// statistically analyze.
1644 ///
1645 /// \param Cand provides the policy and current best candidate.
1646 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1647 /// \param Zone describes the scheduled zone that we are extending.
1648 /// \param RPTracker describes reg pressure within the scheduled zone.
1649 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
1650 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1651                                        SchedCandidate &TryCand,
1652                                        SchedBoundary &Zone,
1653                                        const RegPressureTracker &RPTracker,
1654                                        RegPressureTracker &TempTracker) {
1655
1656   // Always initialize TryCand's RPDelta.
1657   TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1658                                   DAG->getRegionCriticalPSets(),
1659                                   DAG->getRegPressure().MaxSetPressure);
1660
1661   // Initialize the candidate if needed.
1662   if (!Cand.isValid()) {
1663     TryCand.Reason = NodeOrder;
1664     return;
1665   }
1666   // Avoid exceeding the target's limit.
1667   if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1668               Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1669     return;
1670   if (Cand.Reason == SingleExcess)
1671     Cand.Reason = MultiPressure;
1672
1673   // Avoid increasing the max critical pressure in the scheduled region.
1674   if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1675               Cand.RPDelta.CriticalMax.UnitIncrease,
1676               TryCand, Cand, SingleCritical))
1677     return;
1678   if (Cand.Reason == SingleCritical)
1679     Cand.Reason = MultiPressure;
1680
1681   // Keep clustered nodes together to encourage downstream peephole
1682   // optimizations which may reduce resource requirements.
1683   //
1684   // This is a best effort to set things up for a post-RA pass. Optimizations
1685   // like generating loads of multiple registers should ideally be done within
1686   // the scheduler pass by combining the loads during DAG postprocessing.
1687   const SUnit *NextClusterSU =
1688     Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1689   if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1690                  TryCand, Cand, Cluster))
1691     return;
1692   // Currently, weak edges are for clustering, so we hard-code that reason.
1693   // However, deferring the current TryCand will not change Cand's reason.
1694   CandReason OrigReason = Cand.Reason;
1695   if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1696               getWeakLeft(Cand.SU, Zone.isTop()),
1697               TryCand, Cand, Cluster)) {
1698     Cand.Reason = OrigReason;
1699     return;
1700   }
1701   // Avoid critical resource consumption and balance the schedule.
1702   TryCand.initResourceDelta(DAG, SchedModel);
1703   if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1704               TryCand, Cand, ResourceReduce))
1705     return;
1706   if (tryGreater(TryCand.ResDelta.DemandedResources,
1707                  Cand.ResDelta.DemandedResources,
1708                  TryCand, Cand, ResourceDemand))
1709     return;
1710
1711   // Avoid serializing long latency dependence chains.
1712   if (Cand.Policy.ReduceLatency) {
1713     if (Zone.isTop()) {
1714       if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1715           > Zone.ExpectedCount) {
1716         if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1717                     TryCand, Cand, TopDepthReduce))
1718           return;
1719       }
1720       if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1721                      TryCand, Cand, TopPathReduce))
1722         return;
1723     }
1724     else {
1725       if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1726           > Zone.ExpectedCount) {
1727         if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1728                     TryCand, Cand, BotHeightReduce))
1729           return;
1730       }
1731       if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1732                      TryCand, Cand, BotPathReduce))
1733         return;
1734     }
1735   }
1736
1737   // Avoid increasing the max pressure of the entire region.
1738   if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1739               Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1740     return;
1741   if (Cand.Reason == SingleMax)
1742     Cand.Reason = MultiPressure;
1743
1744   // Prefer immediate defs/users of the last scheduled instruction. This is a
1745   // nice pressure avoidance strategy that also conserves the processor's
1746   // register renaming resources and keeps the machine code readable.
1747   if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1748                  TryCand, Cand, NextDefUse))
1749     return;
1750
1751   // Fall through to original instruction order.
1752   if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1753       || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1754     TryCand.Reason = NodeOrder;
1755   }
1756 }
1757
1758 /// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1759 /// more desirable than RHS from scheduling standpoint.
1760 static bool compareRPDelta(const RegPressureDelta &LHS,
1761                            const RegPressureDelta &RHS) {
1762   // Compare each component of pressure in decreasing order of importance
1763   // without checking if any are valid. Invalid PressureElements are assumed to
1764   // have UnitIncrease==0, so are neutral.
1765
1766   // Avoid increasing the max critical pressure in the scheduled region.
1767   if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1768     DEBUG(dbgs() << "RP excess top - bot: "
1769           << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
1770     return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
1771   }
1772   // Avoid increasing the max critical pressure in the scheduled region.
1773   if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1774     DEBUG(dbgs() << "RP critical top - bot: "
1775           << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1776           << '\n');
1777     return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
1778   }
1779   // Avoid increasing the max pressure of the entire region.
1780   if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1781     DEBUG(dbgs() << "RP current top - bot: "
1782           << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1783           << '\n');
1784     return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
1785   }
1786   return false;
1787 }
1788
1789 #ifndef NDEBUG
1790 const char *ConvergingScheduler::getReasonStr(
1791   ConvergingScheduler::CandReason Reason) {
1792   switch (Reason) {
1793   case NoCand:         return "NOCAND    ";
1794   case SingleExcess:   return "REG-EXCESS";
1795   case SingleCritical: return "REG-CRIT  ";
1796   case Cluster:        return "CLUSTER   ";
1797   case SingleMax:      return "REG-MAX   ";
1798   case MultiPressure:  return "REG-MULTI ";
1799   case ResourceReduce: return "RES-REDUCE";
1800   case ResourceDemand: return "RES-DEMAND";
1801   case TopDepthReduce: return "TOP-DEPTH ";
1802   case TopPathReduce:  return "TOP-PATH  ";
1803   case BotHeightReduce:return "BOT-HEIGHT";
1804   case BotPathReduce:  return "BOT-PATH  ";
1805   case NextDefUse:     return "DEF-USE   ";
1806   case NodeOrder:      return "ORDER     ";
1807   };
1808   llvm_unreachable("Unknown reason!");
1809 }
1810
1811 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1812                                          const SchedBoundary &Zone) {
1813   const char *Label = getReasonStr(Cand.Reason);
1814   PressureElement P;
1815   unsigned ResIdx = 0;
1816   unsigned Latency = 0;
1817   switch (Cand.Reason) {
1818   default:
1819     break;
1820   case SingleExcess:
1821     P = Cand.RPDelta.Excess;
1822     break;
1823   case SingleCritical:
1824     P = Cand.RPDelta.CriticalMax;
1825     break;
1826   case SingleMax:
1827     P = Cand.RPDelta.CurrentMax;
1828     break;
1829   case ResourceReduce:
1830     ResIdx = Cand.Policy.ReduceResIdx;
1831     break;
1832   case ResourceDemand:
1833     ResIdx = Cand.Policy.DemandResIdx;
1834     break;
1835   case TopDepthReduce:
1836     Latency = Cand.SU->getDepth();
1837     break;
1838   case TopPathReduce:
1839     Latency = Cand.SU->getHeight();
1840     break;
1841   case BotHeightReduce:
1842     Latency = Cand.SU->getHeight();
1843     break;
1844   case BotPathReduce:
1845     Latency = Cand.SU->getDepth();
1846     break;
1847   }
1848   dbgs() << Label << " " << Zone.Available.getName() << " ";
1849   if (P.isValid())
1850     dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1851            << " ";
1852   else
1853     dbgs() << "     ";
1854   if (ResIdx)
1855     dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1856   else
1857     dbgs() << "        ";
1858   if (Latency)
1859     dbgs() << Latency << " cycles ";
1860   else
1861     dbgs() << "         ";
1862   Cand.SU->dump(DAG);
1863 }
1864 #endif
1865
1866 /// Pick the best candidate from the top queue.
1867 ///
1868 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1869 /// DAG building. To adjust for the current scheduling location we need to
1870 /// maintain the number of vreg uses remaining to be top-scheduled.
1871 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1872                                             const RegPressureTracker &RPTracker,
1873                                             SchedCandidate &Cand) {
1874   ReadyQueue &Q = Zone.Available;
1875
1876   DEBUG(Q.dump());
1877
1878   // getMaxPressureDelta temporarily modifies the tracker.
1879   RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1880
1881   for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
1882
1883     SchedCandidate TryCand(Cand.Policy);
1884     TryCand.SU = *I;
1885     tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1886     if (TryCand.Reason != NoCand) {
1887       // Initialize resource delta if needed in case future heuristics query it.
1888       if (TryCand.ResDelta == SchedResourceDelta())
1889         TryCand.initResourceDelta(DAG, SchedModel);
1890       Cand.setBest(TryCand);
1891       DEBUG(traceCandidate(Cand, Zone));
1892     }
1893   }
1894 }
1895
1896 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1897                       bool IsTop) {
1898   DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1899         << " SU(" << Cand.SU->NodeNum << ") "
1900         << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
1901 }
1902
1903 /// Pick the best candidate node from either the top or bottom queue.
1904 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
1905   // Schedule as far as possible in the direction of no choice. This is most
1906   // efficient, but also provides the best heuristics for CriticalPSets.
1907   if (SUnit *SU = Bot.pickOnlyChoice()) {
1908     IsTopNode = false;
1909     return SU;
1910   }
1911   if (SUnit *SU = Top.pickOnlyChoice()) {
1912     IsTopNode = true;
1913     return SU;
1914   }
1915   CandPolicy NoPolicy;
1916   SchedCandidate BotCand(NoPolicy);
1917   SchedCandidate TopCand(NoPolicy);
1918   checkResourceLimits(TopCand, BotCand);
1919
1920   // Prefer bottom scheduling when heuristics are silent.
1921   pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1922   assert(BotCand.Reason != NoCand && "failed to find the first candidate");
1923
1924   // If either Q has a single candidate that provides the least increase in
1925   // Excess pressure, we can immediately schedule from that Q.
1926   //
1927   // RegionCriticalPSets summarizes the pressure within the scheduled region and
1928   // affects picking from either Q. If scheduling in one direction must
1929   // increase pressure for one of the excess PSets, then schedule in that
1930   // direction first to provide more freedom in the other direction.
1931   if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
1932     IsTopNode = false;
1933     tracePick(BotCand, IsTopNode);
1934     return BotCand.SU;
1935   }
1936   // Check if the top Q has a better candidate.
1937   pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1938   assert(TopCand.Reason != NoCand && "failed to find the first candidate");
1939
1940   // If either Q has a single candidate that minimizes pressure above the
1941   // original region's pressure pick it.
1942   if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1943     if (TopCand.Reason < BotCand.Reason) {
1944       IsTopNode = true;
1945       tracePick(TopCand, IsTopNode);
1946       return TopCand.SU;
1947     }
1948     IsTopNode = false;
1949     tracePick(BotCand, IsTopNode);
1950     return BotCand.SU;
1951   }
1952   // Check for a salient pressure difference and pick the best from either side.
1953   if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
1954     IsTopNode = true;
1955     tracePick(TopCand, IsTopNode);
1956     return TopCand.SU;
1957   }
1958   // Otherwise prefer the bottom candidate, in node order if all else failed.
1959   if (TopCand.Reason < BotCand.Reason) {
1960     IsTopNode = true;
1961     tracePick(TopCand, IsTopNode);
1962     return TopCand.SU;
1963   }
1964   IsTopNode = false;
1965   tracePick(BotCand, IsTopNode);
1966   return BotCand.SU;
1967 }
1968
1969 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
1970 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1971   if (DAG->top() == DAG->bottom()) {
1972     assert(Top.Available.empty() && Top.Pending.empty() &&
1973            Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
1974     return NULL;
1975   }
1976   SUnit *SU;
1977   do {
1978     if (ForceTopDown) {
1979       SU = Top.pickOnlyChoice();
1980       if (!SU) {
1981         CandPolicy NoPolicy;
1982         SchedCandidate TopCand(NoPolicy);
1983         pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1984         assert(TopCand.Reason != NoCand && "failed to find the first candidate");
1985         SU = TopCand.SU;
1986       }
1987       IsTopNode = true;
1988     }
1989     else if (ForceBottomUp) {
1990       SU = Bot.pickOnlyChoice();
1991       if (!SU) {
1992         CandPolicy NoPolicy;
1993         SchedCandidate BotCand(NoPolicy);
1994         pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1995         assert(BotCand.Reason != NoCand && "failed to find the first candidate");
1996         SU = BotCand.SU;
1997       }
1998       IsTopNode = false;
1999     }
2000     else {
2001       SU = pickNodeBidirectional(IsTopNode);
2002     }
2003   } while (SU->isScheduled);
2004
2005   if (SU->isTopReady())
2006     Top.removeReady(SU);
2007   if (SU->isBottomReady())
2008     Bot.removeReady(SU);
2009
2010   DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2011         << " Scheduling Instruction in cycle "
2012         << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2013         SU->dump(DAG));
2014   return SU;
2015 }
2016
2017 /// Update the scheduler's state after scheduling a node. This is the same node
2018 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
2019 /// it's state based on the current cycle before MachineSchedStrategy does.
2020 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2021   if (IsTopNode) {
2022     SU->TopReadyCycle = Top.CurrCycle;
2023     Top.bumpNode(SU);
2024   }
2025   else {
2026     SU->BotReadyCycle = Bot.CurrCycle;
2027     Bot.bumpNode(SU);
2028   }
2029 }
2030
2031 /// Create the standard converging machine scheduler. This will be used as the
2032 /// default scheduler if the target does not set a default.
2033 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
2034   assert((!ForceTopDown || !ForceBottomUp) &&
2035          "-misched-topdown incompatible with -misched-bottomup");
2036   ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2037   // Register DAG post-processors.
2038   if (EnableLoadCluster)
2039     DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2040   if (EnableMacroFusion)
2041     DAG->addMutation(new MacroFusion(DAG->TII));
2042   return DAG;
2043 }
2044 static MachineSchedRegistry
2045 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2046                         createConvergingSched);
2047
2048 //===----------------------------------------------------------------------===//
2049 // ILP Scheduler. Currently for experimental analysis of heuristics.
2050 //===----------------------------------------------------------------------===//
2051
2052 namespace {
2053 /// \brief Order nodes by the ILP metric.
2054 struct ILPOrder {
2055   SchedDFSResult *DFSResult;
2056   BitVector *ScheduledTrees;
2057   bool MaximizeILP;
2058
2059   ILPOrder(SchedDFSResult *dfs, BitVector *schedtrees, bool MaxILP)
2060     : DFSResult(dfs), ScheduledTrees(schedtrees), MaximizeILP(MaxILP) {}
2061
2062   /// \brief Apply a less-than relation on node priority.
2063   ///
2064   /// (Return true if A comes after B in the Q.)
2065   bool operator()(const SUnit *A, const SUnit *B) const {
2066     unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2067     unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2068     if (SchedTreeA != SchedTreeB) {
2069       // Unscheduled trees have lower priority.
2070       if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2071         return ScheduledTrees->test(SchedTreeB);
2072
2073       // Trees with shallower connections have have lower priority.
2074       if (DFSResult->getSubtreeLevel(SchedTreeA)
2075           != DFSResult->getSubtreeLevel(SchedTreeB)) {
2076         return DFSResult->getSubtreeLevel(SchedTreeA)
2077           < DFSResult->getSubtreeLevel(SchedTreeB);
2078       }
2079     }
2080     if (MaximizeILP)
2081       return DFSResult->getILP(A) < DFSResult->getILP(B);
2082     else
2083       return DFSResult->getILP(A) > DFSResult->getILP(B);
2084   }
2085 };
2086
2087 /// \brief Schedule based on the ILP metric.
2088 class ILPScheduler : public MachineSchedStrategy {
2089   /// In case all subtrees are eventually connected to a common root through
2090   /// data dependence (e.g. reduction), place an upper limit on their size.
2091   ///
2092   /// FIXME: A subtree limit is generally good, but in the situation commented
2093   /// above, where multiple similar subtrees feed a common root, we should
2094   /// only split at a point where the resulting subtrees will be balanced.
2095   /// (a motivating test case must be found).
2096   static const unsigned SubtreeLimit = 16;
2097
2098   SchedDFSResult DFSResult;
2099   BitVector ScheduledTrees;
2100   ILPOrder Cmp;
2101
2102   std::vector<SUnit*> ReadyQ;
2103 public:
2104   ILPScheduler(bool MaximizeILP)
2105   : DFSResult(/*BottomUp=*/true, SubtreeLimit),
2106     Cmp(&DFSResult, &ScheduledTrees, MaximizeILP) {}
2107
2108   virtual void initialize(ScheduleDAGMI *DAG) {
2109     ReadyQ.clear();
2110     DFSResult.clear();
2111     DFSResult.resize(DAG->SUnits.size());
2112     ScheduledTrees.clear();
2113   }
2114
2115   virtual void registerRoots() {
2116     DFSResult.compute(ReadyQ);
2117     ScheduledTrees.resize(DFSResult.getNumSubtrees());
2118     // Restore the heap in ReadyQ with the updated DFS results.
2119     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2120   }
2121
2122   /// Implement MachineSchedStrategy interface.
2123   /// -----------------------------------------
2124
2125   /// Callback to select the highest priority node from the ready Q.
2126   virtual SUnit *pickNode(bool &IsTopNode) {
2127     if (ReadyQ.empty()) return NULL;
2128     pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2129     SUnit *SU = ReadyQ.back();
2130     ReadyQ.pop_back();
2131     IsTopNode = false;
2132     DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2133           << *SU->getInstr()
2134           << " ILP: " << DFSResult.getILP(SU)
2135           << " Tree: " << DFSResult.getSubtreeID(SU) << " @"
2136           << DFSResult.getSubtreeLevel(DFSResult.getSubtreeID(SU))<< '\n');
2137     return SU;
2138   }
2139
2140   /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2141   /// DFSResults, and resort the priority Q.
2142   virtual void schedNode(SUnit *SU, bool IsTopNode) {
2143     assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2144     if (!ScheduledTrees.test(DFSResult.getSubtreeID(SU))) {
2145       ScheduledTrees.set(DFSResult.getSubtreeID(SU));
2146       DFSResult.scheduleTree(DFSResult.getSubtreeID(SU));
2147       std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2148     }
2149   }
2150
2151   virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2152
2153   virtual void releaseBottomNode(SUnit *SU) {
2154     ReadyQ.push_back(SU);
2155     std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2156   }
2157 };
2158 } // namespace
2159
2160 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2161   return new ScheduleDAGMI(C, new ILPScheduler(true));
2162 }
2163 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2164   return new ScheduleDAGMI(C, new ILPScheduler(false));
2165 }
2166 static MachineSchedRegistry ILPMaxRegistry(
2167   "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2168 static MachineSchedRegistry ILPMinRegistry(
2169   "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2170
2171 //===----------------------------------------------------------------------===//
2172 // Machine Instruction Shuffler for Correctness Testing
2173 //===----------------------------------------------------------------------===//
2174
2175 #ifndef NDEBUG
2176 namespace {
2177 /// Apply a less-than relation on the node order, which corresponds to the
2178 /// instruction order prior to scheduling. IsReverse implements greater-than.
2179 template<bool IsReverse>
2180 struct SUnitOrder {
2181   bool operator()(SUnit *A, SUnit *B) const {
2182     if (IsReverse)
2183       return A->NodeNum > B->NodeNum;
2184     else
2185       return A->NodeNum < B->NodeNum;
2186   }
2187 };
2188
2189 /// Reorder instructions as much as possible.
2190 class InstructionShuffler : public MachineSchedStrategy {
2191   bool IsAlternating;
2192   bool IsTopDown;
2193
2194   // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2195   // gives nodes with a higher number higher priority causing the latest
2196   // instructions to be scheduled first.
2197   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2198     TopQ;
2199   // When scheduling bottom-up, use greater-than as the queue priority.
2200   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2201     BottomQ;
2202 public:
2203   InstructionShuffler(bool alternate, bool topdown)
2204     : IsAlternating(alternate), IsTopDown(topdown) {}
2205
2206   virtual void initialize(ScheduleDAGMI *) {
2207     TopQ.clear();
2208     BottomQ.clear();
2209   }
2210
2211   /// Implement MachineSchedStrategy interface.
2212   /// -----------------------------------------
2213
2214   virtual SUnit *pickNode(bool &IsTopNode) {
2215     SUnit *SU;
2216     if (IsTopDown) {
2217       do {
2218         if (TopQ.empty()) return NULL;
2219         SU = TopQ.top();
2220         TopQ.pop();
2221       } while (SU->isScheduled);
2222       IsTopNode = true;
2223     }
2224     else {
2225       do {
2226         if (BottomQ.empty()) return NULL;
2227         SU = BottomQ.top();
2228         BottomQ.pop();
2229       } while (SU->isScheduled);
2230       IsTopNode = false;
2231     }
2232     if (IsAlternating)
2233       IsTopDown = !IsTopDown;
2234     return SU;
2235   }
2236
2237   virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2238
2239   virtual void releaseTopNode(SUnit *SU) {
2240     TopQ.push(SU);
2241   }
2242   virtual void releaseBottomNode(SUnit *SU) {
2243     BottomQ.push(SU);
2244   }
2245 };
2246 } // namespace
2247
2248 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
2249   bool Alternate = !ForceTopDown && !ForceBottomUp;
2250   bool TopDown = !ForceBottomUp;
2251   assert((TopDown || !ForceTopDown) &&
2252          "-misched-topdown incompatible with -misched-bottomup");
2253   return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
2254 }
2255 static MachineSchedRegistry ShufflerRegistry(
2256   "shuffle", "Shuffle machine instructions alternating directions",
2257   createInstructionShuffler);
2258 #endif // !NDEBUG