Rename ConstantSDNode::getValue to getZExtValue, for consistency
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGList.cpp
index 9e23a8cc7fb180fafc298363e9a114169ec8dd90..4b09b7c26310571ca871182c6e960f6dfa532642 100644 (file)
 //
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by Evan Cheng and is distributed under the
-// University of Illinois Open Source License. See LICENSE.TXT for details.
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
 //
-// This implements a simple two pass scheduler.  The first pass attempts to push
-// backward any lengthy instructions and critical paths.  The second pass packs
-// instructions into semi-optimal time slots.
+// This implements a top-down list scheduler, using standard algorithms.
+// The basic approach uses a priority queue of available nodes to schedule.
+// One at a time, nodes are taken from the priority queue (thus in priority
+// order), checked for legality to schedule, and emitted if legal.
+//
+// Nodes may not be legal to schedule either due to structural hazards (e.g.
+// pipeline or resource constraints) or because an input to the instruction has
+// not completed execution.
 //
 //===----------------------------------------------------------------------===//
 
-#define DEBUG_TYPE "sched"
+#define DEBUG_TYPE "pre-RA-sched"
 #include "llvm/CodeGen/ScheduleDAG.h"
-#include "llvm/CodeGen/SelectionDAG.h"
+#include "llvm/CodeGen/SchedulerRegistry.h"
+#include "llvm/CodeGen/SelectionDAGISel.h"
+#include "llvm/Target/TargetRegisterInfo.h"
+#include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/ADT/PriorityQueue.h"
+#include "llvm/ADT/Statistic.h"
 #include <climits>
-#include <iostream>
-#include <memory>
-#include <queue>
 using namespace llvm;
 
