shoot a few more std::ostream print methods in the head.
[oota-llvm.git] / lib / CodeGen / PostRASchedulerList.cpp
1 //===----- SchedulePostRAList.cpp - list 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 // This implements a top-down list scheduler, using standard algorithms.
11 // The basic approach uses a priority queue of available nodes to schedule.
12 // One at a time, nodes are taken from the priority queue (thus in priority
13 // order), checked for legality to schedule, and emitted if legal.
14 //
15 // Nodes may not be legal to schedule either due to structural hazards (e.g.
16 // pipeline or resource constraints) or because an input to the instruction has
17 // not completed execution.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "post-RA-sched"
22 #include "ExactHazardRecognizer.h"
23 #include "SimpleHazardRecognizer.h"
24 #include "ScheduleDAGInstrs.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/LatencyPriorityQueue.h"
27 #include "llvm/CodeGen/SchedulerRegistry.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/ADT/Statistic.h"
42 #include <map>
43 using namespace llvm;
44
45 STATISTIC(NumNoops, "Number of noops inserted");
46 STATISTIC(NumStalls, "Number of pipeline stalls");
47
48 static cl::opt<bool>
49 EnableAntiDepBreaking("break-anti-dependencies",
50                       cl::desc("Break post-RA scheduling anti-dependencies"),
51                       cl::init(true), cl::Hidden);
52
53 static cl::opt<bool>
54 EnablePostRAHazardAvoidance("avoid-hazards",
55                       cl::desc("Enable exact hazard avoidance"),
56                       cl::init(false), cl::Hidden);
57
58 namespace {
59   class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
60   public:
61     static char ID;
62     PostRAScheduler() : MachineFunctionPass(&ID) {}
63
64     void getAnalysisUsage(AnalysisUsage &AU) const {
65       AU.setPreservesCFG();
66       AU.addRequired<MachineDominatorTree>();
67       AU.addPreserved<MachineDominatorTree>();
68       AU.addRequired<MachineLoopInfo>();
69       AU.addPreserved<MachineLoopInfo>();
70       MachineFunctionPass::getAnalysisUsage(AU);
71     }
72
73     const char *getPassName() const {
74       return "Post RA top-down list latency scheduler";
75     }
76
77     bool runOnMachineFunction(MachineFunction &Fn);
78   };
79   char PostRAScheduler::ID = 0;
80
81   class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
82     /// AvailableQueue - The priority queue to use for the available SUnits.
83     ///
84     LatencyPriorityQueue AvailableQueue;
85   
86     /// PendingQueue - This contains all of the instructions whose operands have
87     /// been issued, but their results are not ready yet (due to the latency of
88     /// the operation).  Once the operands becomes available, the instruction is
89     /// added to the AvailableQueue.
90     std::vector<SUnit*> PendingQueue;
91
92     /// Topo - A topological ordering for SUnits.
93     ScheduleDAGTopologicalSort Topo;
94
95     /// AllocatableSet - The set of allocatable registers.
96     /// We'll be ignoring anti-dependencies on non-allocatable registers,
97     /// because they may not be safe to break.
98     const BitVector AllocatableSet;
99
100     /// HazardRec - The hazard recognizer to use.
101     ScheduleHazardRecognizer *HazardRec;
102
103     /// Classes - For live regs that are only used in one register class in a
104     /// live range, the register class. If the register is not live, the
105     /// corresponding value is null. If the register is live but used in
106     /// multiple register classes, the corresponding value is -1 casted to a
107     /// pointer.
108     const TargetRegisterClass *
109       Classes[TargetRegisterInfo::FirstVirtualRegister];
110
111     /// RegRegs - Map registers to all their references within a live range.
112     std::multimap<unsigned, MachineOperand *> RegRefs;
113
114     /// The index of the most recent kill (proceding bottom-up), or ~0u if
115     /// the register is not live.
116     unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
117
118     /// The index of the most recent complete def (proceding bottom up), or ~0u
119     /// if the register is live.
120     unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
121
122   public:
123     SchedulePostRATDList(MachineFunction &MF,
124                          const MachineLoopInfo &MLI,
125                          const MachineDominatorTree &MDT,
126                          ScheduleHazardRecognizer *HR)
127       : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
128         AllocatableSet(TRI->getAllocatableSet(MF)),
129         HazardRec(HR) {}
130
131     ~SchedulePostRATDList() {
132       delete HazardRec;
133     }
134
135     /// StartBlock - Initialize register live-range state for scheduling in
136     /// this block.
137     ///
138     void StartBlock(MachineBasicBlock *BB);
139
140     /// Schedule - Schedule the instruction range using list scheduling.
141     ///
142     void Schedule();
143
144     /// Observe - Update liveness information to account for the current
145     /// instruction, which will not be scheduled.
146     ///
147     void Observe(MachineInstr *MI, unsigned Count);
148
149     /// FinishBlock - Clean up register live-range state.
150     ///
151     void FinishBlock();
152
153   private:
154     void PrescanInstruction(MachineInstr *MI);
155     void ScanInstruction(MachineInstr *MI, unsigned Count);
156     void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
157     void ReleaseSuccessors(SUnit *SU);
158     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
159     void ListScheduleTopDown();
160     bool BreakAntiDependencies();
161     unsigned findSuitableFreeRegister(unsigned AntiDepReg,
162                                       unsigned LastNewReg,
163                                       const TargetRegisterClass *);
164   };
165 }
166
167 /// isSchedulingBoundary - Test if the given instruction should be
168 /// considered a scheduling boundary. This primarily includes labels
169 /// and terminators.
170 ///
171 static bool isSchedulingBoundary(const MachineInstr *MI,
172                                  const MachineFunction &MF) {
173   // Terminators and labels can't be scheduled around.
174   if (MI->getDesc().isTerminator() || MI->isLabel())
175     return true;
176
177   // Don't attempt to schedule around any instruction that modifies
178   // a stack-oriented pointer, as it's unlikely to be profitable. This
179   // saves compile time, because it doesn't require every single
180   // stack slot reference to depend on the instruction that does the
181   // modification.
182   const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
183   if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
184     return true;
185
186   return false;
187 }
188
189 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
190   DEBUG(errs() << "PostRAScheduler\n");
191
192   const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
193   const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
194   const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
195   ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
196     (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
197     (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
198
199   SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
200
201   // Loop over all of the basic blocks
202   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
203        MBB != MBBe; ++MBB) {
204     // Initialize register live-range state for scheduling in this block.
205     Scheduler.StartBlock(MBB);
206
207     // Schedule each sequence of instructions not interrupted by a label
208     // or anything else that effectively needs to shut down scheduling.
209     MachineBasicBlock::iterator Current = MBB->end();
210     unsigned Count = MBB->size(), CurrentCount = Count;
211     for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
212       MachineInstr *MI = prior(I);
213       if (isSchedulingBoundary(MI, Fn)) {
214         Scheduler.Run(MBB, I, Current, CurrentCount);
215         Scheduler.EmitSchedule();
216         Current = MI;
217         CurrentCount = Count - 1;
218         Scheduler.Observe(MI, CurrentCount);
219       }
220       I = MI;
221       --Count;
222     }
223     assert(Count == 0 && "Instruction count mismatch!");
224     assert((MBB->begin() == Current || CurrentCount != 0) &&
225            "Instruction count mismatch!");
226     Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
227     Scheduler.EmitSchedule();
228
229     // Clean up register live-range state.
230     Scheduler.FinishBlock();
231   }
232
233   return true;
234 }
235   
236 /// StartBlock - Initialize register live-range state for scheduling in
237 /// this block.
238 ///
239 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
240   // Call the superclass.
241   ScheduleDAGInstrs::StartBlock(BB);
242
243   // Reset the hazard recognizer.
244   HazardRec->Reset();
245
246   // Clear out the register class data.
247   std::fill(Classes, array_endof(Classes),
248             static_cast<const TargetRegisterClass *>(0));
249
250   // Initialize the indices to indicate that no registers are live.
251   std::fill(KillIndices, array_endof(KillIndices), ~0u);
252   std::fill(DefIndices, array_endof(DefIndices), BB->size());
253
254   // Determine the live-out physregs for this block.
255   if (!BB->empty() && BB->back().getDesc().isReturn())
256     // In a return block, examine the function live-out regs.
257     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
258          E = MRI.liveout_end(); I != E; ++I) {
259       unsigned Reg = *I;
260       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
261       KillIndices[Reg] = BB->size();
262       DefIndices[Reg] = ~0u;
263       // Repeat, for all aliases.
264       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
265         unsigned AliasReg = *Alias;
266         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
267         KillIndices[AliasReg] = BB->size();
268         DefIndices[AliasReg] = ~0u;
269       }
270     }
271   else
272     // In a non-return block, examine the live-in regs of all successors.
273     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
274          SE = BB->succ_end(); SI != SE; ++SI)
275       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
276            E = (*SI)->livein_end(); I != E; ++I) {
277         unsigned Reg = *I;
278         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
279         KillIndices[Reg] = BB->size();
280         DefIndices[Reg] = ~0u;
281         // Repeat, for all aliases.
282         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
283           unsigned AliasReg = *Alias;
284           Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
285           KillIndices[AliasReg] = BB->size();
286           DefIndices[AliasReg] = ~0u;
287         }
288       }
289
290   // Consider callee-saved registers as live-out, since we're running after
291   // prologue/epilogue insertion so there's no way to add additional
292   // saved registers.
293   //
294   // TODO: If the callee saves and restores these, then we can potentially
295   // use them between the save and the restore. To do that, we could scan
296   // the exit blocks to see which of these registers are defined.
297   // Alternatively, callee-saved registers that aren't saved and restored
298   // could be marked live-in in every block.
299   for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
300     unsigned Reg = *I;
301     Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
302     KillIndices[Reg] = BB->size();
303     DefIndices[Reg] = ~0u;
304     // Repeat, for all aliases.
305     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
306       unsigned AliasReg = *Alias;
307       Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
308       KillIndices[AliasReg] = BB->size();
309       DefIndices[AliasReg] = ~0u;
310     }
311   }
312 }
313
314 /// Schedule - Schedule the instruction range using list scheduling.
315 ///
316 void SchedulePostRATDList::Schedule() {
317   DEBUG(errs() << "********** List Scheduling **********\n");
318   
319   // Build the scheduling graph.
320   BuildSchedGraph();
321
322   if (EnableAntiDepBreaking) {
323     if (BreakAntiDependencies()) {
324       // We made changes. Update the dependency graph.
325       // Theoretically we could update the graph in place:
326       // When a live range is changed to use a different register, remove
327       // the def's anti-dependence *and* output-dependence edges due to
328       // that register, and add new anti-dependence and output-dependence
329       // edges based on the next live range of the register.
330       SUnits.clear();
331       EntrySU = SUnit();
332       ExitSU = SUnit();
333       BuildSchedGraph();
334     }
335   }
336
337   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
338           SUnits[su].dumpAll(this));
339
340   AvailableQueue.initNodes(SUnits);
341
342   ListScheduleTopDown();
343   
344   AvailableQueue.releaseState();
345 }
346
347 /// Observe - Update liveness information to account for the current
348 /// instruction, which will not be scheduled.
349 ///
350 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
351   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
352
353   // Any register which was defined within the previous scheduling region
354   // may have been rescheduled and its lifetime may overlap with registers
355   // in ways not reflected in our current liveness state. For each such
356   // register, adjust the liveness state to be conservatively correct.
357   for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
358     if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
359       assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
360       // Mark this register to be non-renamable.
361       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
362       // Move the def index to the end of the previous region, to reflect
363       // that the def could theoretically have been scheduled at the end.
364       DefIndices[Reg] = InsertPosIndex;
365     }
366
367   PrescanInstruction(MI);
368   ScanInstruction(MI, Count);
369 }
370
371 /// FinishBlock - Clean up register live-range state.
372 ///
373 void SchedulePostRATDList::FinishBlock() {
374   RegRefs.clear();
375
376   // Call the superclass.
377   ScheduleDAGInstrs::FinishBlock();
378 }
379
380 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
381 /// critical path.
382 static SDep *CriticalPathStep(SUnit *SU) {
383   SDep *Next = 0;
384   unsigned NextDepth = 0;
385   // Find the predecessor edge with the greatest depth.
386   for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
387        P != PE; ++P) {
388     SUnit *PredSU = P->getSUnit();
389     unsigned PredLatency = P->getLatency();
390     unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
391     // In the case of a latency tie, prefer an anti-dependency edge over
392     // other types of edges.
393     if (NextDepth < PredTotalLatency ||
394         (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
395       NextDepth = PredTotalLatency;
396       Next = &*P;
397     }
398   }
399   return Next;
400 }
401
402 void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
403   // Scan the register operands for this instruction and update
404   // Classes and RegRefs.
405   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
406     MachineOperand &MO = MI->getOperand(i);
407     if (!MO.isReg()) continue;
408     unsigned Reg = MO.getReg();
409     if (Reg == 0) continue;
410     const TargetRegisterClass *NewRC = 0;
411     
412     if (i < MI->getDesc().getNumOperands())
413       NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
414
415     // For now, only allow the register to be changed if its register
416     // class is consistent across all uses.
417     if (!Classes[Reg] && NewRC)
418       Classes[Reg] = NewRC;
419     else if (!NewRC || Classes[Reg] != NewRC)
420       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
421
422     // Now check for aliases.
423     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
424       // If an alias of the reg is used during the live range, give up.
425       // Note that this allows us to skip checking if AntiDepReg
426       // overlaps with any of the aliases, among other things.
427       unsigned AliasReg = *Alias;
428       if (Classes[AliasReg]) {
429         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
430         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
431       }
432     }
433
434     // If we're still willing to consider this register, note the reference.
435     if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
436       RegRefs.insert(std::make_pair(Reg, &MO));
437   }
438 }
439
440 void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
441                                            unsigned Count) {
442   // Update liveness.
443   // Proceding upwards, registers that are defed but not used in this
444   // instruction are now dead.
445   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
446     MachineOperand &MO = MI->getOperand(i);
447     if (!MO.isReg()) continue;
448     unsigned Reg = MO.getReg();
449     if (Reg == 0) continue;
450     if (!MO.isDef()) continue;
451     // Ignore two-addr defs.
452     if (MI->isRegTiedToUseOperand(i)) continue;
453
454     DefIndices[Reg] = Count;
455     KillIndices[Reg] = ~0u;
456           assert(((KillIndices[Reg] == ~0u) !=
457                   (DefIndices[Reg] == ~0u)) &&
458                "Kill and Def maps aren't consistent for Reg!");
459     Classes[Reg] = 0;
460     RegRefs.erase(Reg);
461     // Repeat, for all subregs.
462     for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
463          *Subreg; ++Subreg) {
464       unsigned SubregReg = *Subreg;
465       DefIndices[SubregReg] = Count;
466       KillIndices[SubregReg] = ~0u;
467       Classes[SubregReg] = 0;
468       RegRefs.erase(SubregReg);
469     }
470     // Conservatively mark super-registers as unusable.
471     for (const unsigned *Super = TRI->getSuperRegisters(Reg);
472          *Super; ++Super) {
473       unsigned SuperReg = *Super;
474       Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
475     }
476   }
477   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
478     MachineOperand &MO = MI->getOperand(i);
479     if (!MO.isReg()) continue;
480     unsigned Reg = MO.getReg();
481     if (Reg == 0) continue;
482     if (!MO.isUse()) continue;
483
484     const TargetRegisterClass *NewRC = 0;
485     if (i < MI->getDesc().getNumOperands())
486       NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
487
488     // For now, only allow the register to be changed if its register
489     // class is consistent across all uses.
490     if (!Classes[Reg] && NewRC)
491       Classes[Reg] = NewRC;
492     else if (!NewRC || Classes[Reg] != NewRC)
493       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
494
495     RegRefs.insert(std::make_pair(Reg, &MO));
496
497     // It wasn't previously live but now it is, this is a kill.
498     if (KillIndices[Reg] == ~0u) {
499       KillIndices[Reg] = Count;
500       DefIndices[Reg] = ~0u;
501           assert(((KillIndices[Reg] == ~0u) !=
502                   (DefIndices[Reg] == ~0u)) &&
503                "Kill and Def maps aren't consistent for Reg!");
504     }
505     // Repeat, for all aliases.
506     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
507       unsigned AliasReg = *Alias;
508       if (KillIndices[AliasReg] == ~0u) {
509         KillIndices[AliasReg] = Count;
510         DefIndices[AliasReg] = ~0u;
511       }
512     }
513   }
514 }
515
516 unsigned
517 SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
518                                                unsigned LastNewReg,
519                                                const TargetRegisterClass *RC) {
520   for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
521        RE = RC->allocation_order_end(MF); R != RE; ++R) {
522     unsigned NewReg = *R;
523     // Don't replace a register with itself.
524     if (NewReg == AntiDepReg) continue;
525     // Don't replace a register with one that was recently used to repair
526     // an anti-dependence with this AntiDepReg, because that would
527     // re-introduce that anti-dependence.
528     if (NewReg == LastNewReg) continue;
529     // If NewReg is dead and NewReg's most recent def is not before
530     // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
531     assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
532            "Kill and Def maps aren't consistent for AntiDepReg!");
533     assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
534            "Kill and Def maps aren't consistent for NewReg!");
535     if (KillIndices[NewReg] != ~0u ||
536         Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
537         KillIndices[AntiDepReg] > DefIndices[NewReg])
538       continue;
539     return NewReg;
540   }
541
542   // No registers are free and available!
543   return 0;
544 }
545
546 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
547 /// of the ScheduleDAG and break them by renaming registers.
548 ///
549 bool SchedulePostRATDList::BreakAntiDependencies() {
550   // The code below assumes that there is at least one instruction,
551   // so just duck out immediately if the block is empty.
552   if (SUnits.empty()) return false;
553
554   // Find the node at the bottom of the critical path.
555   SUnit *Max = 0;
556   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
557     SUnit *SU = &SUnits[i];
558     if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
559       Max = SU;
560   }
561
562   DEBUG(errs() << "Critical path has total latency "
563         << (Max->getDepth() + Max->Latency) << "\n");
564
565   // Track progress along the critical path through the SUnit graph as we walk
566   // the instructions.
567   SUnit *CriticalPathSU = Max;
568   MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
569
570   // Consider this pattern:
571   //   A = ...
572   //   ... = A
573   //   A = ...
574   //   ... = A
575   //   A = ...
576   //   ... = A
577   //   A = ...
578   //   ... = A
579   // There are three anti-dependencies here, and without special care,
580   // we'd break all of them using the same register:
581   //   A = ...
582   //   ... = A
583   //   B = ...
584   //   ... = B
585   //   B = ...
586   //   ... = B
587   //   B = ...
588   //   ... = B
589   // because at each anti-dependence, B is the first register that
590   // isn't A which is free.  This re-introduces anti-dependencies
591   // at all but one of the original anti-dependencies that we were
592   // trying to break.  To avoid this, keep track of the most recent
593   // register that each register was replaced with, avoid
594   // using it to repair an anti-dependence on the same register.
595   // This lets us produce this:
596   //   A = ...
597   //   ... = A
598   //   B = ...
599   //   ... = B
600   //   C = ...
601   //   ... = C
602   //   B = ...
603   //   ... = B
604   // This still has an anti-dependence on B, but at least it isn't on the
605   // original critical path.
606   //
607   // TODO: If we tracked more than one register here, we could potentially
608   // fix that remaining critical edge too. This is a little more involved,
609   // because unlike the most recent register, less recent registers should
610   // still be considered, though only if no other registers are available.
611   unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
612
613   // Attempt to break anti-dependence edges on the critical path. Walk the
614   // instructions from the bottom up, tracking information about liveness
615   // as we go to help determine which registers are available.
616   bool Changed = false;
617   unsigned Count = InsertPosIndex - 1;
618   for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
619        I != E; --Count) {
620     MachineInstr *MI = --I;
621
622     // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
623     // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
624     // is left behind appearing to clobber the super-register, while the
625     // subregister needs to remain live. So we just ignore them.
626     if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
627       continue;
628
629     // Check if this instruction has a dependence on the critical path that
630     // is an anti-dependence that we may be able to break. If it is, set
631     // AntiDepReg to the non-zero register associated with the anti-dependence.
632     //
633     // We limit our attention to the critical path as a heuristic to avoid
634     // breaking anti-dependence edges that aren't going to significantly
635     // impact the overall schedule. There are a limited number of registers
636     // and we want to save them for the important edges.
637     // 
638     // TODO: Instructions with multiple defs could have multiple
639     // anti-dependencies. The current code here only knows how to break one
640     // edge per instruction. Note that we'd have to be able to break all of
641     // the anti-dependencies in an instruction in order to be effective.
642     unsigned AntiDepReg = 0;
643     if (MI == CriticalPathMI) {
644       if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
645         SUnit *NextSU = Edge->getSUnit();
646
647         // Only consider anti-dependence edges.
648         if (Edge->getKind() == SDep::Anti) {
649           AntiDepReg = Edge->getReg();
650           assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
651           // Don't break anti-dependencies on non-allocatable registers.
652           if (!AllocatableSet.test(AntiDepReg))
653             AntiDepReg = 0;
654           else {
655             // If the SUnit has other dependencies on the SUnit that it
656             // anti-depends on, don't bother breaking the anti-dependency
657             // since those edges would prevent such units from being
658             // scheduled past each other regardless.
659             //
660             // Also, if there are dependencies on other SUnits with the
661             // same register as the anti-dependency, don't attempt to
662             // break it.
663             for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
664                  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
665               if (P->getSUnit() == NextSU ?
666                     (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
667                     (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
668                 AntiDepReg = 0;
669                 break;
670               }
671           }
672         }
673         CriticalPathSU = NextSU;
674         CriticalPathMI = CriticalPathSU->getInstr();
675       } else {
676         // We've reached the end of the critical path.
677         CriticalPathSU = 0;
678         CriticalPathMI = 0;
679       }
680     }
681
682     PrescanInstruction(MI);
683
684     // If this instruction has a use of AntiDepReg, breaking it
685     // is invalid.
686     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
687       MachineOperand &MO = MI->getOperand(i);
688       if (!MO.isReg()) continue;
689       unsigned Reg = MO.getReg();
690       if (Reg == 0) continue;
691       if (MO.isUse() && AntiDepReg == Reg) {
692         AntiDepReg = 0;
693         break;
694       }
695     }
696
697     // Determine AntiDepReg's register class, if it is live and is
698     // consistently used within a single class.
699     const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
700     assert((AntiDepReg == 0 || RC != NULL) &&
701            "Register should be live if it's causing an anti-dependence!");
702     if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
703       AntiDepReg = 0;
704
705     // Look for a suitable register to use to break the anti-depenence.
706     //
707     // TODO: Instead of picking the first free register, consider which might
708     // be the best.
709     if (AntiDepReg != 0) {
710       if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
711                                                      LastNewReg[AntiDepReg],
712                                                      RC)) {
713         DEBUG(errs() << "Breaking anti-dependence edge on "
714               << TRI->getName(AntiDepReg)
715               << " with " << RegRefs.count(AntiDepReg) << " references"
716               << " using " << TRI->getName(NewReg) << "!\n");
717
718         // Update the references to the old register to refer to the new
719         // register.
720         std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
721                   std::multimap<unsigned, MachineOperand *>::iterator>
722            Range = RegRefs.equal_range(AntiDepReg);
723         for (std::multimap<unsigned, MachineOperand *>::iterator
724              Q = Range.first, QE = Range.second; Q != QE; ++Q)
725           Q->second->setReg(NewReg);
726
727         // We just went back in time and modified history; the
728         // liveness information for the anti-depenence reg is now
729         // inconsistent. Set the state as if it were dead.
730         Classes[NewReg] = Classes[AntiDepReg];
731         DefIndices[NewReg] = DefIndices[AntiDepReg];
732         KillIndices[NewReg] = KillIndices[AntiDepReg];
733         assert(((KillIndices[NewReg] == ~0u) !=
734                 (DefIndices[NewReg] == ~0u)) &&
735              "Kill and Def maps aren't consistent for NewReg!");
736
737         Classes[AntiDepReg] = 0;
738         DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
739         KillIndices[AntiDepReg] = ~0u;
740         assert(((KillIndices[AntiDepReg] == ~0u) !=
741                 (DefIndices[AntiDepReg] == ~0u)) &&
742              "Kill and Def maps aren't consistent for AntiDepReg!");
743
744         RegRefs.erase(AntiDepReg);
745         Changed = true;
746         LastNewReg[AntiDepReg] = NewReg;
747       }
748     }
749
750     ScanInstruction(MI, Count);
751   }
752
753   return Changed;
754 }
755
756 //===----------------------------------------------------------------------===//
757 //  Top-Down Scheduling
758 //===----------------------------------------------------------------------===//
759
760 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
761 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
762 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
763   SUnit *SuccSU = SuccEdge->getSUnit();
764   --SuccSU->NumPredsLeft;
765   
766 #ifndef NDEBUG
767   if (SuccSU->NumPredsLeft < 0) {
768     cerr << "*** Scheduling failed! ***\n";
769     SuccSU->dump(this);
770     cerr << " has been released too many times!\n";
771     llvm_unreachable(0);
772   }
773 #endif
774   
775   // Compute how many cycles it will be before this actually becomes
776   // available.  This is the max of the start time of all predecessors plus
777   // their latencies.
778   SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
779   
780   // If all the node's predecessors are scheduled, this node is ready
781   // to be scheduled. Ignore the special ExitSU node.
782   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
783     PendingQueue.push_back(SuccSU);
784 }
785
786 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
787 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
788   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
789        I != E; ++I)
790     ReleaseSucc(SU, &*I);
791 }
792
793 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
794 /// count of its successors. If a successor pending count is zero, add it to
795 /// the Available queue.
796 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
797   DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
798   DEBUG(SU->dump(this));
799   
800   Sequence.push_back(SU);
801   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
802   SU->setDepthToAtLeast(CurCycle);
803
804   ReleaseSuccessors(SU);
805   SU->isScheduled = true;
806   AvailableQueue.ScheduledNode(SU);
807 }
808
809 /// ListScheduleTopDown - The main loop of list scheduling for top-down
810 /// schedulers.
811 void SchedulePostRATDList::ListScheduleTopDown() {
812   unsigned CurCycle = 0;
813
814   // Release any successors of the special Entry node.
815   ReleaseSuccessors(&EntrySU);
816
817   // All leaves to Available queue.
818   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
819     // It is available if it has no predecessors.
820     if (SUnits[i].Preds.empty()) {
821       AvailableQueue.push(&SUnits[i]);
822       SUnits[i].isAvailable = true;
823     }
824   }
825
826   // In any cycle where we can't schedule any instructions, we must
827   // stall or emit a noop, depending on the target.
828   bool CycleInstCnt = 0;
829
830   // While Available queue is not empty, grab the node with the highest
831   // priority. If it is not ready put it back.  Schedule the node.
832   std::vector<SUnit*> NotReady;
833   Sequence.reserve(SUnits.size());
834   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
835     // Check to see if any of the pending instructions are ready to issue.  If
836     // so, add them to the available queue.
837     unsigned MinDepth = ~0u;
838     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
839       if (PendingQueue[i]->getDepth() <= CurCycle) {
840         AvailableQueue.push(PendingQueue[i]);
841         PendingQueue[i]->isAvailable = true;
842         PendingQueue[i] = PendingQueue.back();
843         PendingQueue.pop_back();
844         --i; --e;
845       } else if (PendingQueue[i]->getDepth() < MinDepth)
846         MinDepth = PendingQueue[i]->getDepth();
847     }
848
849     DEBUG(errs() << "\n*** Examining Available\n";
850           LatencyPriorityQueue q = AvailableQueue;
851           while (!q.empty()) {
852             SUnit *su = q.pop();
853             errs() << "Height " << su->getHeight() << ": ";
854             su->dump(this);
855           });
856
857     SUnit *FoundSUnit = 0;
858
859     bool HasNoopHazards = false;
860     while (!AvailableQueue.empty()) {
861       SUnit *CurSUnit = AvailableQueue.pop();
862
863       ScheduleHazardRecognizer::HazardType HT =
864         HazardRec->getHazardType(CurSUnit);
865       if (HT == ScheduleHazardRecognizer::NoHazard) {
866         FoundSUnit = CurSUnit;
867         break;
868       }
869
870       // Remember if this is a noop hazard.
871       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
872
873       NotReady.push_back(CurSUnit);
874     }
875
876     // Add the nodes that aren't ready back onto the available list.
877     if (!NotReady.empty()) {
878       AvailableQueue.push_all(NotReady);
879       NotReady.clear();
880     }
881
882     // If we found a node to schedule, do it now.
883     if (FoundSUnit) {
884       ScheduleNodeTopDown(FoundSUnit, CurCycle);
885       HazardRec->EmitInstruction(FoundSUnit);
886       CycleInstCnt++;
887
888       // If we are using the target-specific hazards, then don't
889       // advance the cycle time just because we schedule a node. If
890       // the target allows it we can schedule multiple nodes in the
891       // same cycle.
892       if (!EnablePostRAHazardAvoidance) {
893         if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
894           ++CurCycle;
895       }
896     } else {
897       if (CycleInstCnt > 0) {
898         DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
899         HazardRec->AdvanceCycle();
900       } else if (!HasNoopHazards) {
901         // Otherwise, we have a pipeline stall, but no other problem,
902         // just advance the current cycle and try again.
903         DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
904         HazardRec->AdvanceCycle();
905         ++NumStalls;
906       } else {
907         // Otherwise, we have no instructions to issue and we have instructions
908         // that will fault if we don't do this right.  This is the case for
909         // processors without pipeline interlocks and other cases.
910         DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
911         HazardRec->EmitNoop();
912         Sequence.push_back(0);   // NULL here means noop
913         ++NumNoops;
914       }
915
916       ++CurCycle;
917       CycleInstCnt = 0;
918     }
919   }
920
921 #ifndef NDEBUG
922   VerifySchedule(/*isBottomUp=*/false);
923 #endif
924 }
925
926 //===----------------------------------------------------------------------===//
927 //                         Public Constructor Functions
928 //===----------------------------------------------------------------------===//
929
930 FunctionPass *llvm::createPostRAScheduler() {
931   return new PostRAScheduler();
932 }