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