-namespace {
-
-/// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or a
-/// group of nodes flagged together.
-struct SUnit {
-  SDNode *Node;                       // Representative node.
-  std::vector<SDNode*> FlaggedNodes;  // All nodes flagged to Node.
-  std::vector<SDNode*> Preds;         // All real predecessors.
-  std::vector<SDNode*> ChainPreds;    // All chain predecessors.
-  std::vector<SDNode*> Succs;         // All real successors.
-  std::vector<SDNode*> ChainSuccs;    // All chain successors.
-  int NumPredsLeft;                   // # of preds not scheduled.
-  int NumSuccsLeft;                   // # of succs not scheduled.
-  int Priority1;                      // Scheduling priority 1.
-  int Priority2;                      // Scheduling priority 2.
-  unsigned Latency;                   // Node latency.
-  unsigned CycleBound;                // Upper/lower cycle to be scheduled at.
-  unsigned Slot;                      // Cycle node is scheduled at.
-
-  SUnit(SDNode *node)
-    : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
-      Priority1(INT_MIN), Priority2(INT_MIN), Latency(0),
-      CycleBound(0), Slot(0) {}
-
-  void dump(const SelectionDAG *G, bool All=true) const;
-};
-
-void SUnit::dump(const SelectionDAG *G, bool All) const {
-  std::cerr << "SU:  ";
-  Node->dump(G);
-  std::cerr << "\n";
-  if (All) {
-    std::cerr << "# preds left  : " << NumPredsLeft << "\n";
-    std::cerr << "# succs left  : " << NumSuccsLeft << "\n";
-    std::cerr << "Latency       : " << Latency << "\n";
-    std::cerr << "Priority      : " << Priority1 << " , " << Priority2 << "\n";
-  }
-
-  if (FlaggedNodes.size() != 0) {
-    if (All)
-      std::cerr << "Flagged nodes :\n";
-    for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
-      std::cerr << "     ";
-      FlaggedNodes[i]->dump(G);
-      std::cerr << "\n";
-    }
-  }
+STATISTIC(NumNoops , "Number of noops inserted");
+STATISTIC(NumStalls, "Number of pipeline stalls");
 
-  if (All) {
-    if (Preds.size() != 0) {
-      std::cerr << "Predecessors  :\n";
-      for (unsigned i = 0, e = Preds.size(); i != e; i++) {
-        std::cerr << "    ";
-        Preds[i]->dump(G);
-        std::cerr << "\n";
-      }
-    }
-    if (ChainPreds.size() != 0) {
-      std::cerr << "Chained Preds :\n";
-      for (unsigned i = 0, e = ChainPreds.size(); i != e; i++) {
-        std::cerr << "    ";
-        ChainPreds[i]->dump(G);
-        std::cerr << "\n";
-      }
-    }
-    if (Succs.size() != 0) {
-      std::cerr << "Successors    :\n";
-      for (unsigned i = 0, e = Succs.size(); i != e; i++) {
-        std::cerr << "    ";
-        Succs[i]->dump(G);
-        std::cerr << "\n";
-      }
-    }
-    if (ChainSuccs.size() != 0) {
-      std::cerr << "Chained succs :\n";
-      for (unsigned i = 0, e = ChainSuccs.size(); i != e; i++) {
-        std::cerr << "    ";
-        ChainSuccs[i]->dump(G);
-        std::cerr << "\n";
-      }
-    }
-  }
-}
-
-/// Sorting functions for the Available queue.
-struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
-  bool operator()(const SUnit* left, const SUnit* right) const {
-    if (left->Priority1 > right->Priority1) {
-      return true;
-    } else if (left->Priority1 == right->Priority1) {
-      unsigned lf = left->FlaggedNodes.size();
-      unsigned rf = right->FlaggedNodes.size();
-      if (lf > rf)
-        return true;
-      else if (lf == rf) {
-        if (left->Priority2 > right->Priority2)
-          return true;
-        else if (left->Priority2 == right->Priority2) {
-          if (left->CycleBound > right->CycleBound) 
-            return true;
-          else
-            return left->Node->getNodeDepth() < right->Node->getNodeDepth();
-        }
-      }
-    }
-
-    return false;
-  }
-};
-
-/// ScheduleDAGList - List scheduler.
-class ScheduleDAGList : public ScheduleDAG {
+static RegisterScheduler
+  tdListDAGScheduler("list-td", "  Top-down list scheduler",
+                     createTDListDAGScheduler);
+   
+namespace {
+//===----------------------------------------------------------------------===//
+/// ScheduleDAGList - The actual list scheduler implementation.  This supports
+/// top-down scheduling.
+///
+class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAG {
 private:
-  // SDNode to SUnit mapping (many to one).
-  std::map<SDNode*, SUnit*> SUnitMap;
-  // Available queue.
-  std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Available;
-  // The schedule.
-  std::vector<SUnit*> Sequence;
-  // Current scheduling cycle.
-  unsigned CurrCycle;
+  /// AvailableQueue - The priority queue to use for the available SUnits.
+  ///
+  SchedulingPriorityQueue *AvailableQueue;
+  
+  /// PendingQueue - This contains all of the instructions whose operands have
+  /// been issued, but their results are not ready yet (due to the latency of
+  /// the operation).  Once the operands becomes available, the instruction is
+  /// added to the AvailableQueue.  This keeps track of each SUnit and the
+  /// number of cycles left to execute before the operation is available.
+  std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
+
+  /// HazardRec - The hazard recognizer to use.
+  HazardRecognizer *HazardRec;
 
 public:
   ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
-                  const TargetMachine &tm)
-    : ScheduleDAG(listSchedulingBURR, dag, bb, tm), CurrCycle(0) {};
+                  const TargetMachine &tm,
+                  SchedulingPriorityQueue *availqueue,
+                  HazardRecognizer *HR)
+    : ScheduleDAG(dag, bb, tm),
+      AvailableQueue(availqueue), HazardRec(HR) {
+    }
 
   ~ScheduleDAGList() {
-    for (std::map<SDNode*, SUnit*>::iterator I = SUnitMap.begin(),
-           E = SUnitMap.end(); I != E; ++I) {
-      SUnit *SU = I->second;
-      // Multiple SDNode* can point to one SUnit. Do ref counting, sort of.
-      if (SU->FlaggedNodes.size() == 0)
-        delete SU;
-      else
-        SU->FlaggedNodes.pop_back();
-    }
+    delete HazardRec;
+    delete AvailableQueue;
   }
 
   void Schedule();
 
-  void dump() const;
-
 private:
-  void ReleasePred(SUnit *PredSU);
-  void ScheduleNode(SUnit *SU);
-  int  CalcNodePriority(SUnit *SU);
-  void CalculatePriorities();
-  void ListSchedule();
-  void BuildSchedUnits();
-  void EmitSchedule();
+  void ReleaseSucc(SUnit *SuccSU, bool isChain);
+  void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
+  void ListScheduleTopDown();
 };
-}  // end namespace
+}  // end anonymous namespace
 
