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