ScheduleDAG.h revision 4d8455ea4d2950ca3e818c7e9ba14150286c039b
1//===------- llvm/CodeGen/ScheduleDAG.h - Common Base Class------*- C++ -*-===//
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 file implements the ScheduleDAG class, which is used as the common
11// base class for instruction schedulers.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CODEGEN_SCHEDULEDAG_H
16#define LLVM_CODEGEN_SCHEDULEDAG_H
17
18#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/Target/TargetMachine.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/BitVector.h"
22#include "llvm/ADT/GraphTraits.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/PointerIntPair.h"
25
26namespace llvm {
27  class AliasAnalysis;
28  class SUnit;
29  class MachineConstantPool;
30  class MachineFunction;
31  class MachineRegisterInfo;
32  class MachineInstr;
33  class TargetRegisterInfo;
34  class ScheduleDAG;
35  class SDNode;
36  class TargetInstrInfo;
37  class TargetInstrDesc;
38  class TargetMachine;
39  class TargetRegisterClass;
40  template<class Graph> class GraphWriter;
41
42  /// SDep - Scheduling dependency. This represents one direction of an
43  /// edge in the scheduling DAG.
44  class SDep {
45  public:
46    /// Kind - These are the different kinds of scheduling dependencies.
47    enum Kind {
48      Data,        ///< Regular data dependence (aka true-dependence).
49      Anti,        ///< A register anti-dependedence (aka WAR).
50      Output,      ///< A register output-dependence (aka WAW).
51      Order        ///< Any other ordering dependency.
52    };
53
54  private:
55    /// Dep - A pointer to the depending/depended-on SUnit, and an enum
56    /// indicating the kind of the dependency.
57    PointerIntPair<SUnit *, 2, Kind> Dep;
58
59    /// Contents - A union discriminated by the dependence kind.
60    union {
61      /// Reg - For Data, Anti, and Output dependencies, the associated
62      /// register. For Data dependencies that don't currently have a register
63      /// assigned, this is set to zero.
64      unsigned Reg;
65
66      /// Order - Additional information about Order dependencies.
67      struct {
68        /// isNormalMemory - True if both sides of the dependence
69        /// access memory in non-volatile and fully modeled ways.
70        bool isNormalMemory : 1;
71
72        /// isMustAlias - True if both sides of the dependence are known to
73        /// access the same memory.
74        bool isMustAlias : 1;
75
76        /// isArtificial - True if this is an artificial dependency, meaning
77        /// it is not necessary for program correctness, and may be safely
78        /// deleted if necessary.
79        bool isArtificial : 1;
80      } Order;
81    } Contents;
82
83    /// Latency - The time associated with this edge. Often this is just
84    /// the value of the Latency field of the predecessor, however advanced
85    /// models may provide additional information about specific edges.
86    unsigned Latency;
87
88  public:
89    /// SDep - Construct a null SDep. This is only for use by container
90    /// classes which require default constructors. SUnits may not
91    /// have null SDep edges.
92    SDep() : Dep(0, Data) {}
93
94    /// SDep - Construct an SDep with the specified values.
95    SDep(SUnit *S, Kind kind, unsigned latency = 1, unsigned Reg = 0,
96         bool isNormalMemory = false, bool isMustAlias = false,
97         bool isArtificial = false)
98      : Dep(S, kind), Contents(), Latency(latency) {
99      switch (kind) {
100      case Anti:
101      case Output:
102        assert(Reg != 0 &&
103               "SDep::Anti and SDep::Output must use a non-zero Reg!");
104        // fall through
105      case Data:
106        assert(!isMustAlias && "isMustAlias only applies with SDep::Order!");
107        assert(!isArtificial && "isArtificial only applies with SDep::Order!");
108        Contents.Reg = Reg;
109        break;
110      case Order:
111        assert(Reg == 0 && "Reg given for non-register dependence!");
112        Contents.Order.isNormalMemory = isNormalMemory;
113        Contents.Order.isMustAlias = isMustAlias;
114        Contents.Order.isArtificial = isArtificial;
115        break;
116      }
117    }
118
119    bool operator==(const SDep &Other) const {
120      if (Dep != Other.Dep || Latency != Other.Latency) return false;
121      switch (Dep.getInt()) {
122      case Data:
123      case Anti:
124      case Output:
125        return Contents.Reg == Other.Contents.Reg;
126      case Order:
127        return Contents.Order.isNormalMemory ==
128                 Other.Contents.Order.isNormalMemory &&
129               Contents.Order.isMustAlias == Other.Contents.Order.isMustAlias &&
130               Contents.Order.isArtificial == Other.Contents.Order.isArtificial;
131      }
132      assert(0 && "Invalid dependency kind!");
133      return false;
134    }
135
136    bool operator!=(const SDep &Other) const {
137      return !operator==(Other);
138    }
139
140    /// getLatency - Return the latency value for this edge, which roughly
141    /// means the minimum number of cycles that must elapse between the
142    /// predecessor and the successor, given that they have this edge
143    /// between them.
144    unsigned getLatency() const {
145      return Latency;
146    }
147
148    /// setLatency - Set the latency for this edge.
149    void setLatency(unsigned Lat) {
150      Latency = Lat;
151    }
152
153    //// getSUnit - Return the SUnit to which this edge points.
154    SUnit *getSUnit() const {
155      return Dep.getPointer();
156    }
157
158    //// setSUnit - Assign the SUnit to which this edge points.
159    void setSUnit(SUnit *SU) {
160      Dep.setPointer(SU);
161    }
162
163    /// getKind - Return an enum value representing the kind of the dependence.
164    Kind getKind() const {
165      return Dep.getInt();
166    }
167
168    /// isCtrl - Shorthand for getKind() != SDep::Data.
169    bool isCtrl() const {
170      return getKind() != Data;
171    }
172
173    /// isNormalMemory - Test if this is an Order dependence between two
174    /// memory accesses where both sides of the dependence access memory
175    /// in non-volatile and fully modeled ways.
176    bool isNormalMemory() const {
177      return getKind() == Order && Contents.Order.isNormalMemory;
178    }
179
180    /// isMustAlias - Test if this is an Order dependence that is marked
181    /// as "must alias", meaning that the SUnits at either end of the edge
182    /// have a memory dependence on a known memory location.
183    bool isMustAlias() const {
184      return getKind() == Order && Contents.Order.isMustAlias;
185    }
186
187    /// isArtificial - Test if this is an Order dependence that is marked
188    /// as "artificial", meaning it isn't necessary for correctness.
189    bool isArtificial() const {
190      return getKind() == Order && Contents.Order.isArtificial;
191    }
192
193    /// isAssignedRegDep - Test if this is a Data dependence that is
194    /// associated with a register.
195    bool isAssignedRegDep() const {
196      return getKind() == Data && Contents.Reg != 0;
197    }
198
199    /// getReg - Return the register associated with this edge. This is
200    /// only valid on Data, Anti, and Output edges. On Data edges, this
201    /// value may be zero, meaning there is no associated register.
202    unsigned getReg() const {
203      assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
204             "getReg called on non-register dependence edge!");
205      return Contents.Reg;
206    }
207
208    /// setReg - Assign the associated register for this edge. This is
209    /// only valid on Data, Anti, and Output edges. On Anti and Output
210    /// edges, this value must not be zero. On Data edges, the value may
211    /// be zero, which would mean that no specific register is associated
212    /// with this edge.
213    void setReg(unsigned Reg) {
214      assert((getKind() == Data || getKind() == Anti || getKind() == Output) &&
215             "setReg called on non-register dependence edge!");
216      assert((getKind() != Anti || Reg != 0) &&
217             "SDep::Anti edge cannot use the zero register!");
218      assert((getKind() != Output || Reg != 0) &&
219             "SDep::Output edge cannot use the zero register!");
220      Contents.Reg = Reg;
221    }
222  };
223
224  template <>
225  struct isPodLike<SDep> { static const bool value = true; };
226
227  /// SUnit - Scheduling unit. This is a node in the scheduling DAG.
228  class SUnit {
229  private:
230    SDNode *Node;                       // Representative node.
231    MachineInstr *Instr;                // Alternatively, a MachineInstr.
232  public:
233    SUnit *OrigNode;                    // If not this, the node from which
234                                        // this node was cloned.
235
236    // Preds/Succs - The SUnits before/after us in the graph.
237    SmallVector<SDep, 4> Preds;  // All sunit predecessors.
238    SmallVector<SDep, 4> Succs;  // All sunit successors.
239
240    typedef SmallVector<SDep, 4>::iterator pred_iterator;
241    typedef SmallVector<SDep, 4>::iterator succ_iterator;
242    typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
243    typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
244
245    unsigned NodeNum;                   // Entry # of node in the node vector.
246    unsigned NodeQueueId;               // Queue id of node.
247    unsigned NumPreds;                  // # of SDep::Data preds.
248    unsigned NumSuccs;                  // # of SDep::Data sucss.
249    unsigned NumPredsLeft;              // # of preds not scheduled.
250    unsigned NumSuccsLeft;              // # of succs not scheduled.
251    unsigned short Latency;             // Node latency.
252    bool isCall           : 1;          // Is a function call.
253    bool isTwoAddress     : 1;          // Is a two-address instruction.
254    bool isCommutable     : 1;          // Is a commutable instruction.
255    bool hasPhysRegDefs   : 1;          // Has physreg defs that are being used.
256    bool hasPhysRegClobbers : 1;        // Has any physreg defs, used or not.
257    bool isPending        : 1;          // True once pending.
258    bool isAvailable      : 1;          // True once available.
259    bool isScheduled      : 1;          // True once scheduled.
260    bool isScheduleHigh   : 1;          // True if preferable to schedule high.
261    bool isCloned         : 1;          // True if this node has been cloned.
262    Sched::Preference SchedulingPref;   // Scheduling preference.
263
264    SmallVector<MachineInstr*, 4> DbgInstrList; // dbg_values referencing this.
265  private:
266    bool isDepthCurrent   : 1;          // True if Depth is current.
267    bool isHeightCurrent  : 1;          // True if Height is current.
268    unsigned Depth;                     // Node depth.
269    unsigned Height;                    // Node height.
270  public:
271    const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
272    const TargetRegisterClass *CopySrcRC;
273
274    /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
275    /// an SDNode and any nodes flagged to it.
276    SUnit(SDNode *node, unsigned nodenum)
277      : Node(node), Instr(0), OrigNode(0), NodeNum(nodenum),
278        NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
279        NumSuccsLeft(0), Latency(0),
280        isCall(false), isTwoAddress(false), isCommutable(false),
281        hasPhysRegDefs(false), hasPhysRegClobbers(false),
282        isPending(false), isAvailable(false), isScheduled(false),
283        isScheduleHigh(false), isCloned(false),
284        SchedulingPref(Sched::None),
285        isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
286        CopyDstRC(NULL), CopySrcRC(NULL) {}
287
288    /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
289    /// a MachineInstr.
290    SUnit(MachineInstr *instr, unsigned nodenum)
291      : Node(0), Instr(instr), OrigNode(0), NodeNum(nodenum),
292        NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
293        NumSuccsLeft(0), Latency(0),
294        isCall(false), isTwoAddress(false), isCommutable(false),
295        hasPhysRegDefs(false), hasPhysRegClobbers(false),
296        isPending(false), isAvailable(false), isScheduled(false),
297        isScheduleHigh(false), isCloned(false),
298        SchedulingPref(Sched::None),
299        isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
300        CopyDstRC(NULL), CopySrcRC(NULL) {}
301
302    /// SUnit - Construct a placeholder SUnit.
303    SUnit()
304      : Node(0), Instr(0), OrigNode(0), NodeNum(~0u),
305        NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
306        NumSuccsLeft(0), Latency(0),
307        isCall(false), isTwoAddress(false), isCommutable(false),
308        hasPhysRegDefs(false), hasPhysRegClobbers(false),
309        isPending(false), isAvailable(false), isScheduled(false),
310        isScheduleHigh(false), isCloned(false),
311        SchedulingPref(Sched::None),
312        isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
313        CopyDstRC(NULL), CopySrcRC(NULL) {}
314
315    /// setNode - Assign the representative SDNode for this SUnit.
316    /// This may be used during pre-regalloc scheduling.
317    void setNode(SDNode *N) {
318      assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
319      Node = N;
320    }
321
322    /// getNode - Return the representative SDNode for this SUnit.
323    /// This may be used during pre-regalloc scheduling.
324    SDNode *getNode() const {
325      assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
326      return Node;
327    }
328
329    /// setInstr - Assign the instruction for the SUnit.
330    /// This may be used during post-regalloc scheduling.
331    void setInstr(MachineInstr *MI) {
332      assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
333      Instr = MI;
334    }
335
336    /// getInstr - Return the representative MachineInstr for this SUnit.
337    /// This may be used during post-regalloc scheduling.
338    MachineInstr *getInstr() const {
339      assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
340      return Instr;
341    }
342
343    /// addPred - This adds the specified edge as a pred of the current node if
344    /// not already.  It also adds the current node as a successor of the
345    /// specified node.
346    void addPred(const SDep &D);
347
348    /// removePred - This removes the specified edge as a pred of the current
349    /// node if it exists.  It also removes the current node as a successor of
350    /// the specified node.
351    void removePred(const SDep &D);
352
353    /// getDepth - Return the depth of this node, which is the length of the
354    /// maximum path up to any node with has no predecessors.
355    unsigned getDepth() const {
356      if (!isDepthCurrent)
357        const_cast<SUnit *>(this)->ComputeDepth();
358      return Depth;
359    }
360
361    /// getHeight - Return the height of this node, which is the length of the
362    /// maximum path down to any node with has no successors.
363    unsigned getHeight() const {
364      if (!isHeightCurrent)
365        const_cast<SUnit *>(this)->ComputeHeight();
366      return Height;
367    }
368
369    /// setDepthToAtLeast - If NewDepth is greater than this node's
370    /// depth value, set it to be the new depth value. This also
371    /// recursively marks successor nodes dirty.
372    void setDepthToAtLeast(unsigned NewDepth);
373
374    /// setDepthToAtLeast - If NewDepth is greater than this node's
375    /// depth value, set it to be the new height value. This also
376    /// recursively marks predecessor nodes dirty.
377    void setHeightToAtLeast(unsigned NewHeight);
378
379    /// setDepthDirty - Set a flag in this node to indicate that its
380    /// stored Depth value will require recomputation the next time
381    /// getDepth() is called.
382    void setDepthDirty();
383
384    /// setHeightDirty - Set a flag in this node to indicate that its
385    /// stored Height value will require recomputation the next time
386    /// getHeight() is called.
387    void setHeightDirty();
388
389    /// isPred - Test if node N is a predecessor of this node.
390    bool isPred(SUnit *N) {
391      for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
392        if (Preds[i].getSUnit() == N)
393          return true;
394      return false;
395    }
396
397    /// isSucc - Test if node N is a successor of this node.
398    bool isSucc(SUnit *N) {
399      for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
400        if (Succs[i].getSUnit() == N)
401          return true;
402      return false;
403    }
404
405    void dump(const ScheduleDAG *G) const;
406    void dumpAll(const ScheduleDAG *G) const;
407    void print(raw_ostream &O, const ScheduleDAG *G) const;
408
409  private:
410    void ComputeDepth();
411    void ComputeHeight();
412  };
413
414  //===--------------------------------------------------------------------===//
415  /// SchedulingPriorityQueue - This interface is used to plug different
416  /// priorities computation algorithms into the list scheduler. It implements
417  /// the interface of a standard priority queue, where nodes are inserted in
418  /// arbitrary order and returned in priority order.  The computation of the
419  /// priority and the representation of the queue are totally up to the
420  /// implementation to decide.
421  ///
422  class SchedulingPriorityQueue {
423    unsigned CurCycle;
424  public:
425    SchedulingPriorityQueue() : CurCycle(0) {}
426    virtual ~SchedulingPriorityQueue() {}
427
428    virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
429    virtual void addNode(const SUnit *SU) = 0;
430    virtual void updateNode(const SUnit *SU) = 0;
431    virtual void releaseState() = 0;
432
433    virtual bool empty() const = 0;
434    virtual void push(SUnit *U) = 0;
435
436    void push_all(const std::vector<SUnit *> &Nodes) {
437      for (std::vector<SUnit *>::const_iterator I = Nodes.begin(),
438           E = Nodes.end(); I != E; ++I)
439        push(*I);
440    }
441
442    virtual SUnit *pop() = 0;
443
444    virtual void remove(SUnit *SU) = 0;
445
446    /// ScheduledNode - As each node is scheduled, this method is invoked.  This
447    /// allows the priority function to adjust the priority of related
448    /// unscheduled nodes, for example.
449    ///
450    virtual void ScheduledNode(SUnit *) {}
451
452    virtual void UnscheduledNode(SUnit *) {}
453
454    void setCurCycle(unsigned Cycle) {
455      CurCycle = Cycle;
456    }
457
458    unsigned getCurCycle() const {
459      return CurCycle;
460    }
461  };
462
463  class ScheduleDAG {
464  public:
465    MachineBasicBlock *BB;          // The block in which to insert instructions
466    MachineBasicBlock::iterator InsertPos;// The position to insert instructions
467    const TargetMachine &TM;              // Target processor
468    const TargetInstrInfo *TII;           // Target instruction information
469    const TargetRegisterInfo *TRI;        // Target processor register info
470    MachineFunction &MF;                  // Machine function
471    MachineRegisterInfo &MRI;             // Virtual/real register map
472    std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
473                                          // represent noop instructions.
474    std::vector<SUnit> SUnits;            // The scheduling units.
475    SUnit EntrySU;                        // Special node for the region entry.
476    SUnit ExitSU;                         // Special node for the region exit.
477
478    explicit ScheduleDAG(MachineFunction &mf);
479
480    virtual ~ScheduleDAG();
481
482    /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
483    /// using 'dot'.
484    ///
485    void viewGraph();
486
487    /// EmitSchedule - Insert MachineInstrs into the MachineBasicBlock
488    /// according to the order specified in Sequence.
489    ///
490    virtual MachineBasicBlock *EmitSchedule() = 0;
491
492    void dumpSchedule() const;
493
494    virtual void dumpNode(const SUnit *SU) const = 0;
495
496    /// getGraphNodeLabel - Return a label for an SUnit node in a visualization
497    /// of the ScheduleDAG.
498    virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0;
499
500    /// addCustomGraphFeatures - Add custom features for a visualization of
501    /// the ScheduleDAG.
502    virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const {}
503
504#ifndef NDEBUG
505    /// VerifySchedule - Verify that all SUnits were scheduled and that
506    /// their state is consistent.
507    void VerifySchedule(bool isBottomUp);
508#endif
509
510  protected:
511    /// Run - perform scheduling.
512    ///
513    void Run(MachineBasicBlock *bb, MachineBasicBlock::iterator insertPos);
514
515    /// BuildSchedGraph - Build SUnits and set up their Preds and Succs
516    /// to form the scheduling dependency graph.
517    ///
518    virtual void BuildSchedGraph(AliasAnalysis *AA) = 0;
519
520    /// ComputeLatency - Compute node latency.
521    ///
522    virtual void ComputeLatency(SUnit *SU) = 0;
523
524    /// ComputeOperandLatency - Override dependence edge latency using
525    /// operand use/def information
526    ///
527    virtual void ComputeOperandLatency(SUnit *, SUnit *,
528                                       SDep&) const { }
529
530    /// Schedule - Order nodes according to selected style, filling
531    /// in the Sequence member.
532    ///
533    virtual void Schedule() = 0;
534
535    /// ForceUnitLatencies - Return true if all scheduling edges should be given
536    /// a latency value of one.  The default is to return false; schedulers may
537    /// override this as needed.
538    virtual bool ForceUnitLatencies() const { return false; }
539
540    /// EmitNoop - Emit a noop instruction.
541    ///
542    void EmitNoop();
543
544    void EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
545  };
546
547  class SUnitIterator : public std::iterator<std::forward_iterator_tag,
548                                             SUnit, ptrdiff_t> {
549    SUnit *Node;
550    unsigned Operand;
551
552    SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
553  public:
554    bool operator==(const SUnitIterator& x) const {
555      return Operand == x.Operand;
556    }
557    bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
558
559    const SUnitIterator &operator=(const SUnitIterator &I) {
560      assert(I.Node==Node && "Cannot assign iterators to two different nodes!");
561      Operand = I.Operand;
562      return *this;
563    }
564
565    pointer operator*() const {
566      return Node->Preds[Operand].getSUnit();
567    }
568    pointer operator->() const { return operator*(); }
569
570    SUnitIterator& operator++() {                // Preincrement
571      ++Operand;
572      return *this;
573    }
574    SUnitIterator operator++(int) { // Postincrement
575      SUnitIterator tmp = *this; ++*this; return tmp;
576    }
577
578    static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
579    static SUnitIterator end  (SUnit *N) {
580      return SUnitIterator(N, (unsigned)N->Preds.size());
581    }
582
583    unsigned getOperand() const { return Operand; }
584    const SUnit *getNode() const { return Node; }
585    /// isCtrlDep - Test if this is not an SDep::Data dependence.
586    bool isCtrlDep() const {
587      return getSDep().isCtrl();
588    }
589    bool isArtificialDep() const {
590      return getSDep().isArtificial();
591    }
592    const SDep &getSDep() const {
593      return Node->Preds[Operand];
594    }
595  };
596
597  template <> struct GraphTraits<SUnit*> {
598    typedef SUnit NodeType;
599    typedef SUnitIterator ChildIteratorType;
600    static inline NodeType *getEntryNode(SUnit *N) { return N; }
601    static inline ChildIteratorType child_begin(NodeType *N) {
602      return SUnitIterator::begin(N);
603    }
604    static inline ChildIteratorType child_end(NodeType *N) {
605      return SUnitIterator::end(N);
606    }
607  };
608
609  template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
610    typedef std::vector<SUnit>::iterator nodes_iterator;
611    static nodes_iterator nodes_begin(ScheduleDAG *G) {
612      return G->SUnits.begin();
613    }
614    static nodes_iterator nodes_end(ScheduleDAG *G) {
615      return G->SUnits.end();
616    }
617  };
618
619  /// ScheduleDAGTopologicalSort is a class that computes a topological
620  /// ordering for SUnits and provides methods for dynamically updating
621  /// the ordering as new edges are added.
622  ///
623  /// This allows a very fast implementation of IsReachable, for example.
624  ///
625  class ScheduleDAGTopologicalSort {
626    /// SUnits - A reference to the ScheduleDAG's SUnits.
627    std::vector<SUnit> &SUnits;
628
629    /// Index2Node - Maps topological index to the node number.
630    std::vector<int> Index2Node;
631    /// Node2Index - Maps the node number to its topological index.
632    std::vector<int> Node2Index;
633    /// Visited - a set of nodes visited during a DFS traversal.
634    BitVector Visited;
635
636    /// DFS - make a DFS traversal and mark all nodes affected by the
637    /// edge insertion. These nodes will later get new topological indexes
638    /// by means of the Shift method.
639    void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
640
641    /// Shift - reassign topological indexes for the nodes in the DAG
642    /// to preserve the topological ordering.
643    void Shift(BitVector& Visited, int LowerBound, int UpperBound);
644
645    /// Allocate - assign the topological index to the node n.
646    void Allocate(int n, int index);
647
648  public:
649    explicit ScheduleDAGTopologicalSort(std::vector<SUnit> &SUnits);
650
651    /// InitDAGTopologicalSorting - create the initial topological
652    /// ordering from the DAG to be scheduled.
653    void InitDAGTopologicalSorting();
654
655    /// IsReachable - Checks if SU is reachable from TargetSU.
656    bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
657
658    /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU
659    /// will create a cycle.
660    bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
661
662    /// AddPred - Updates the topological ordering to accomodate an edge
663    /// to be added from SUnit X to SUnit Y.
664    void AddPred(SUnit *Y, SUnit *X);
665
666    /// RemovePred - Updates the topological ordering to accomodate an
667    /// an edge to be removed from the specified node N from the predecessors
668    /// of the current node M.
669    void RemovePred(SUnit *M, SUnit *N);
670
671    typedef std::vector<int>::iterator iterator;
672    typedef std::vector<int>::const_iterator const_iterator;
673    iterator begin() { return Index2Node.begin(); }
674    const_iterator begin() const { return Index2Node.begin(); }
675    iterator end() { return Index2Node.end(); }
676    const_iterator end() const { return Index2Node.end(); }
677
678    typedef std::vector<int>::reverse_iterator reverse_iterator;
679    typedef std::vector<int>::const_reverse_iterator const_reverse_iterator;
680    reverse_iterator rbegin() { return Index2Node.rbegin(); }
681    const_reverse_iterator rbegin() const { return Index2Node.rbegin(); }
682    reverse_iterator rend() { return Index2Node.rend(); }
683    const_reverse_iterator rend() const { return Index2Node.rend(); }
684  };
685}
686
687#endif
688