-void ScheduleDAGList::ReleasePred(SUnit *PredSU) {
-  SDNode *PredNode = PredSU->Node;
+HazardRecognizer::~HazardRecognizer() {}
 
-  PredSU->NumSuccsLeft--;
-  if (PredSU->NumSuccsLeft == 0) {
-    // EntryToken has to go last!
-    if (PredNode->getOpcode() != ISD::EntryToken)
-      Available.push(PredSU);
-  } else if (PredSU->NumSuccsLeft < 0) {
-#ifndef NDEBUG
-    std::cerr << "*** List scheduling failed! ***\n";
-    PredSU->dump(&DAG);
-    std::cerr << " has been released too many times!\n";
-    assert(0);
-#endif
-  }
 
-  // FIXME: the distance between two nodes is not always == the predecessor's
-  // latency. For example, the reader can very well read the register written
-  // by the predecessor later than the issue cycle. It also depends on the
-  // interrupt model (drain vs. freeze).
-  PredSU->CycleBound = std::max(PredSU->CycleBound, CurrCycle + PredSU->Latency);
-}
+/// Schedule - Schedule the DAG using list scheduling.
+void ScheduleDAGList::Schedule() {
+  DOUT << "********** List Scheduling **********\n";
+  
+  // Build scheduling units.
+  BuildSchedUnits();
 
-/// ScheduleNode - Add the node to the schedule. Decrement the pending count of
-/// its predecessors. If a predecessor pending count is zero, add it to the
-/// Available queue.
-void ScheduleDAGList::ScheduleNode(SUnit *SU) {
-  Sequence.push_back(SU);
-  SU->Slot = CurrCycle;
+  AvailableQueue->initNodes(SUnits);
+  
+  ListScheduleTopDown();
+  
+  AvailableQueue->releaseState();
+}
 
-  // Bottom up: release predecessors
-  for (unsigned i = 0, e = SU->Preds.size(); i != e; i++) 
-    ReleasePred(SUnitMap[SU->Preds[i]]);
-  for (unsigned i = 0, e = SU->ChainPreds.size(); i != e; i++) 
-    ReleasePred(SUnitMap[SU->ChainPreds[i]]);
+//===----------------------------------------------------------------------===//
+//  Top-Down Scheduling
+//===----------------------------------------------------------------------===//
 
-  CurrCycle++;
+/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
+/// the PendingQueue if the count reaches zero.
+void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
+  SuccSU->NumPredsLeft--;
+  
+  assert(SuccSU->NumPredsLeft >= 0 &&
+         "List scheduling internal error");
+  
+  if (SuccSU->NumPredsLeft == 0) {
+    // Compute how many cycles it will be before this actually becomes
+    // available.  This is the max of the start time of all predecessors plus
+    // their latencies.
+    unsigned AvailableCycle = 0;
+    for (SUnit::pred_iterator I = SuccSU->Preds.begin(),
+         E = SuccSU->Preds.end(); I != E; ++I) {
+      // If this is a token edge, we don't need to wait for the latency of the
+      // preceeding instruction (e.g. a long-latency load) unless there is also
+      // some other data dependence.
+      SUnit &Pred = *I->Dep;
+      unsigned PredDoneCycle = Pred.Cycle;
+      if (!I->isCtrl)
+        PredDoneCycle += Pred.Latency;
+      else if (Pred.Latency)
+        PredDoneCycle += 1;
+
+      AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
+    }
+    
+    PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
+  }
 }
 
-/// isReady - True if node's lower cycle bound is less or equal to the current
-/// scheduling cycle. Always true if all nodes have uniform latency 1.
-static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
-  return SU->CycleBound <= CurrCycle;
+/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
+/// count of its successors. If a successor pending count is zero, add it to
+/// the Available queue.
+void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
+  DOUT << "*** Scheduling [" << CurCycle << "]: ";
+  DEBUG(SU->dump(&DAG));
+  
+  Sequence.push_back(SU);
+  SU->Cycle = CurCycle;
+  
+  // Bottom up: release successors.
+  for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
+       I != E; ++I)
+    ReleaseSucc(I->Dep, I->isCtrl);
 }
 
