Change push_all to a non-virtual function and implement it in the
[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/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
26 namespace 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   /// SUnit - Scheduling unit. This is a node in the scheduling DAG.
225   class SUnit {
226   private:
227     SDNode *Node;                       // Representative node.
228     MachineInstr *Instr;                // Alternatively, a MachineInstr.
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     Sched::Preference SchedulingPref;   // Scheduling preference.
260
261     SmallVector<MachineInstr*, 4> DbgInstrList; // dbg_values referencing this.
262   private:
263     bool isDepthCurrent   : 1;          // True if Depth is current.
264     bool isHeightCurrent  : 1;          // True if Height is current.
265     unsigned Depth;                     // Node depth.
266     unsigned Height;                    // Node height.
267   public:
268     const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
269     const TargetRegisterClass *CopySrcRC;
270     
271     /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
272     /// an SDNode and any nodes flagged to it.
273     SUnit(SDNode *node, unsigned nodenum)
274       : Node(node), Instr(0), OrigNode(0), NodeNum(nodenum),
275         NodeQueueId(0),  Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
276         NumSuccsLeft(0), isTwoAddress(false), isCommutable(false),
277         hasPhysRegDefs(false), hasPhysRegClobbers(false),
278         isPending(false), isAvailable(false), isScheduled(false),
279         isScheduleHigh(false), isCloned(false),
280         SchedulingPref(Sched::None),
281         isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
282         CopyDstRC(NULL), CopySrcRC(NULL) {}
283
284     /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
285     /// a MachineInstr.
286     SUnit(MachineInstr *instr, unsigned nodenum)
287       : Node(0), Instr(instr), OrigNode(0), NodeNum(nodenum),
288         NodeQueueId(0), Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
289         NumSuccsLeft(0), isTwoAddress(false), isCommutable(false),
290         hasPhysRegDefs(false), hasPhysRegClobbers(false),
291         isPending(false), isAvailable(false), isScheduled(false),
292         isScheduleHigh(false), isCloned(false),
293         SchedulingPref(Sched::None),
294         isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
295         CopyDstRC(NULL), CopySrcRC(NULL) {}
296
297     /// SUnit - Construct a placeholder SUnit.
298     SUnit()
299       : Node(0), Instr(0), OrigNode(0), NodeNum(~0u),
300         NodeQueueId(0), Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0),
301         NumSuccsLeft(0), isTwoAddress(false), isCommutable(false),
302         hasPhysRegDefs(false), hasPhysRegClobbers(false),
303         isPending(false), isAvailable(false), isScheduled(false),
304         isScheduleHigh(false), isCloned(false),
305         SchedulingPref(Sched::None),
306         isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0),
307         CopyDstRC(NULL), CopySrcRC(NULL) {}
308
309     /// setNode - Assign the representative SDNode for this SUnit.
310     /// This may be used during pre-regalloc scheduling.
311     void setNode(SDNode *N) {
312       assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
313       Node = N;
314     }
315
316     /// getNode - Return the representative SDNode for this SUnit.
317     /// This may be used during pre-regalloc scheduling.
318     SDNode *getNode() const {
319       assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
320       return Node;
321     }
322
323     /// setInstr - Assign the instruction for the SUnit.
324     /// This may be used during post-regalloc scheduling.
325     void setInstr(MachineInstr *MI) {
326       assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
327       Instr = MI;
328     }
329
330     /// getInstr - Return the representative MachineInstr for this SUnit.
331     /// This may be used during post-regalloc scheduling.
332     MachineInstr *getInstr() const {
333       assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
334       return Instr;
335     }
336
337     /// addPred - This adds the specified edge as a pred of the current node if
338     /// not already.  It also adds the current node as a successor of the
339     /// specified node.
340     void addPred(const SDep &D);
341
342     /// removePred - This removes the specified edge as a pred of the current
343     /// node if it exists.  It also removes the current node as a successor of
344     /// the specified node.
345     void removePred(const SDep &D);
346
347     /// getDepth - Return the depth of this node, which is the length of the
348     /// maximum path up to any node with has no predecessors.
349     unsigned getDepth() const {
350       if (!isDepthCurrent) 
351         const_cast<SUnit *>(this)->ComputeDepth();
352       return Depth;
353     }
354
355     /// getHeight - Return the height of this node, which is the length of the
356     /// maximum path down to any node with has no successors.
357     unsigned getHeight() const {
358       if (!isHeightCurrent) 
359         const_cast<SUnit *>(this)->ComputeHeight();
360       return Height;
361     }
362
363     /// setDepthToAtLeast - If NewDepth is greater than this node's
364     /// depth value, set it to be the new depth value. This also
365     /// recursively marks successor nodes dirty.
366     void setDepthToAtLeast(unsigned NewDepth);
367
368     /// setDepthToAtLeast - If NewDepth is greater than this node's
369     /// depth value, set it to be the new height value. This also
370     /// recursively marks predecessor nodes dirty.
371     void setHeightToAtLeast(unsigned NewHeight);
372
373     /// setDepthDirty - Set a flag in this node to indicate that its
374     /// stored Depth value will require recomputation the next time
375     /// getDepth() is called.
376     void setDepthDirty();
377
378     /// setHeightDirty - Set a flag in this node to indicate that its
379     /// stored Height value will require recomputation the next time
380     /// getHeight() is called.
381     void setHeightDirty();
382
383     /// isPred - Test if node N is a predecessor of this node.
384     bool isPred(SUnit *N) {
385       for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
386         if (Preds[i].getSUnit() == N)
387           return true;
388       return false;
389     }
390     
391     /// isSucc - Test if node N is a successor of this node.
392     bool isSucc(SUnit *N) {
393       for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
394         if (Succs[i].getSUnit() == N)
395           return true;
396       return false;
397     }
398
399     void dump(const ScheduleDAG *G) const;
400     void dumpAll(const ScheduleDAG *G) const;
401     void print(raw_ostream &O, const ScheduleDAG *G) const;
402
403   private:
404     void ComputeDepth();
405     void ComputeHeight();
406   };
407
408   //===--------------------------------------------------------------------===//
409   /// SchedulingPriorityQueue - This interface is used to plug different
410   /// priorities computation algorithms into the list scheduler. It implements
411   /// the interface of a standard priority queue, where nodes are inserted in 
412   /// arbitrary order and returned in priority order.  The computation of the
413   /// priority and the representation of the queue are totally up to the
414   /// implementation to decide.
415   /// 
416   class SchedulingPriorityQueue {
417     unsigned CurCycle;
418   public:
419     SchedulingPriorityQueue() : CurCycle(0) {}
420     virtual ~SchedulingPriorityQueue() {}
421   
422     virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
423     virtual void addNode(const SUnit *SU) = 0;
424     virtual void updateNode(const SUnit *SU) = 0;
425     virtual void releaseState() = 0;
426
427     virtual bool empty() const = 0;
428     virtual void push(SUnit *U) = 0;
429   
430     void push_all(const std::vector<SUnit *> &Nodes) {
431       for (std::vector<SUnit *>::const_iterator I = Nodes.begin(),
432            E = Nodes.end(); I != E; ++I)
433         push(*I);
434     }
435
436     virtual SUnit *pop() = 0;
437
438     virtual void remove(SUnit *SU) = 0;
439
440     /// ScheduledNode - As each node is scheduled, this method is invoked.  This
441     /// allows the priority function to adjust the priority of related
442     /// unscheduled nodes, for example.
443     ///
444     virtual void ScheduledNode(SUnit *) {}
445
446     virtual void UnscheduledNode(SUnit *) {}
447
448     void setCurCycle(unsigned Cycle) {
449       CurCycle = Cycle;
450     }
451
452     unsigned getCurCycle() const {
453       return CurCycle;
454     }    
455   };
456
457   class ScheduleDAG {
458   public:
459     MachineBasicBlock *BB;          // The block in which to insert instructions
460     MachineBasicBlock::iterator InsertPos;// The position to insert instructions
461     const TargetMachine &TM;              // Target processor
462     const TargetInstrInfo *TII;           // Target instruction information
463     const TargetRegisterInfo *TRI;        // Target processor register info
464     MachineFunction &MF;                  // Machine function
465     MachineRegisterInfo &MRI;             // Virtual/real register map
466     std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
467                                           // represent noop instructions.
468     std::vector<SUnit> SUnits;            // The scheduling units.
469     SUnit EntrySU;                        // Special node for the region entry.
470     SUnit ExitSU;                         // Special node for the region exit.
471
472     explicit ScheduleDAG(MachineFunction &mf);
473
474     virtual ~ScheduleDAG();
475
476     /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
477     /// using 'dot'.
478     ///
479     void viewGraph();
480   
481     /// EmitSchedule - Insert MachineInstrs into the MachineBasicBlock
482     /// according to the order specified in Sequence.
483     ///
484     virtual MachineBasicBlock *EmitSchedule() = 0;
485
486     void dumpSchedule() const;
487
488     virtual void dumpNode(const SUnit *SU) const = 0;
489
490     /// getGraphNodeLabel - Return a label for an SUnit node in a visualization
491     /// of the ScheduleDAG.
492     virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0;
493
494     /// addCustomGraphFeatures - Add custom features for a visualization of
495     /// the ScheduleDAG.
496     virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const {}
497
498 #ifndef NDEBUG
499     /// VerifySchedule - Verify that all SUnits were scheduled and that
500     /// their state is consistent.
501     void VerifySchedule(bool isBottomUp);
502 #endif
503
504   protected:
505     /// Run - perform scheduling.
506     ///
507     void Run(MachineBasicBlock *bb, MachineBasicBlock::iterator insertPos);
508
509     /// BuildSchedGraph - Build SUnits and set up their Preds and Succs
510     /// to form the scheduling dependency graph.
511     ///
512     virtual void BuildSchedGraph(AliasAnalysis *AA) = 0;
513
514     /// ComputeLatency - Compute node latency.
515     ///
516     virtual void ComputeLatency(SUnit *SU) = 0;
517
518     /// ComputeOperandLatency - Override dependence edge latency using
519     /// operand use/def information
520     ///
521     virtual void ComputeOperandLatency(SUnit *, SUnit *,
522                                        SDep&) const { }
523
524     /// Schedule - Order nodes according to selected style, filling
525     /// in the Sequence member.
526     ///
527     virtual void Schedule() = 0;
528
529     /// ForceUnitLatencies - Return true if all scheduling edges should be given
530     /// a latency value of one.  The default is to return false; schedulers may
531     /// override this as needed.
532     virtual bool ForceUnitLatencies() const { return false; }
533
534     /// EmitNoop - Emit a noop instruction.
535     ///
536     void EmitNoop();
537
538     void EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
539   };
540
541   class SUnitIterator : public std::iterator<std::forward_iterator_tag,
542                                              SUnit, ptrdiff_t> {
543     SUnit *Node;
544     unsigned Operand;
545
546     SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
547   public:
548     bool operator==(const SUnitIterator& x) const {
549       return Operand == x.Operand;
550     }
551     bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
552
553     const SUnitIterator &operator=(const SUnitIterator &I) {
554       assert(I.Node==Node && "Cannot assign iterators to two different nodes!");
555       Operand = I.Operand;
556       return *this;
557     }
558
559     pointer operator*() const {
560       return Node->Preds[Operand].getSUnit();
561     }
562     pointer operator->() const { return operator*(); }
563
564     SUnitIterator& operator++() {                // Preincrement
565       ++Operand;
566       return *this;
567     }
568     SUnitIterator operator++(int) { // Postincrement
569       SUnitIterator tmp = *this; ++*this; return tmp;
570     }
571
572     static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
573     static SUnitIterator end  (SUnit *N) {
574       return SUnitIterator(N, (unsigned)N->Preds.size());
575     }
576
577     unsigned getOperand() const { return Operand; }
578     const SUnit *getNode() const { return Node; }
579     /// isCtrlDep - Test if this is not an SDep::Data dependence.
580     bool isCtrlDep() const {
581       return getSDep().isCtrl();
582     }
583     bool isArtificialDep() const {
584       return getSDep().isArtificial();
585     }
586     const SDep &getSDep() const {
587       return Node->Preds[Operand];
588     }
589   };
590
591   template <> struct GraphTraits<SUnit*> {
592     typedef SUnit NodeType;
593     typedef SUnitIterator ChildIteratorType;
594     static inline NodeType *getEntryNode(SUnit *N) { return N; }
595     static inline ChildIteratorType child_begin(NodeType *N) {
596       return SUnitIterator::begin(N);
597     }
598     static inline ChildIteratorType child_end(NodeType *N) {
599       return SUnitIterator::end(N);
600     }
601   };
602
603   template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
604     typedef std::vector<SUnit>::iterator nodes_iterator;
605     static nodes_iterator nodes_begin(ScheduleDAG *G) {
606       return G->SUnits.begin();
607     }
608     static nodes_iterator nodes_end(ScheduleDAG *G) {
609       return G->SUnits.end();
610     }
611   };
612
613   /// ScheduleDAGTopologicalSort is a class that computes a topological
614   /// ordering for SUnits and provides methods for dynamically updating
615   /// the ordering as new edges are added.
616   ///
617   /// This allows a very fast implementation of IsReachable, for example.
618   ///
619   class ScheduleDAGTopologicalSort {
620     /// SUnits - A reference to the ScheduleDAG's SUnits.
621     std::vector<SUnit> &SUnits;
622
623     /// Index2Node - Maps topological index to the node number.
624     std::vector<int> Index2Node;
625     /// Node2Index - Maps the node number to its topological index.
626     std::vector<int> Node2Index;
627     /// Visited - a set of nodes visited during a DFS traversal.
628     BitVector Visited;
629
630     /// DFS - make a DFS traversal and mark all nodes affected by the 
631     /// edge insertion. These nodes will later get new topological indexes
632     /// by means of the Shift method.
633     void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
634
635     /// Shift - reassign topological indexes for the nodes in the DAG
636     /// to preserve the topological ordering.
637     void Shift(BitVector& Visited, int LowerBound, int UpperBound);
638
639     /// Allocate - assign the topological index to the node n.
640     void Allocate(int n, int index);
641
642   public:
643     explicit ScheduleDAGTopologicalSort(std::vector<SUnit> &SUnits);
644
645     /// InitDAGTopologicalSorting - create the initial topological 
646     /// ordering from the DAG to be scheduled.
647     void InitDAGTopologicalSorting();
648
649     /// IsReachable - Checks if SU is reachable from TargetSU.
650     bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
651
652     /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU
653     /// will create a cycle.
654     bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
655
656     /// AddPred - Updates the topological ordering to accomodate an edge
657     /// to be added from SUnit X to SUnit Y.
658     void AddPred(SUnit *Y, SUnit *X);
659
660     /// RemovePred - Updates the topological ordering to accomodate an
661     /// an edge to be removed from the specified node N from the predecessors
662     /// of the current node M.
663     void RemovePred(SUnit *M, SUnit *N);
664
665     typedef std::vector<int>::iterator iterator;
666     typedef std::vector<int>::const_iterator const_iterator;
667     iterator begin() { return Index2Node.begin(); }
668     const_iterator begin() const { return Index2Node.begin(); }
669     iterator end() { return Index2Node.end(); }
670     const_iterator end() const { return Index2Node.end(); }
671
672     typedef std::vector<int>::reverse_iterator reverse_iterator;
673     typedef std::vector<int>::const_reverse_iterator const_reverse_iterator;
674     reverse_iterator rbegin() { return Index2Node.rbegin(); }
675     const_reverse_iterator rbegin() const { return Index2Node.rbegin(); }
676     reverse_iterator rend() { return Index2Node.rend(); }
677     const_reverse_iterator rend() const { return Index2Node.rend(); }
678   };
679 }
680
681 #endif