LLVM API Documentation

PostRASchedulerList.cpp

Go to the documentation of this file.
00001 //===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements a top-down list scheduler, using standard algorithms.
00011 // The basic approach uses a priority queue of available nodes to schedule.
00012 // One at a time, nodes are taken from the priority queue (thus in priority
00013 // order), checked for legality to schedule, and emitted if legal.
00014 //
00015 // Nodes may not be legal to schedule either due to structural hazards (e.g.
00016 // pipeline or resource constraints) or because an input to the instruction has
00017 // not completed execution.
00018 //
00019 //===----------------------------------------------------------------------===//
00020 
00021 #define DEBUG_TYPE "post-RA-sched"
00022 #include "llvm/CodeGen/Passes.h"
00023 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
00024 #include "llvm/CodeGen/LatencyPriorityQueue.h"
00025 #include "llvm/CodeGen/SchedulerRegistry.h"
00026 #include "llvm/CodeGen/MachineDominators.h"
00027 #include "llvm/CodeGen/MachineFunctionPass.h"
00028 #include "llvm/CodeGen/MachineLoopInfo.h"
00029 #include "llvm/CodeGen/MachineRegisterInfo.h"
00030 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
00031 #include "llvm/Target/TargetMachine.h"
00032 #include "llvm/Target/TargetInstrInfo.h"
00033 #include "llvm/Target/TargetRegisterInfo.h"
00034 #include "llvm/Support/Compiler.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/ADT/Statistic.h"
00037 #include <map>
00038 using namespace llvm;
00039 
00040 STATISTIC(NumNoops, "Number of noops inserted");
00041 STATISTIC(NumStalls, "Number of pipeline stalls");
00042 
00043 static cl::opt<bool>
00044 EnableAntiDepBreaking("break-anti-dependencies",
00045                       cl::desc("Break post-RA scheduling anti-dependencies"),
00046                       cl::init(true), cl::Hidden);
00047 
00048 static cl::opt<bool>
00049 EnablePostRAHazardAvoidance("avoid-hazards",
00050                       cl::desc("Enable simple hazard-avoidance"),
00051                       cl::init(true), cl::Hidden);
00052 
00053 namespace {
00054   class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
00055   public:
00056     static char ID;
00057     PostRAScheduler() : MachineFunctionPass(&ID) {}
00058 
00059     void getAnalysisUsage(AnalysisUsage &AU) const {
00060       AU.addRequired<MachineDominatorTree>();
00061       AU.addPreserved<MachineDominatorTree>();
00062       AU.addRequired<MachineLoopInfo>();
00063       AU.addPreserved<MachineLoopInfo>();
00064       MachineFunctionPass::getAnalysisUsage(AU);
00065     }
00066 
00067     const char *getPassName() const {
00068       return "Post RA top-down list latency scheduler";
00069     }
00070 
00071     bool runOnMachineFunction(MachineFunction &Fn);
00072   };
00073   char PostRAScheduler::ID = 0;
00074 
00075   class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
00076     /// AvailableQueue - The priority queue to use for the available SUnits.
00077     ///
00078     LatencyPriorityQueue AvailableQueue;
00079   
00080     /// PendingQueue - This contains all of the instructions whose operands have
00081     /// been issued, but their results are not ready yet (due to the latency of
00082     /// the operation).  Once the operands becomes available, the instruction is
00083     /// added to the AvailableQueue.
00084     std::vector<SUnit*> PendingQueue;
00085 
00086     /// Topo - A topological ordering for SUnits.
00087     ScheduleDAGTopologicalSort Topo;
00088 
00089     /// AllocatableSet - The set of allocatable registers.
00090     /// We'll be ignoring anti-dependencies on non-allocatable registers,
00091     /// because they may not be safe to break.
00092     const BitVector AllocatableSet;
00093 
00094     /// HazardRec - The hazard recognizer to use.
00095     ScheduleHazardRecognizer *HazardRec;
00096 
00097   public:
00098     SchedulePostRATDList(MachineFunction &MF,
00099                          const MachineLoopInfo &MLI,
00100                          const MachineDominatorTree &MDT,
00101                          ScheduleHazardRecognizer *HR)
00102       : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
00103         AllocatableSet(TRI->getAllocatableSet(MF)),
00104         HazardRec(HR) {}
00105 
00106     ~SchedulePostRATDList() {
00107       delete HazardRec;
00108     }
00109 
00110     void Schedule();
00111 
00112   private:
00113     void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
00114     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
00115     void ListScheduleTopDown();
00116     bool BreakAntiDependencies();
00117   };
00118 
00119   /// SimpleHazardRecognizer - A *very* simple hazard recognizer. It uses
00120   /// a coarse classification and attempts to avoid that instructions of
00121   /// a given class aren't grouped too densely together.
00122   class SimpleHazardRecognizer : public ScheduleHazardRecognizer {
00123     /// Class - A simple classification for SUnits.
00124     enum Class {
00125       Other, Load, Store
00126     };
00127 
00128     /// Window - The Class values of the most recently issued
00129     /// instructions.
00130     Class Window[8];
00131 
00132     /// getClass - Classify the given SUnit.
00133     Class getClass(const SUnit *SU) {
00134       const MachineInstr *MI = SU->getInstr();
00135       const TargetInstrDesc &TID = MI->getDesc();
00136       if (TID.mayLoad())
00137         return Load;
00138       if (TID.mayStore())
00139         return Store;
00140       return Other;
00141     }
00142 
00143     /// Step - Rotate the existing entries in Window and insert the
00144     /// given class value in position as the most recent.
00145     void Step(Class C) {
00146       std::copy(Window+1, array_endof(Window), Window);
00147       Window[array_lengthof(Window)-1] = C;
00148     }
00149 
00150   public:
00151     SimpleHazardRecognizer() : Window() {}
00152 
00153     virtual HazardType getHazardType(SUnit *SU) {
00154       Class C = getClass(SU);
00155       if (C == Other)
00156         return NoHazard;
00157       unsigned Score = 0;
00158       for (unsigned i = 0; i != array_lengthof(Window); ++i)
00159         if (Window[i] == C)
00160           Score += i + 1;
00161       if (Score > array_lengthof(Window) * 2)
00162         return Hazard;
00163       return NoHazard;
00164     }
00165 
00166     virtual void EmitInstruction(SUnit *SU) {
00167       Step(getClass(SU));
00168     }
00169 
00170     virtual void AdvanceCycle() {
00171       Step(Other);
00172     }
00173   };
00174 }
00175 
00176 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
00177   DOUT << "PostRAScheduler\n";
00178 
00179   const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
00180   const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
00181   ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
00182                                  new SimpleHazardRecognizer :
00183                                  new ScheduleHazardRecognizer();
00184 
00185   SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
00186 
00187   // Loop over all of the basic blocks
00188   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
00189        MBB != MBBe; ++MBB) {
00190     // Schedule each sequence of instructions not interrupted by a label
00191     // or anything else that effectively needs to shut down scheduling.
00192     MachineBasicBlock::iterator Current = MBB->begin(), End = MBB->end();
00193     for (MachineBasicBlock::iterator MI = Current; MI != End; ++MI)
00194       if (MI->getDesc().isTerminator() || MI->isLabel()) {
00195         Scheduler.Run(0, MBB, Current, MI);
00196         Scheduler.EmitSchedule();
00197         Current = next(MI);
00198       }
00199 
00200     Scheduler.Run(0, MBB, Current, End);
00201     Scheduler.EmitSchedule();
00202   }
00203 
00204   return true;
00205 }
00206   
00207 /// Schedule - Schedule the DAG using list scheduling.
00208 void SchedulePostRATDList::Schedule() {
00209   DOUT << "********** List Scheduling **********\n";
00210   
00211   // Build the scheduling graph.
00212   BuildSchedGraph();
00213 
00214   if (EnableAntiDepBreaking) {
00215     if (BreakAntiDependencies()) {
00216       // We made changes. Update the dependency graph.
00217       // Theoretically we could update the graph in place:
00218       // When a live range is changed to use a different register, remove
00219       // the def's anti-dependence *and* output-dependence edges due to
00220       // that register, and add new anti-dependence and output-dependence
00221       // edges based on the next live range of the register.
00222       SUnits.clear();
00223       BuildSchedGraph();
00224     }
00225   }
00226 
00227   AvailableQueue.initNodes(SUnits);
00228 
00229   ListScheduleTopDown();
00230   
00231   AvailableQueue.releaseState();
00232 }
00233 
00234 /// getInstrOperandRegClass - Return register class of the operand of an
00235 /// instruction of the specified TargetInstrDesc.
00236 static const TargetRegisterClass*
00237 getInstrOperandRegClass(const TargetRegisterInfo *TRI,
00238                         const TargetInstrInfo *TII, const TargetInstrDesc &II,
00239                         unsigned Op) {
00240   if (Op >= II.getNumOperands())
00241     return NULL;
00242   if (II.OpInfo[Op].isLookupPtrRegClass())
00243     return TII->getPointerRegClass();
00244   return TRI->getRegClass(II.OpInfo[Op].RegClass);
00245 }
00246 
00247 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
00248 /// critical path.
00249 static SDep *CriticalPathStep(SUnit *SU) {
00250   SDep *Next = 0;
00251   unsigned NextDepth = 0;
00252   // Find the predecessor edge with the greatest depth.
00253   for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
00254        P != PE; ++P) {
00255     SUnit *PredSU = P->getSUnit();
00256     unsigned PredLatency = P->getLatency();
00257     unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
00258     // In the case of a latency tie, prefer an anti-dependency edge over
00259     // other types of edges.
00260     if (NextDepth < PredTotalLatency ||
00261         (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
00262       NextDepth = PredTotalLatency;
00263       Next = &*P;
00264     }
00265   }
00266   return Next;
00267 }
00268 
00269 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
00270 /// of the ScheduleDAG and break them by renaming registers.
00271 ///
00272 bool SchedulePostRATDList::BreakAntiDependencies() {
00273   // The code below assumes that there is at least one instruction,
00274   // so just duck out immediately if the block is empty.
00275   if (SUnits.empty()) return false;
00276 
00277   // Find the node at the bottom of the critical path.
00278   SUnit *Max = 0;
00279   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
00280     SUnit *SU = &SUnits[i];
00281     if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
00282       Max = SU;
00283   }
00284 
00285   DOUT << "Critical path has total latency "
00286        << (Max->getDepth() + Max->Latency) << "\n";
00287 
00288   // Track progress along the critical path through the SUnit graph as we walk
00289   // the instructions.
00290   SUnit *CriticalPathSU = Max;
00291   MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
00292 
00293   // For live regs that are only used in one register class in a live range,
00294   // the register class. If the register is not live, the corresponding value
00295   // is null. If the register is live but used in multiple register classes,
00296   // the corresponding value is -1 casted to a pointer.
00297   const TargetRegisterClass *
00298     Classes[TargetRegisterInfo::FirstVirtualRegister] = {};
00299 
00300   // Map registers to all their references within a live range.
00301   std::multimap<unsigned, MachineOperand *> RegRefs;
00302 
00303   // The index of the most recent kill (proceding bottom-up), or ~0u if
00304   // the register is not live.
00305   unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
00306   std::fill(KillIndices, array_endof(KillIndices), ~0u);
00307   // The index of the most recent complete def (proceding bottom up), or ~0u if
00308   // the register is live.
00309   unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
00310   std::fill(DefIndices, array_endof(DefIndices), BB->size());
00311 
00312   // Determine the live-out physregs for this block.
00313   if (BB->back().getDesc().isReturn())
00314     // In a return block, examine the function live-out regs.
00315     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
00316          E = MRI.liveout_end(); I != E; ++I) {
00317       unsigned Reg = *I;
00318       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00319       KillIndices[Reg] = BB->size();
00320       DefIndices[Reg] = ~0u;
00321       // Repeat, for all aliases.
00322       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
00323         unsigned AliasReg = *Alias;
00324         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
00325         KillIndices[AliasReg] = BB->size();
00326         DefIndices[AliasReg] = ~0u;
00327       }
00328     }
00329   else
00330     // In a non-return block, examine the live-in regs of all successors.
00331     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
00332          SE = BB->succ_end(); SI != SE; ++SI) 
00333       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
00334            E = (*SI)->livein_end(); I != E; ++I) {
00335         unsigned Reg = *I;
00336         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00337         KillIndices[Reg] = BB->size();
00338         DefIndices[Reg] = ~0u;
00339         // Repeat, for all aliases.
00340         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
00341           unsigned AliasReg = *Alias;
00342           Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
00343           KillIndices[AliasReg] = BB->size();
00344           DefIndices[AliasReg] = ~0u;
00345         }
00346       }
00347 
00348   // Consider callee-saved registers as live-out, since we're running after
00349   // prologue/epilogue insertion so there's no way to add additional
00350   // saved registers.
00351   //
00352   // TODO: If the callee saves and restores these, then we can potentially
00353   // use them between the save and the restore. To do that, we could scan
00354   // the exit blocks to see which of these registers are defined.
00355   // Alternatively, callee-saved registers that aren't saved and restored
00356   // could be marked live-in in every block.
00357   for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
00358     unsigned Reg = *I;
00359     Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00360     KillIndices[Reg] = BB->size();
00361     DefIndices[Reg] = ~0u;
00362     // Repeat, for all aliases.
00363     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
00364       unsigned AliasReg = *Alias;
00365       Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
00366       KillIndices[AliasReg] = BB->size();
00367       DefIndices[AliasReg] = ~0u;
00368     }
00369   }
00370 
00371   // Consider this pattern:
00372   //   A = ...
00373   //   ... = A
00374   //   A = ...
00375   //   ... = A
00376   //   A = ...
00377   //   ... = A
00378   //   A = ...
00379   //   ... = A
00380   // There are three anti-dependencies here, and without special care,
00381   // we'd break all of them using the same register:
00382   //   A = ...
00383   //   ... = A
00384   //   B = ...
00385   //   ... = B
00386   //   B = ...
00387   //   ... = B
00388   //   B = ...
00389   //   ... = B
00390   // because at each anti-dependence, B is the first register that
00391   // isn't A which is free.  This re-introduces anti-dependencies
00392   // at all but one of the original anti-dependencies that we were
00393   // trying to break.  To avoid this, keep track of the most recent
00394   // register that each register was replaced with, avoid avoid
00395   // using it to repair an anti-dependence on the same register.
00396   // This lets us produce this:
00397   //   A = ...
00398   //   ... = A
00399   //   B = ...
00400   //   ... = B
00401   //   C = ...
00402   //   ... = C
00403   //   B = ...
00404   //   ... = B
00405   // This still has an anti-dependence on B, but at least it isn't on the
00406   // original critical path.
00407   //
00408   // TODO: If we tracked more than one register here, we could potentially
00409   // fix that remaining critical edge too. This is a little more involved,
00410   // because unlike the most recent register, less recent registers should
00411   // still be considered, though only if no other registers are available.
00412   unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
00413 
00414   // Attempt to break anti-dependence edges on the critical path. Walk the
00415   // instructions from the bottom up, tracking information about liveness
00416   // as we go to help determine which registers are available.
00417   bool Changed = false;
00418   unsigned Count = BB->size() - 1;
00419   for (MachineBasicBlock::reverse_iterator I = BB->rbegin(), E = BB->rend();
00420        I != E; ++I, --Count) {
00421     MachineInstr *MI = &*I;
00422 
00423     // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
00424     // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
00425     // is left behind appearing to clobber the super-register, while the
00426     // subregister needs to remain live. So we just ignore them.
00427     if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
00428       continue;
00429 
00430     // Check if this instruction has a dependence on the critical path that
00431     // is an anti-dependence that we may be able to break. If it is, set
00432     // AntiDepReg to the non-zero register associated with the anti-dependence.
00433     //
00434     // We limit our attention to the critical path as a heuristic to avoid
00435     // breaking anti-dependence edges that aren't going to significantly
00436     // impact the overall schedule. There are a limited number of registers
00437     // and we want to save them for the important edges.
00438     // 
00439     // TODO: Instructions with multiple defs could have multiple
00440     // anti-dependencies. The current code here only knows how to break one
00441     // edge per instruction. Note that we'd have to be able to break all of
00442     // the anti-dependencies in an instruction in order to be effective.
00443     unsigned AntiDepReg = 0;
00444     if (MI == CriticalPathMI) {
00445       if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
00446         SUnit *NextSU = Edge->getSUnit();
00447 
00448         // Only consider anti-dependence edges.
00449         if (Edge->getKind() == SDep::Anti) {
00450           AntiDepReg = Edge->getReg();
00451           assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
00452           // Don't break anti-dependencies on non-allocatable registers.
00453           if (!AllocatableSet.test(AntiDepReg))
00454             AntiDepReg = 0;
00455           else {
00456             // If the SUnit has other dependencies on the SUnit that it
00457             // anti-depends on, don't bother breaking the anti-dependency
00458             // since those edges would prevent such units from being
00459             // scheduled past each other regardless.
00460             //
00461             // Also, if there are dependencies on other SUnits with the
00462             // same register as the anti-dependency, don't attempt to
00463             // break it.
00464             for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
00465                  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
00466               if (P->getSUnit() == NextSU ?
00467                     (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
00468                     (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
00469                 AntiDepReg = 0;
00470                 break;
00471               }
00472           }
00473         }
00474         CriticalPathSU = NextSU;
00475         CriticalPathMI = CriticalPathSU->getInstr();
00476       } else {
00477         // We've reached the end of the critical path.
00478         CriticalPathSU = 0;
00479         CriticalPathMI = 0;
00480       }
00481     }
00482 
00483     // Scan the register operands for this instruction and update
00484     // Classes and RegRefs.
00485     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00486       MachineOperand &MO = MI->getOperand(i);
00487       if (!MO.isReg()) continue;
00488       unsigned Reg = MO.getReg();
00489       if (Reg == 0) continue;
00490       const TargetRegisterClass *NewRC =
00491         getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
00492 
00493       // If this instruction has a use of AntiDepReg, breaking it
00494       // is invalid.
00495       if (MO.isUse() && AntiDepReg == Reg)
00496         AntiDepReg = 0;
00497 
00498       // For now, only allow the register to be changed if its register
00499       // class is consistent across all uses.
00500       if (!Classes[Reg] && NewRC)
00501         Classes[Reg] = NewRC;
00502       else if (!NewRC || Classes[Reg] != NewRC)
00503         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00504 
00505       // Now check for aliases.
00506       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
00507         // If an alias of the reg is used during the live range, give up.
00508         // Note that this allows us to skip checking if AntiDepReg
00509         // overlaps with any of the aliases, among other things.
00510         unsigned AliasReg = *Alias;
00511         if (Classes[AliasReg]) {
00512           Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
00513           Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00514         }
00515       }
00516 
00517       // If we're still willing to consider this register, note the reference.
00518       if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
00519         RegRefs.insert(std::make_pair(Reg, &MO));
00520     }
00521 
00522     // Determine AntiDepReg's register class, if it is live and is
00523     // consistently used within a single class.
00524     const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
00525     assert((AntiDepReg == 0 || RC != NULL) &&
00526            "Register should be live if it's causing an anti-dependence!");
00527     if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
00528       AntiDepReg = 0;
00529 
00530     // Look for a suitable register to use to break the anti-depenence.
00531     //
00532     // TODO: Instead of picking the first free register, consider which might
00533     // be the best.
00534     if (AntiDepReg != 0) {
00535       for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
00536            RE = RC->allocation_order_end(MF); R != RE; ++R) {
00537         unsigned NewReg = *R;
00538         // Don't replace a register with itself.
00539         if (NewReg == AntiDepReg) continue;
00540         // Don't replace a register with one that was recently used to repair
00541         // an anti-dependence with this AntiDepReg, because that would
00542         // re-introduce that anti-dependence.
00543         if (NewReg == LastNewReg[AntiDepReg]) continue;
00544         // If NewReg is dead and NewReg's most recent def is not before
00545         // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
00546         assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
00547                "Kill and Def maps aren't consistent for AntiDepReg!");
00548         assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
00549                "Kill and Def maps aren't consistent for NewReg!");
00550         if (KillIndices[NewReg] == ~0u &&
00551             Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
00552             KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
00553           DOUT << "Breaking anti-dependence edge on "
00554                << TRI->getName(AntiDepReg)
00555                << " with " << RegRefs.count(AntiDepReg) << " references"
00556                << " using " << TRI->getName(NewReg) << "!\n";
00557 
00558           // Update the references to the old register to refer to the new
00559           // register.
00560           std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
00561                     std::multimap<unsigned, MachineOperand *>::iterator>
00562              Range = RegRefs.equal_range(AntiDepReg);
00563           for (std::multimap<unsigned, MachineOperand *>::iterator
00564                Q = Range.first, QE = Range.second; Q != QE; ++Q)
00565             Q->second->setReg(NewReg);
00566 
00567           // We just went back in time and modified history; the
00568           // liveness information for the anti-depenence reg is now
00569           // inconsistent. Set the state as if it were dead.
00570           Classes[NewReg] = Classes[AntiDepReg];
00571           DefIndices[NewReg] = DefIndices[AntiDepReg];
00572           KillIndices[NewReg] = KillIndices[AntiDepReg];
00573 
00574           Classes[AntiDepReg] = 0;
00575           DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
00576           KillIndices[AntiDepReg] = ~0u;
00577 
00578           RegRefs.erase(AntiDepReg);
00579           Changed = true;
00580           LastNewReg[AntiDepReg] = NewReg;
00581           break;
00582         }
00583       }
00584     }
00585 
00586     // Update liveness.
00587     // Proceding upwards, registers that are defed but not used in this
00588     // instruction are now dead.
00589     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00590       MachineOperand &MO = MI->getOperand(i);
00591       if (!MO.isReg()) continue;
00592       unsigned Reg = MO.getReg();
00593       if (Reg == 0) continue;
00594       if (!MO.isDef()) continue;
00595       // Ignore two-addr defs.
00596       if (MI->isRegReDefinedByTwoAddr(i)) continue;
00597 
00598       DefIndices[Reg] = Count;
00599       KillIndices[Reg] = ~0u;
00600       Classes[Reg] = 0;
00601       RegRefs.erase(Reg);
00602       // Repeat, for all subregs.
00603       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
00604            *Subreg; ++Subreg) {
00605         unsigned SubregReg = *Subreg;
00606         DefIndices[SubregReg] = Count;
00607         KillIndices[SubregReg] = ~0u;
00608         Classes[SubregReg] = 0;
00609         RegRefs.erase(SubregReg);
00610       }
00611       // Conservatively mark super-registers as unusable.
00612       for (const unsigned *Super = TRI->getSuperRegisters(Reg);
00613            *Super; ++Super) {
00614         unsigned SuperReg = *Super;
00615         Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
00616       }
00617     }
00618     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00619       MachineOperand &MO = MI->getOperand(i);
00620       if (!MO.isReg()) continue;
00621       unsigned Reg = MO.getReg();
00622       if (Reg == 0) continue;
00623       if (!MO.isUse()) continue;
00624 
00625       const TargetRegisterClass *NewRC =
00626         getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
00627 
00628       // For now, only allow the register to be changed if its register
00629       // class is consistent across all uses.
00630       if (!Classes[Reg] && NewRC)
00631         Classes[Reg] = NewRC;
00632       else if (!NewRC || Classes[Reg] != NewRC)
00633         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
00634 
00635       RegRefs.insert(std::make_pair(Reg, &MO));
00636 
00637       // It wasn't previously live but now it is, this is a kill.
00638       if (KillIndices[Reg] == ~0u) {
00639         KillIndices[Reg] = Count;
00640         DefIndices[Reg] = ~0u;
00641       }
00642       // Repeat, for all aliases.
00643       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
00644         unsigned AliasReg = *Alias;
00645         if (KillIndices[AliasReg] == ~0u) {
00646           KillIndices[AliasReg] = Count;
00647           DefIndices[AliasReg] = ~0u;
00648         }
00649       }
00650     }
00651   }
00652   assert(Count == ~0u && "Count mismatch!");
00653 
00654   return Changed;
00655 }
00656 
00657 //===----------------------------------------------------------------------===//
00658 //  Top-Down Scheduling
00659 //===----------------------------------------------------------------------===//
00660 
00661 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
00662 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
00663 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
00664   SUnit *SuccSU = SuccEdge->getSUnit();
00665   --SuccSU->NumPredsLeft;
00666   
00667 #ifndef NDEBUG
00668   if (SuccSU->NumPredsLeft < 0) {
00669     cerr << "*** Scheduling failed! ***\n";
00670     SuccSU->dump(this);
00671     cerr << " has been released too many times!\n";
00672     assert(0);
00673   }
00674 #endif
00675   
00676   // Compute how many cycles it will be before this actually becomes
00677   // available.  This is the max of the start time of all predecessors plus
00678   // their latencies.
00679   SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
00680   
00681   if (SuccSU->NumPredsLeft == 0) {
00682     PendingQueue.push_back(SuccSU);
00683   }
00684 }
00685 
00686 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
00687 /// count of its successors. If a successor pending count is zero, add it to
00688 /// the Available queue.
00689 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
00690   DOUT << "*** Scheduling [" << CurCycle << "]: ";
00691   DEBUG(SU->dump(this));
00692   
00693   Sequence.push_back(SU);
00694   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
00695   SU->setDepthToAtLeast(CurCycle);
00696 
00697   // Top down: release successors.
00698   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
00699        I != E; ++I)
00700     ReleaseSucc(SU, &*I);
00701 
00702   SU->isScheduled = true;
00703   AvailableQueue.ScheduledNode(SU);
00704 }
00705 
00706 /// ListScheduleTopDown - The main loop of list scheduling for top-down
00707 /// schedulers.
00708 void SchedulePostRATDList::ListScheduleTopDown() {
00709   unsigned CurCycle = 0;
00710 
00711   // All leaves to Available queue.
00712   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
00713     // It is available if it has no predecessors.
00714     if (SUnits[i].Preds.empty()) {
00715       AvailableQueue.push(&SUnits[i]);
00716       SUnits[i].isAvailable = true;
00717     }
00718   }
00719   
00720   // While Available queue is not empty, grab the node with the highest
00721   // priority. If it is not ready put it back.  Schedule the node.
00722   std::vector<SUnit*> NotReady;
00723   Sequence.reserve(SUnits.size());
00724   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
00725     // Check to see if any of the pending instructions are ready to issue.  If
00726     // so, add them to the available queue.
00727     unsigned MinDepth = ~0u;
00728     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
00729       if (PendingQueue[i]->getDepth() <= CurCycle) {
00730         AvailableQueue.push(PendingQueue[i]);
00731         PendingQueue[i]->isAvailable = true;
00732         PendingQueue[i] = PendingQueue.back();
00733         PendingQueue.pop_back();
00734         --i; --e;
00735       } else if (PendingQueue[i]->getDepth() < MinDepth)
00736         MinDepth = PendingQueue[i]->getDepth();
00737     }
00738     
00739     // If there are no instructions available, don't try to issue anything, and
00740     // don't advance the hazard recognizer.
00741     if (AvailableQueue.empty()) {
00742       CurCycle = MinDepth != ~0u ? MinDepth : CurCycle + 1;
00743       continue;
00744     }
00745 
00746     SUnit *FoundSUnit = 0;
00747 
00748     bool HasNoopHazards = false;
00749     while (!AvailableQueue.empty()) {
00750       SUnit *CurSUnit = AvailableQueue.pop();
00751 
00752       ScheduleHazardRecognizer::HazardType HT =
00753         HazardRec->getHazardType(CurSUnit);
00754       if (HT == ScheduleHazardRecognizer::NoHazard) {
00755         FoundSUnit = CurSUnit;
00756         break;
00757       }
00758 
00759       // Remember if this is a noop hazard.
00760       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
00761 
00762       NotReady.push_back(CurSUnit);
00763     }
00764 
00765     // Add the nodes that aren't ready back onto the available list.
00766     if (!NotReady.empty()) {
00767       AvailableQueue.push_all(NotReady);
00768       NotReady.clear();
00769     }
00770 
00771     // If we found a node to schedule, do it now.
00772     if (FoundSUnit) {
00773       ScheduleNodeTopDown(FoundSUnit, CurCycle);
00774       HazardRec->EmitInstruction(FoundSUnit);
00775 
00776       // If this is a pseudo-op node, we don't want to increment the current
00777       // cycle.
00778       if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
00779         ++CurCycle;
00780     } else if (!HasNoopHazards) {
00781       // Otherwise, we have a pipeline stall, but no other problem, just advance
00782       // the current cycle and try again.
00783       DOUT << "*** Advancing cycle, no work to do\n";
00784       HazardRec->AdvanceCycle();
00785       ++NumStalls;
00786       ++CurCycle;
00787     } else {
00788       // Otherwise, we have no instructions to issue and we have instructions
00789       // that will fault if we don't do this right.  This is the case for
00790       // processors without pipeline interlocks and other cases.
00791       DOUT << "*** Emitting noop\n";
00792       HazardRec->EmitNoop();
00793       Sequence.push_back(0);   // NULL here means noop
00794       ++NumNoops;
00795       ++CurCycle;
00796     }
00797   }
00798 
00799 #ifndef NDEBUG
00800   VerifySchedule(/*isBottomUp=*/false);
00801 #endif
00802 }
00803 
00804 //===----------------------------------------------------------------------===//
00805 //                         Public Constructor Functions
00806 //===----------------------------------------------------------------------===//
00807 
00808 FunctionPass *llvm::createPostRAScheduler() {
00809   return new PostRAScheduler();
00810 }