-/// ListSchedule - The main loop of list scheduling.
-void ScheduleDAGList::ListSchedule() {
-  // Add root to Available queue
-  SUnit *Root = SUnitMap[DAG.getRoot().Val];
-  Available.push(Root);
-
+/// ListScheduleTopDown - The main loop of list scheduling for top-down
+/// schedulers.
+void ScheduleDAGList::ListScheduleTopDown() {
+  unsigned CurCycle = 0;
+
+  // All leaves to Available queue.
+  for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
+    // It is available if it has no predecessors.
+    if (SUnits[i].Preds.empty()) {
+      AvailableQueue->push(&SUnits[i]);
+      SUnits[i].isAvailable = SUnits[i].isPending = true;
+    }
+  }
+  
   // While Available queue is not empty, grab the node with the highest
-  // priority. If it is not ready put it back. Schedule the node.
+  // priority. If it is not ready put it back.  Schedule the node.
   std::vector<SUnit*> NotReady;
-  while (!Available.empty()) {
-    SUnit *CurrNode = Available.top();
-    Available.pop();
-
-    NotReady.clear();
-    while (!isReady(CurrNode, CurrCycle)) {
-      NotReady.push_back(CurrNode);
-      CurrNode = Available.top();
-      Available.pop();
+  Sequence.reserve(SUnits.size());
+  while (!AvailableQueue->empty() || !PendingQueue.empty()) {
+    // Check to see if any of the pending instructions are ready to issue.  If
+    // so, add them to the available queue.
+    for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
+      if (PendingQueue[i].first == CurCycle) {
+        AvailableQueue->push(PendingQueue[i].second);
+        PendingQueue[i].second->isAvailable = true;
+        PendingQueue[i] = PendingQueue.back();
+        PendingQueue.pop_back();
+        --i; --e;
+      } else {
+        assert(PendingQueue[i].first > CurCycle && "Negative latency?");
+      }
+    }
+    
+    // If there are no instructions available, don't try to issue anything, and
+    // don't advance the hazard recognizer.
+    if (AvailableQueue->empty()) {
+      ++CurCycle;
+      continue;
     }
-    for (unsigned i = 0, e = NotReady.size(); i != e; ++i)
-      Available.push(NotReady[i]);
 
-    DEBUG(std::cerr << "\n*** Scheduling: ");
-    DEBUG(CurrNode->dump(&DAG, false));
-    DEBUG(std::cerr << "\n");
-    ScheduleNode(CurrNode);
-  }
+    SUnit *FoundSUnit = 0;
+    SDNode *FoundNode = 0;
+    
+    bool HasNoopHazards = false;
+    while (!AvailableQueue->empty()) {
+      SUnit *CurSUnit = AvailableQueue->pop();
+      
+      // Get the node represented by this SUnit.
+      FoundNode = CurSUnit->Node;
+      
+      // If this is a pseudo op, like copyfromreg, look to see if there is a
+      // real target node flagged to it.  If so, use the target node.
+      for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size(); 
+           !FoundNode->isMachineOpcode() && i != e; ++i)
+        FoundNode = CurSUnit->FlaggedNodes[i];
+      
+      HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
+      if (HT == HazardRecognizer::NoHazard) {
+        FoundSUnit = CurSUnit;
+        break;
+      }
+      
+      // Remember if this is a noop hazard.
+      HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
+      
+      NotReady.push_back(CurSUnit);
+    }
+    
+    // Add the nodes that aren't ready back onto the available list.
+    if (!NotReady.empty()) {
+      AvailableQueue->push_all(NotReady);
+      NotReady.clear();
+    }
 
-  // Add entry node last
-  if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
-    SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
-    Entry->Slot = CurrCycle;
-    Sequence.push_back(Entry);
+    // If we found a node to schedule, do it now.
+    if (FoundSUnit) {
+      ScheduleNodeTopDown(FoundSUnit, CurCycle);
+      HazardRec->EmitInstruction(FoundNode);
+      FoundSUnit->isScheduled = true;
+      AvailableQueue->ScheduledNode(FoundSUnit);
+
+      // If this is a pseudo-op node, we don't want to increment the current
+      // cycle.
+      if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
+        ++CurCycle;        
+    } else if (!HasNoopHazards) {
+      // Otherwise, we have a pipeline stall, but no other problem, just advance
+      // the current cycle and try again.
+      DOUT << "*** Advancing cycle, no work to do\n";
+      HazardRec->AdvanceCycle();
+      ++NumStalls;
+      ++CurCycle;
+    } else {
+      // Otherwise, we have no instructions to issue and we have instructions
+      // that will fault if we don't do this right.  This is the case for
+      // processors without pipeline interlocks and other cases.
+      DOUT << "*** Emitting noop\n";
+      HazardRec->EmitNoop();
+      Sequence.push_back(0);   // NULL SUnit* -> noop
+      ++NumNoops;
+      ++CurCycle;
+    }
   }
 
 #ifndef NDEBUG
