Factor out the code for verifying the work of the scheduler,
[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/GraphTraits.h"
21 #include "llvm/ADT/SmallVector.h"
22
23 namespace llvm {
24   struct SUnit;
25   class MachineConstantPool;
26   class MachineFunction;
27   class MachineModuleInfo;
28   class MachineRegisterInfo;
29   class MachineInstr;
30   class TargetRegisterInfo;
31   class ScheduleDAG;
32   class SelectionDAG;
33   class SDNode;
34   class TargetInstrInfo;
35   class TargetInstrDesc;
36   class TargetLowering;
37   class TargetMachine;
38   class TargetRegisterClass;
39   template<class Graph> class GraphWriter;
40
41   /// SDep - Scheduling dependency. It keeps track of dependent nodes,
42   /// cost of the depdenency, etc.
43   struct SDep {
44     SUnit    *Dep;           // Dependent - either a predecessor or a successor.
45     unsigned  Reg;           // If non-zero, this dep is a phy register dependency.
46     int       Cost;          // Cost of the dependency.
47     bool      isCtrl    : 1; // True iff it's a control dependency.
48     bool      isSpecial : 1; // True iff it's a special ctrl dep added during sched.
49     SDep(SUnit *d, unsigned r, int t, bool c, bool s)
50       : Dep(d), Reg(r), Cost(t), isCtrl(c), isSpecial(s) {}
51   };
52
53   /// SUnit - Scheduling unit. This is a node in the scheduling DAG.
54   struct SUnit {
55   private:
56     SDNode *Node;                       // Representative node.
57     MachineInstr *Instr;                // Alternatively, a MachineInstr.
58   public:
59     SUnit *OrigNode;                    // If not this, the node from which
60                                         // this node was cloned.
61     
62     // Preds/Succs - The SUnits before/after us in the graph.  The boolean value
63     // is true if the edge is a token chain edge, false if it is a value edge. 
64     SmallVector<SDep, 4> Preds;  // All sunit predecessors.
65     SmallVector<SDep, 4> Succs;  // All sunit successors.
66
67     typedef SmallVector<SDep, 4>::iterator pred_iterator;
68     typedef SmallVector<SDep, 4>::iterator succ_iterator;
69     typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
70     typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
71     
72     unsigned NodeNum;                   // Entry # of node in the node vector.
73     unsigned NodeQueueId;               // Queue id of node.
74     unsigned short Latency;             // Node latency.
75     short NumPreds;                     // # of non-control preds.
76     short NumSuccs;                     // # of non-control sucss.
77     short NumPredsLeft;                 // # of preds not scheduled.
78     short NumSuccsLeft;                 // # of succs not scheduled.
79     bool isTwoAddress     : 1;          // Is a two-address instruction.
80     bool isCommutable     : 1;          // Is a commutable instruction.
81     bool hasPhysRegDefs   : 1;          // Has physreg defs that are being used.
82     bool isPending        : 1;          // True once pending.
83     bool isAvailable      : 1;          // True once available.
84     bool isScheduled      : 1;          // True once scheduled.
85     unsigned CycleBound;                // Upper/lower cycle to be scheduled at.
86     unsigned Cycle;                     // Once scheduled, the cycle of the op.
87     unsigned Depth;                     // Node depth;
88     unsigned Height;                    // Node height;
89     const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
90     const TargetRegisterClass *CopySrcRC;
91     
92     /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent
93     /// an SDNode and any nodes flagged to it.
94     SUnit(SDNode *node, unsigned nodenum)
95       : Node(node), Instr(0), OrigNode(0), NodeNum(nodenum), NodeQueueId(0),
96         Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
97         isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
98         isPending(false), isAvailable(false), isScheduled(false),
99         CycleBound(0), Cycle(~0u), Depth(0), Height(0),
100         CopyDstRC(NULL), CopySrcRC(NULL) {}
101
102     /// SUnit - Construct an SUnit for post-regalloc scheduling to represent
103     /// a MachineInstr.
104     SUnit(MachineInstr *instr, unsigned nodenum)
105       : Node(0), Instr(instr), OrigNode(0), NodeNum(nodenum), NodeQueueId(0),
106         Latency(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
107         isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
108         isPending(false), isAvailable(false), isScheduled(false),
109         CycleBound(0), Cycle(~0u), Depth(0), Height(0),
110         CopyDstRC(NULL), CopySrcRC(NULL) {}
111
112     /// setNode - Assign the representative SDNode for this SUnit.
113     /// This may be used during pre-regalloc scheduling.
114     void setNode(SDNode *N) {
115       assert(!Instr && "Setting SDNode of SUnit with MachineInstr!");
116       Node = N;
117     }
118
119     /// getNode - Return the representative SDNode for this SUnit.
120     /// This may be used during pre-regalloc scheduling.
121     SDNode *getNode() const {
122       assert(!Instr && "Reading SDNode of SUnit with MachineInstr!");
123       return Node;
124     }
125
126     /// setInstr - Assign the instruction for the SUnit.
127     /// This may be used during post-regalloc scheduling.
128     void setInstr(MachineInstr *MI) {
129       assert(!Node && "Setting MachineInstr of SUnit with SDNode!");
130       Instr = MI;
131     }
132
133     /// getInstr - Return the representative MachineInstr for this SUnit.
134     /// This may be used during post-regalloc scheduling.
135     MachineInstr *getInstr() const {
136       assert(!Node && "Reading MachineInstr of SUnit with SDNode!");
137       return Instr;
138     }
139
140     /// addPred - This adds the specified node as a pred of the current node if
141     /// not already.  This returns true if this is a new pred.
142     bool addPred(SUnit *N, bool isCtrl, bool isSpecial,
143                  unsigned PhyReg = 0, int Cost = 1) {
144       for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
145         if (Preds[i].Dep == N &&
146             Preds[i].isCtrl == isCtrl && Preds[i].isSpecial == isSpecial)
147           return false;
148       Preds.push_back(SDep(N, PhyReg, Cost, isCtrl, isSpecial));
149       N->Succs.push_back(SDep(this, PhyReg, Cost, isCtrl, isSpecial));
150       if (!isCtrl) {
151         ++NumPreds;
152         ++N->NumSuccs;
153       }
154       if (!N->isScheduled)
155         ++NumPredsLeft;
156       if (!isScheduled)
157         ++N->NumSuccsLeft;
158       return true;
159     }
160
161     bool removePred(SUnit *N, bool isCtrl, bool isSpecial) {
162       for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
163            I != E; ++I)
164         if (I->Dep == N && I->isCtrl == isCtrl && I->isSpecial == isSpecial) {
165           bool FoundSucc = false;
166           for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
167                  EE = N->Succs.end(); II != EE; ++II)
168             if (II->Dep == this &&
169                 II->isCtrl == isCtrl && II->isSpecial == isSpecial) {
170               FoundSucc = true;
171               N->Succs.erase(II);
172               break;
173             }
174           assert(FoundSucc && "Mismatching preds / succs lists!");
175           Preds.erase(I);
176           if (!isCtrl) {
177             --NumPreds;
178             --N->NumSuccs;
179           }
180           if (!N->isScheduled)
181             --NumPredsLeft;
182           if (!isScheduled)
183             --N->NumSuccsLeft;
184           return true;
185         }
186       return false;
187     }
188
189     bool isPred(SUnit *N) {
190       for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
191         if (Preds[i].Dep == N)
192           return true;
193       return false;
194     }
195     
196     bool isSucc(SUnit *N) {
197       for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
198         if (Succs[i].Dep == N)
199           return true;
200       return false;
201     }
202     
203     void dump(const ScheduleDAG *G) const;
204     void dumpAll(const ScheduleDAG *G) const;
205     void print(raw_ostream &O, const ScheduleDAG *G) const;
206   };
207
208   //===--------------------------------------------------------------------===//
209   /// SchedulingPriorityQueue - This interface is used to plug different
210   /// priorities computation algorithms into the list scheduler. It implements
211   /// the interface of a standard priority queue, where nodes are inserted in 
212   /// arbitrary order and returned in priority order.  The computation of the
213   /// priority and the representation of the queue are totally up to the
214   /// implementation to decide.
215   /// 
216   class SchedulingPriorityQueue {
217   public:
218     virtual ~SchedulingPriorityQueue() {}
219   
220     virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
221     virtual void addNode(const SUnit *SU) = 0;
222     virtual void updateNode(const SUnit *SU) = 0;
223     virtual void releaseState() = 0;
224
225     virtual unsigned size() const = 0;
226     virtual bool empty() const = 0;
227     virtual void push(SUnit *U) = 0;
228   
229     virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
230     virtual SUnit *pop() = 0;
231
232     virtual void remove(SUnit *SU) = 0;
233
234     /// ScheduledNode - As each node is scheduled, this method is invoked.  This
235     /// allows the priority function to adjust the priority of related
236     /// unscheduled nodes, for example.
237     ///
238     virtual void ScheduledNode(SUnit *) {}
239
240     virtual void UnscheduledNode(SUnit *) {}
241   };
242
243   class ScheduleDAG {
244   public:
245     SelectionDAG *DAG;                    // DAG of the current basic block
246     MachineBasicBlock *BB;                // Current basic block
247     const TargetMachine &TM;              // Target processor
248     const TargetInstrInfo *TII;           // Target instruction information
249     const TargetRegisterInfo *TRI;        // Target processor register info
250     TargetLowering *TLI;                  // Target lowering info
251     MachineFunction *MF;                  // Machine function
252     MachineRegisterInfo &MRI;             // Virtual/real register map
253     MachineConstantPool *ConstPool;       // Target constant pool
254     std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
255                                           // represent noop instructions.
256     std::vector<SUnit> SUnits;            // The scheduling units.
257
258     ScheduleDAG(SelectionDAG *dag, MachineBasicBlock *bb,
259                 const TargetMachine &tm);
260
261     virtual ~ScheduleDAG();
262
263     /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
264     /// using 'dot'.
265     ///
266     void viewGraph();
267   
268     /// Run - perform scheduling.
269     ///
270     void Run();
271
272     /// BuildSchedUnits - Build SUnits and set up their Preds and Succs
273     /// to form the scheduling dependency graph.
274     ///
275     virtual void BuildSchedUnits() = 0;
276
277     /// ComputeLatency - Compute node latency.
278     ///
279     virtual void ComputeLatency(SUnit *SU) { SU->Latency = 1; }
280
281     /// CalculateDepths, CalculateHeights - Calculate node depth / height.
282     ///
283     void CalculateDepths();
284     void CalculateHeights();
285
286   protected:
287     /// EmitNoop - Emit a noop instruction.
288     ///
289     void EmitNoop();
290
291   public:
292     virtual MachineBasicBlock *EmitSchedule() = 0;
293
294     void dumpSchedule() const;
295
296     /// Schedule - Order nodes according to selected style, filling
297     /// in the Sequence member.
298     ///
299     virtual void Schedule() = 0;
300
301     virtual void dumpNode(const SUnit *SU) const = 0;
302
303     /// getGraphNodeLabel - Return a label for an SUnit node in a visualization
304     /// of the ScheduleDAG.
305     virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0;
306
307     /// addCustomGraphFeatures - Add custom features for a visualization of
308     /// the ScheduleDAG.
309     virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &GW) const {}
310
311 #ifndef NDEBUG
312     /// VerifySchedule - Verify that all SUnits were scheduled and that
313     /// their state is consistent.
314     void VerifySchedule(bool isBottomUp);
315 #endif
316
317   protected:
318     void AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO);
319
320     void EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
321
322   private:
323     /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
324     /// physical register has only a single copy use, then coalesced the copy
325     /// if possible.
326     void EmitLiveInCopy(MachineBasicBlock *MBB,
327                         MachineBasicBlock::iterator &InsertPos,
328                         unsigned VirtReg, unsigned PhysReg,
329                         const TargetRegisterClass *RC,
330                         DenseMap<MachineInstr*, unsigned> &CopyRegMap);
331
332     /// EmitLiveInCopies - If this is the first basic block in the function,
333     /// and if it has live ins that need to be copied into vregs, emit the
334     /// copies into the top of the block.
335     void EmitLiveInCopies(MachineBasicBlock *MBB);
336   };
337
338   class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
339     SUnit *Node;
340     unsigned Operand;
341
342     SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
343   public:
344     bool operator==(const SUnitIterator& x) const {
345       return Operand == x.Operand;
346     }
347     bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
348
349     const SUnitIterator &operator=(const SUnitIterator &I) {
350       assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
351       Operand = I.Operand;
352       return *this;
353     }
354
355     pointer operator*() const {
356       return Node->Preds[Operand].Dep;
357     }
358     pointer operator->() const { return operator*(); }
359
360     SUnitIterator& operator++() {                // Preincrement
361       ++Operand;
362       return *this;
363     }
364     SUnitIterator operator++(int) { // Postincrement
365       SUnitIterator tmp = *this; ++*this; return tmp;
366     }
367
368     static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
369     static SUnitIterator end  (SUnit *N) {
370       return SUnitIterator(N, (unsigned)N->Preds.size());
371     }
372
373     unsigned getOperand() const { return Operand; }
374     const SUnit *getNode() const { return Node; }
375     bool isCtrlDep() const { return Node->Preds[Operand].isCtrl; }
376     bool isSpecialDep() const { return Node->Preds[Operand].isSpecial; }
377   };
378
379   template <> struct GraphTraits<SUnit*> {
380     typedef SUnit NodeType;
381     typedef SUnitIterator ChildIteratorType;
382     static inline NodeType *getEntryNode(SUnit *N) { return N; }
383     static inline ChildIteratorType child_begin(NodeType *N) {
384       return SUnitIterator::begin(N);
385     }
386     static inline ChildIteratorType child_end(NodeType *N) {
387       return SUnitIterator::end(N);
388     }
389   };
390
391   template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
392     typedef std::vector<SUnit>::iterator nodes_iterator;
393     static nodes_iterator nodes_begin(ScheduleDAG *G) {
394       return G->SUnits.begin();
395     }
396     static nodes_iterator nodes_end(ScheduleDAG *G) {
397       return G->SUnits.end();
398     }
399   };
400 }
401
402 #endif