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