-  for (std::map<SDNode*, SUnit*>::iterator I = SUnitMap.begin(),
-         E = SUnitMap.end(); I != E; ++I) {
-    SUnit *SU = I->second;
-    if (SU->NumSuccsLeft != 0) {
-      std::cerr << "*** List scheduling failed! ***\n";
-      SU->dump(&DAG);
-      std::cerr << " has not been scheduled!\n";
-      assert(0);
+  // Verify that all SUnits were scheduled.
+  bool AnyNotSched = false;
+  for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
+    if (SUnits[i].NumPredsLeft != 0) {
+      if (!AnyNotSched)
+        cerr << "*** List scheduling failed! ***\n";
+      SUnits[i].dump(&DAG);
+      cerr << "has not been scheduled!\n";
+      AnyNotSched = true;
     }
   }
+  assert(!AnyNotSched);
 #endif
+}
 
+//===----------------------------------------------------------------------===//
+//                    LatencyPriorityQueue Implementation
+//===----------------------------------------------------------------------===//
+//
+// This is a SchedulingPriorityQueue that schedules using latency information to
+// reduce the length of the critical path through the basic block.
+// 
+namespace {
+  class LatencyPriorityQueue;
+  
+  /// Sorting functions for the Available queue.
+  struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
+    LatencyPriorityQueue *PQ;
+    latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
+    latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
+    
+    bool operator()(const SUnit* left, const SUnit* right) const;
+  };
+}  // end anonymous namespace
 
-  // Reverse the order if it is bottom up.
-  std::reverse(Sequence.begin(), Sequence.end());
+namespace {
+  class LatencyPriorityQueue : public SchedulingPriorityQueue {
+    // SUnits - The SUnits for the current graph.
+    std::vector<SUnit> *SUnits;
+    
+    // Latencies - The latency (max of latency from this node to the bb exit)
+    // for each node.
+    std::vector<int> Latencies;
+
+    /// NumNodesSolelyBlocking - This vector contains, for every node in the
+    /// Queue, the number of nodes that the node is the sole unscheduled
+    /// predecessor for.  This is used as a tie-breaker heuristic for better
+    /// mobility.
+    std::vector<unsigned> NumNodesSolelyBlocking;
+
+    PriorityQueue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
+public:
+    LatencyPriorityQueue() : Queue(latency_sort(this)) {
+    }
+    
+    void initNodes(std::vector<SUnit> &sunits) {
+      SUnits = &sunits;
+      // Calculate node priorities.
+      CalculatePriorities();
+    }
 
-  DEBUG(std::cerr << "*** Final schedule ***\n");
-  DEBUG(dump());
-}
+    void addNode(const SUnit *SU) {
+      Latencies.resize(SUnits->size(), -1);
+      NumNodesSolelyBlocking.resize(SUnits->size(), 0);
+      CalcLatency(*SU);
+    }
 
-/// CalcNodePriority - Priority 1 is just the number of live range genned - number
-/// of live range killed. Priority 2 is the Sethi Ullman number. It returns
-/// priority 2 since it is calculated recursively.
-/// Smaller number is the higher priority in both cases.
-int ScheduleDAGList::CalcNodePriority(SUnit *SU) {
-  if (SU->Priority2 != INT_MIN)
-    return SU->Priority2;
-
-  SU->Priority1 = SU->Preds.size() - SU->Succs.size();
-
-  if (SU->Preds.size() == 0) {
-    SU->Priority2 = 1;
-  } else {
-    int Extra = 0;
-    for (unsigned i = 0, e = SU->Preds.size(); i != e; i++) {
-      SDNode *PredN  = SU->Preds[i];
-      SUnit  *PredSU = SUnitMap[PredN];
-      int PredPriority = CalcNodePriority(PredSU);
-      if (PredPriority > SU->Priority2) {
-        SU->Priority2 = PredPriority;
-        Extra = 0;
-      } else if (PredPriority == SU->Priority2)
-        Extra++;
+    void updateNode(const SUnit *SU) {
+      Latencies[SU->NodeNum] = -1;
+      CalcLatency(*SU);
     }
 
-    if (SU->Node->getOpcode() != ISD::TokenFactor)
-      SU->Priority2 += Extra;
-    else
-      SU->Priority2 = (Extra == 1) ? 0 : Extra-1;
-  }
+    void releaseState() {
+      SUnits = 0;
+      Latencies.clear();
+    }
+    
+    unsigned getLatency(unsigned NodeNum) const {
+      assert(NodeNum < Latencies.size());
+      return Latencies[NodeNum];
+    }
+    
+    unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
+      assert(NodeNum < NumNodesSolelyBlocking.size());
+      return NumNodesSolelyBlocking[NodeNum];
+    }
+    
+    unsigned size() const { return Queue.size(); }
 
-  return SU->Priority2;
-}
+    bool empty() const { return Queue.empty(); }
+    
+    virtual void push(SUnit *U) {
+      push_impl(U);
+    }
+    void push_impl(SUnit *U);
+    
+    void push_all(const std::vector<SUnit *> &Nodes) {
+      for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
+        push_impl(Nodes[i]);
+    }
+    
+    SUnit *pop() {
+      if (empty()) return NULL;
+      SUnit *V = Queue.top();
+      Queue.pop();
+      return V;
+    }
 
-/// CalculatePriorities - Calculate priorities of all scheduling units.
-void ScheduleDAGList::CalculatePriorities() {
-  for (std::map<SDNode*, SUnit*>::iterator I = SUnitMap.begin(),
-         E = SUnitMap.end(); I != E; ++I) {
-    SUnit *SU = I->second;
-    // FIXME: assumes uniform latency for now.
-    SU->Latency = 1;
-    (void)CalcNodePriority(SU);
-    DEBUG(I->second->dump(&DAG));
-    DEBUG(std::cerr << "\n");
-  }
+    void remove(SUnit *SU) {
+      assert(!Queue.empty() && "Not in queue!");
+      Queue.erase_one(SU);
+    }
+
+    // ScheduledNode - As nodes are scheduled, we look to see if there are any
+    // successor nodes that have a single unscheduled predecessor.  If so, that
+    // single predecessor has a higher priority, since scheduling it will make
+    // the node available.
+    void ScheduledNode(SUnit *Node);
+
+private:
+    void CalculatePriorities();
+    int CalcLatency(const SUnit &SU);
+    void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
+    SUnit *getSingleUnscheduledPred(SUnit *SU);
+  };
 }
 
