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