-static bool isChainUse(SDNode *N, SDNode *UseN) {
-  for (unsigned i = 0, e = UseN->getNumOperands(); i != e; i++) {
-    SDOperand Op = UseN->getOperand(i);
-    if (Op.Val == N) {
-      MVT::ValueType VT = N->getValueType(Op.ResNo);
-      if (VT == MVT::Other)
-        return true;
-    }
-  }
-  return false;
+bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
+  unsigned LHSNum = LHS->NodeNum;
+  unsigned RHSNum = RHS->NodeNum;
+
+  // The most important heuristic is scheduling the critical path.
+  unsigned LHSLatency = PQ->getLatency(LHSNum);
+  unsigned RHSLatency = PQ->getLatency(RHSNum);
+  if (LHSLatency < RHSLatency) return true;
+  if (LHSLatency > RHSLatency) return false;
+  
+  // After that, if two nodes have identical latencies, look to see if one will
+  // unblock more other nodes than the other.
+  unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
+  unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
+  if (LHSBlocked < RHSBlocked) return true;
+  if (LHSBlocked > RHSBlocked) return false;
+  
+  // Finally, just to provide a stable ordering, use the node number as a
+  // deciding factor.
+  return LHSNum < RHSNum;
 }
 
-void ScheduleDAGList::BuildSchedUnits() {
-  for (unsigned i = 0, NC = NodeCount; i < NC; i++) {
-    NodeInfo *NI = &Info[i];
-    SDNode *N = NI->Node;
-    if (!isPassiveNode(N)) {
-      SUnit *SU;
-      if (NI->isInGroup()) {
-        if (NI != NI->Group->getBottom())  // Bottom up, so only look at bottom
-          continue;                        // node of the NodeGroup
-
-        SU = new SUnit(N);
-
-        // Find the flagged nodes.
-        SDOperand  FlagOp = N->getOperand(N->getNumOperands() - 1);
-        SDNode    *Flag   = FlagOp.Val;
-        unsigned   ResNo  = FlagOp.ResNo;
-        while (Flag->getValueType(ResNo) == MVT::Flag) {
-          NodeInfo *FNI = getNI(Flag);
-          assert(FNI->Group == NI->Group);
-          SU->FlaggedNodes.insert(SU->FlaggedNodes.begin(), Flag);
-          SUnitMap[Flag] = SU;
-
-          FlagOp = Flag->getOperand(Flag->getNumOperands() - 1);
-          Flag   = FlagOp.Val;
-          ResNo  = FlagOp.ResNo;
-        }
-
-        // Find all predecessors (of the group).
-        NodeGroupOpIterator NGOI(NI);
-        while (!NGOI.isEnd()) {
-          SDOperand Op  = NGOI.next();
-          SDNode   *OpN = Op.Val;
-          MVT::ValueType VT = OpN->getValueType(Op.ResNo);
-          NodeInfo *OpNI = getNI(OpN);
-          if (OpNI->Group != NI->Group && !isPassiveNode(OpN)) {
-            assert(VT != MVT::Flag);
-            if (VT == MVT::Other)
-              SU->ChainPreds.push_back(OpN);
-            else
-              SU->Preds.push_back(OpN);
-            SU->NumPredsLeft++;
-          }
-        }
-
-        // Find all successors (of the group).
-        NodeGroupIterator NGI(NI);
-        while (NodeInfo *GNI = NGI.next()) {
-          SDNode *GN = GNI->Node;
-          for (SDNode::use_iterator ui = GN->use_begin(), e = GN->use_end();
-               ui != e; ++ui) {
-            SDNode *UseN = *ui;
-            NodeInfo *UseNI = getNI(UseN);
-            if (UseNI->Group != NI->Group) {
-              if (isChainUse(GN, UseN))
-                SU->ChainSuccs.push_back(UseN);
-              else
-                SU->Succs.push_back(UseN);
-              SU->NumSuccsLeft++;
-            }
-          }
-        }
+
+/// CalcNodePriority - Calculate the maximal path from the node to the exit.
+///
+int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
+  int &Latency = Latencies[SU.NodeNum];
+  if (Latency != -1)
+    return Latency;
+
+  std::vector<const SUnit*> WorkList;
+  WorkList.push_back(&SU);
+  while (!WorkList.empty()) {
+    const SUnit *Cur = WorkList.back();
+    bool AllDone = true;
+    int MaxSuccLatency = 0;
+    for (SUnit::const_succ_iterator I = Cur->Succs.begin(),E = Cur->Succs.end();
+         I != E; ++I) {
+      int SuccLatency = Latencies[I->Dep->NodeNum];
+      if (SuccLatency == -1) {
+        AllDone = false;
+        WorkList.push_back(I->Dep);
       } else {
-        SU = new SUnit(N);
-
-        // Find node predecessors.
-        for (unsigned j = 0, e = N->getNumOperands(); j != e; j++) {
-          SDOperand Op  = N->getOperand(j);
-          SDNode   *OpN = Op.Val;
-          MVT::ValueType VT = OpN->getValueType(Op.ResNo);
-          if (!isPassiveNode(OpN)) {
-            assert(VT != MVT::Flag);
-            if (VT == MVT::Other)
-              SU->ChainPreds.push_back(OpN);
-            else
-              SU->Preds.push_back(OpN);
-            SU->NumPredsLeft++;
-          }
-        }
-
-        // Find node successors.
-        for (SDNode::use_iterator ui = N->use_begin(), e = N->use_end();
-             ui != e; ++ui) {
-          SDNode *UseN = *ui;
-          if (isChainUse(N, UseN))
-            SU->ChainSuccs.push_back(UseN);
-          else
-            SU->Succs.push_back(UseN);
-          SU->NumSuccsLeft++;
-        }
+        MaxSuccLatency = std::max(MaxSuccLatency, SuccLatency);
       }
-
-      SUnitMap[N] = SU;
+    }
+    if (AllDone) {
+      Latencies[Cur->NodeNum] = MaxSuccLatency + Cur->Latency;
+      WorkList.pop_back();
     }
   }
 
-#ifndef NDEBUG
-  for (std::map<SDNode*, SUnit*>::iterator I = SUnitMap.begin(),
-         E = SUnitMap.end(); I != E; ++I) {
-    SUnit *SU = I->second;
-    DEBUG(I->second->dump(&DAG));
-    DEBUG(std::cerr << "\n");
-  }
-#endif
+  return Latency;
 }
 
-/// EmitSchedule - Emit the machine code in scheduled order.
-void ScheduleDAGList::EmitSchedule() {
-  for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
-    SDNode *N;
-    SUnit *SU = Sequence[i];
-    for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++) {
-      N = SU->FlaggedNodes[j];
-      EmitNode(getNI(N));
+/// CalculatePriorities - Calculate priorities of all scheduling units.
+void LatencyPriorityQueue::CalculatePriorities() {
+  Latencies.assign(SUnits->size(), -1);
+  NumNodesSolelyBlocking.assign(SUnits->size(), 0);
+
+  // For each node, calculate the maximal path from the node to the exit.
+  std::vector<std::pair<const SUnit*, unsigned> > WorkList;
+  for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
+    const SUnit *SU = &(*SUnits)[i];
+    if (SU->Succs.empty())
+      WorkList.push_back(std::make_pair(SU, 0U));
+  }
+
+  while (!WorkList.empty()) {
+    const SUnit *SU = WorkList.back().first;
+    unsigned SuccLat = WorkList.back().second;
+    WorkList.pop_back();
+    int &Latency = Latencies[SU->NodeNum];
+    if (Latency == -1 || (SU->Latency + SuccLat) > (unsigned)Latency) {
+      Latency = SU->Latency + SuccLat;
+      for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
+           I != E; ++I)
+        WorkList.push_back(std::make_pair(I->Dep, Latency));
     }
-    EmitNode(getNI(SU->Node));
   }
 }
 
-/// dump - dump the schedule.
-void ScheduleDAGList::dump() const {
-  for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
-    SUnit *SU = Sequence[i];
-    SU->dump(&DAG, false);
+/// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
+/// of SU, return it, otherwise return null.
+SUnit *LatencyPriorityQueue::getSingleUnscheduledPred(SUnit *SU) {
+  SUnit *OnlyAvailablePred = 0;
+  for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
+       I != E; ++I) {
+    SUnit &Pred = *I->Dep;
+    if (!Pred.isScheduled) {
+      // We found an available, but not scheduled, predecessor.  If it's the
+      // only one we have found, keep track of it... otherwise give up.
+      if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
+        return 0;
+      OnlyAvailablePred = &Pred;
+    }
   }
+      
+  return OnlyAvailablePred;
 }
 
-/// Schedule - Schedule the DAG using list scheduling.
-/// FIXME: Right now it only supports the burr (bottom up register reducing)
-/// heuristic.
-void ScheduleDAGList::Schedule() {
-  DEBUG(std::cerr << "********** List Scheduling **********\n");
+void LatencyPriorityQueue::push_impl(SUnit *SU) {
+  // Look at all of the successors of this node.  Count the number of nodes that
+  // this node is the sole unscheduled node for.
+  unsigned NumNodesBlocking = 0;
+  for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
+       I != E; ++I)
+    if (getSingleUnscheduledPred(I->Dep) == SU)
+      ++NumNodesBlocking;
+  NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
+  
+  Queue.push(SU);
+}
 
-  // Build scheduling units.
-  BuildSchedUnits();
 
-  // Calculate node prirorities.
-  CalculatePriorities();
+// ScheduledNode - As nodes are scheduled, we look to see if there are any
+// successor nodes that have a single unscheduled predecessor.  If so, that
+// single predecessor has a higher priority, since scheduling it will make
+// the node available.
+void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
+  for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
+       I != E; ++I)
+    AdjustPriorityOfUnscheduledPreds(I->Dep);
+}
 
-  // Execute the actual scheduling loop.
-  ListSchedule();
+/// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
+/// scheduled.  If SU is not itself available, then there is at least one
+/// predecessor node that has not been scheduled yet.  If SU has exactly ONE
+/// unscheduled predecessor, we want to increase its priority: it getting
+/// scheduled will make this node available, so it is better than some other
+/// node of the same priority that will not make a node available.
+void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
+  if (SU->isPending) return;  // All preds scheduled.
+  
+  SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
+  if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
+  
+  // Okay, we found a single predecessor that is available, but not scheduled.
+  // Since it is available, it must be in the priority queue.  First remove it.
+  remove(OnlyAvailablePred);
 
-  // Emit in scheduled order
-  EmitSchedule();
+  // Reinsert the node into the priority queue, which recomputes its
+  // NumNodesSolelyBlocking value.
+  push(OnlyAvailablePred);
 }
-  
-llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
-                                                    MachineBasicBlock *BB) {
-  return new ScheduleDAGList(DAG, BB, DAG.getTarget());
+
+
+//===----------------------------------------------------------------------===//
+//                         Public Constructor Functions
+//===----------------------------------------------------------------------===//
+
+/// createTDListDAGScheduler - This creates a top-down list scheduler with a
+/// new hazard recognizer. This scheduler takes ownership of the hazard
+/// recognizer and deletes it when done.
+ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
+                                            SelectionDAG *DAG,
+                                            MachineBasicBlock *BB, bool Fast) {
+  return new ScheduleDAGList(*DAG, BB, DAG->getTarget(),
+                             new LatencyPriorityQueue(),
+                             IS->CreateTargetHazardRecognizer());
 }