78eb7a55d9e093d394a0263e8e905f5c49f81a76
[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 SelectionDAG-based instruction scheduler.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CODEGEN_SCHEDULEDAG_H
16 #define LLVM_CODEGEN_SCHEDULEDAG_H
17
18 #include "llvm/CodeGen/SelectionDAG.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/GraphTraits.h"
21 #include "llvm/ADT/SmallSet.h"
22
23 namespace llvm {
24   struct InstrStage;
25   struct SUnit;
26   class MachineConstantPool;
27   class MachineFunction;
28   class MachineModuleInfo;
29   class MachineRegisterInfo;
30   class MachineInstr;
31   class TargetRegisterInfo;
32   class SelectionDAG;
33   class SelectionDAGISel;
34   class TargetInstrInfo;
35   class TargetInstrDesc;
36   class TargetMachine;
37   class TargetRegisterClass;
38
39   /// HazardRecognizer - This determines whether or not an instruction can be
40   /// issued this cycle, and whether or not a noop needs to be inserted to handle
41   /// the hazard.
42   class HazardRecognizer {
43   public:
44     virtual ~HazardRecognizer();
45     
46     enum HazardType {
47       NoHazard,      // This instruction can be emitted at this cycle.
48       Hazard,        // This instruction can't be emitted at this cycle.
49       NoopHazard     // This instruction can't be emitted, and needs noops.
50     };
51     
52     /// getHazardType - Return the hazard type of emitting this node.  There are
53     /// three possible results.  Either:
54     ///  * NoHazard: it is legal to issue this instruction on this cycle.
55     ///  * Hazard: issuing this instruction would stall the machine.  If some
56     ///     other instruction is available, issue it first.
57     ///  * NoopHazard: issuing this instruction would break the program.  If
58     ///     some other instruction can be issued, do so, otherwise issue a noop.
59     virtual HazardType getHazardType(SDNode *Node) {
60       return NoHazard;
61     }
62     
63     /// EmitInstruction - This callback is invoked when an instruction is
64     /// emitted, to advance the hazard state.
65     virtual void EmitInstruction(SDNode *Node) {
66     }
67     
68     /// AdvanceCycle - This callback is invoked when no instructions can be
69     /// issued on this cycle without a hazard.  This should increment the
70     /// internal state of the hazard recognizer so that previously "Hazard"
71     /// instructions will now not be hazards.
72     virtual void AdvanceCycle() {
73     }
74     
75     /// EmitNoop - This callback is invoked when a noop was added to the
76     /// instruction stream.
77     virtual void EmitNoop() {
78     }
79   };
80
81   /// SDep - Scheduling dependency. It keeps track of dependent nodes,
82   /// cost of the depdenency, etc.
83   struct SDep {
84     SUnit    *Dep;           // Dependent - either a predecessor or a successor.
85     unsigned  Reg;           // If non-zero, this dep is a phy register dependency.
86     int       Cost;          // Cost of the dependency.
87     bool      isCtrl    : 1; // True iff it's a control dependency.
88     bool      isSpecial : 1; // True iff it's a special ctrl dep added during sched.
89     SDep(SUnit *d, unsigned r, int t, bool c, bool s)
90       : Dep(d), Reg(r), Cost(t), isCtrl(c), isSpecial(s) {}
91   };
92
93   /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
94   /// a group of nodes flagged together.
95   struct SUnit {
96     SDNode *Node;                       // Representative node.
97     SmallVector<SDNode*,4> FlaggedNodes;// All nodes flagged to Node.
98     unsigned InstanceNo;                // Instance#. One SDNode can be multiple
99                                         // SUnit due to cloning.
100     
101     // Preds/Succs - The SUnits before/after us in the graph.  The boolean value
102     // is true if the edge is a token chain edge, false if it is a value edge. 
103     SmallVector<SDep, 4> Preds;  // All sunit predecessors.
104     SmallVector<SDep, 4> Succs;  // All sunit successors.
105
106     typedef SmallVector<SDep, 4>::iterator pred_iterator;
107     typedef SmallVector<SDep, 4>::iterator succ_iterator;
108     typedef SmallVector<SDep, 4>::const_iterator const_pred_iterator;
109     typedef SmallVector<SDep, 4>::const_iterator const_succ_iterator;
110     
111     unsigned NodeNum;                   // Entry # of node in the node vector.
112     unsigned short Latency;             // Node latency.
113     short NumPreds;                     // # of preds.
114     short NumSuccs;                     // # of sucss.
115     short NumPredsLeft;                 // # of preds not scheduled.
116     short NumSuccsLeft;                 // # of succs not scheduled.
117     bool isTwoAddress     : 1;          // Is a two-address instruction.
118     bool isCommutable     : 1;          // Is a commutable instruction.
119     bool hasPhysRegDefs   : 1;          // Has physreg defs that are being used.
120     bool isPending        : 1;          // True once pending.
121     bool isAvailable      : 1;          // True once available.
122     bool isScheduled      : 1;          // True once scheduled.
123     unsigned CycleBound;                // Upper/lower cycle to be scheduled at.
124     unsigned Cycle;                     // Once scheduled, the cycle of the op.
125     unsigned Depth;                     // Node depth;
126     unsigned Height;                    // Node height;
127     const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null.
128     const TargetRegisterClass *CopySrcRC;
129     
130     SUnit(SDNode *node, unsigned nodenum)
131       : Node(node), InstanceNo(0), NodeNum(nodenum), Latency(0),
132         NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
133         isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
134         isPending(false), isAvailable(false), isScheduled(false),
135         CycleBound(0), Cycle(0), Depth(0), Height(0),
136         CopyDstRC(NULL), CopySrcRC(NULL) {}
137
138     /// addPred - This adds the specified node as a pred of the current node if
139     /// not already.  This returns true if this is a new pred.
140     bool addPred(SUnit *N, bool isCtrl, bool isSpecial,
141                  unsigned PhyReg = 0, int Cost = 1) {
142       for (unsigned i = 0, e = Preds.size(); i != e; ++i)
143         if (Preds[i].Dep == N &&
144             Preds[i].isCtrl == isCtrl && Preds[i].isSpecial == isSpecial)
145           return false;
146       Preds.push_back(SDep(N, PhyReg, Cost, isCtrl, isSpecial));
147       N->Succs.push_back(SDep(this, PhyReg, Cost, isCtrl, isSpecial));
148       if (!isCtrl) {
149         ++NumPreds;
150         ++N->NumSuccs;
151       }
152       if (!N->isScheduled)
153         ++NumPredsLeft;
154       if (!isScheduled)
155         ++N->NumSuccsLeft;
156       return true;
157     }
158
159     bool removePred(SUnit *N, bool isCtrl, bool isSpecial) {
160       for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
161            I != E; ++I)
162         if (I->Dep == N && I->isCtrl == isCtrl && I->isSpecial == isSpecial) {
163           bool FoundSucc = false;
164           for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
165                  EE = N->Succs.end(); II != EE; ++II)
166             if (II->Dep == this &&
167                 II->isCtrl == isCtrl && II->isSpecial == isSpecial) {
168               FoundSucc = true;
169               N->Succs.erase(II);
170               break;
171             }
172           assert(FoundSucc && "Mismatching preds / succs lists!");
173           Preds.erase(I);
174           if (!isCtrl) {
175             --NumPreds;
176             --N->NumSuccs;
177           }
178           if (!N->isScheduled)
179             --NumPredsLeft;
180           if (!isScheduled)
181             --N->NumSuccsLeft;
182           return true;
183         }
184       return false;
185     }
186
187     bool isPred(SUnit *N) {
188       for (unsigned i = 0, e = Preds.size(); i != e; ++i)
189         if (Preds[i].Dep == N)
190           return true;
191       return false;
192     }
193     
194     bool isSucc(SUnit *N) {
195       for (unsigned i = 0, e = Succs.size(); i != e; ++i)
196         if (Succs[i].Dep == N)
197           return true;
198       return false;
199     }
200     
201     void dump(const SelectionDAG *G) const;
202     void dumpAll(const SelectionDAG *G) const;
203   };
204
205   //===--------------------------------------------------------------------===//
206   /// SchedulingPriorityQueue - This interface is used to plug different
207   /// priorities computation algorithms into the list scheduler. It implements
208   /// the interface of a standard priority queue, where nodes are inserted in 
209   /// arbitrary order and returned in priority order.  The computation of the
210   /// priority and the representation of the queue are totally up to the
211   /// implementation to decide.
212   /// 
213   class SchedulingPriorityQueue {
214   public:
215     virtual ~SchedulingPriorityQueue() {}
216   
217     virtual void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &SUMap,
218                            std::vector<SUnit> &SUnits) = 0;
219     virtual void addNode(const SUnit *SU) = 0;
220     virtual void updateNode(const SUnit *SU) = 0;
221     virtual void releaseState() = 0;
222
223     virtual unsigned size() const = 0;
224     virtual bool empty() const = 0;
225     virtual void push(SUnit *U) = 0;
226   
227     virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
228     virtual SUnit *pop() = 0;
229
230     virtual void remove(SUnit *SU) = 0;
231
232     /// ScheduledNode - As each node is scheduled, this method is invoked.  This
233     /// allows the priority function to adjust the priority of node that have
234     /// already been emitted.
235     virtual void ScheduledNode(SUnit *Node) {}
236
237     virtual void UnscheduledNode(SUnit *Node) {}
238   };
239
240   class ScheduleDAG {
241   public:
242     SelectionDAG &DAG;                    // DAG of the current basic block
243     MachineBasicBlock *BB;                // Current basic block
244     const TargetMachine &TM;              // Target processor
245     const TargetInstrInfo *TII;           // Target instruction information
246     const TargetRegisterInfo *TRI;        // Target processor register info
247     MachineFunction *MF;                  // Machine function
248     MachineRegisterInfo &RegInfo;         // Virtual/real register map
249     MachineConstantPool *ConstPool;       // Target constant pool
250     std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
251                                           // represent noop instructions.
252     DenseMap<SDNode*, std::vector<SUnit*> > SUnitMap;
253                                           // SDNode to SUnit mapping (n -> n).
254     std::vector<SUnit> SUnits;            // The scheduling units.
255     SmallSet<SDNode*, 16> CommuteSet;     // Nodes the should be commuted.
256
257     ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
258                 const TargetMachine &tm);
259
260     virtual ~ScheduleDAG() {}
261
262     /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
263     /// using 'dot'.
264     ///
265     void viewGraph();
266   
267     /// Run - perform scheduling.
268     ///
269     MachineBasicBlock *Run();
270
271     /// isPassiveNode - Return true if the node is a non-scheduled leaf.
272     ///
273     static bool isPassiveNode(SDNode *Node) {
274       if (isa<ConstantSDNode>(Node))       return true;
275       if (isa<ConstantFPSDNode>(Node))     return true;
276       if (isa<RegisterSDNode>(Node))       return true;
277       if (isa<GlobalAddressSDNode>(Node))  return true;
278       if (isa<BasicBlockSDNode>(Node))     return true;
279       if (isa<FrameIndexSDNode>(Node))     return true;
280       if (isa<ConstantPoolSDNode>(Node))   return true;
281       if (isa<JumpTableSDNode>(Node))      return true;
282       if (isa<ExternalSymbolSDNode>(Node)) return true;
283       if (isa<MemOperandSDNode>(Node))     return true;
284       return false;
285     }
286
287     /// NewSUnit - Creates a new SUnit and return a ptr to it.
288     ///
289     SUnit *NewSUnit(SDNode *N) {
290       SUnits.push_back(SUnit(N, SUnits.size()));
291       return &SUnits.back();
292     }
293
294     /// Clone - Creates a clone of the specified SUnit. It does not copy the
295     /// predecessors / successors info nor the temporary scheduling states.
296     SUnit *Clone(SUnit *N);
297     
298     /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
299     /// This SUnit graph is similar to the SelectionDAG, but represents flagged
300     /// together nodes with a single SUnit.
301     void BuildSchedUnits();
302
303     /// ComputeLatency - Compute node latency.
304     ///
305     void ComputeLatency(SUnit *SU);
306
307     /// CalculateDepths, CalculateHeights - Calculate node depth / height.
308     ///
309     void CalculateDepths();
310     void CalculateHeights();
311
312     /// CountResults - The results of target nodes have register or immediate
313     /// operands first, then an optional chain, and optional flag operands
314     /// (which do not go into the machine instrs.)
315     static unsigned CountResults(SDNode *Node);
316
317     /// CountOperands - The inputs to target nodes have any actual inputs first,
318     /// followed by optional memory operands chain operand, then flag operands.
319     /// Compute the number of actual operands that  will go into the machine
320     /// instr.
321     static unsigned CountOperands(SDNode *Node);
322
323     /// CountMemOperands - Find the index of the last MemOperandSDNode
324     static unsigned CountMemOperands(SDNode *Node);
325
326     /// EmitNode - Generate machine code for an node and needed dependencies.
327     /// VRBaseMap contains, for each already emitted node, the first virtual
328     /// register number for the results of the node.
329     ///
330     void EmitNode(SDNode *Node, unsigned InstNo,
331                   DenseMap<SDOperand, unsigned> &VRBaseMap);
332     
333     /// EmitNoop - Emit a noop instruction.
334     ///
335     void EmitNoop();
336
337     void EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
338
339     /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
340     /// implicit physical register output.
341     void EmitCopyFromReg(SDNode *Node, unsigned ResNo, unsigned InstNo,
342                          unsigned SrcReg,
343                          DenseMap<SDOperand, unsigned> &VRBaseMap);
344     
345     void CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
346                                 const TargetInstrDesc &II,
347                                 DenseMap<SDOperand, unsigned> &VRBaseMap);
348
349     void EmitSchedule();
350
351     void dumpSchedule() const;
352
353     /// Schedule - Order nodes according to selected style.
354     ///
355     virtual void Schedule() {}
356
357   private:
358     /// EmitSubregNode - Generate machine code for subreg nodes.
359     ///
360     void EmitSubregNode(SDNode *Node, 
361                         DenseMap<SDOperand, unsigned> &VRBaseMap);
362   
363     void AddOperand(MachineInstr *MI, SDOperand Op, unsigned IIOpNum,
364                     const TargetInstrDesc *II,
365                     DenseMap<SDOperand, unsigned> &VRBaseMap);
366
367     void AddMemOperand(MachineInstr *MI, const MemOperand &MO);
368   };
369
370   /// createBURRListDAGScheduler - This creates a bottom up register usage
371   /// reduction list scheduler.
372   ScheduleDAG* createBURRListDAGScheduler(SelectionDAGISel *IS,
373                                           SelectionDAG *DAG,
374                                           MachineBasicBlock *BB);
375   
376   /// createTDRRListDAGScheduler - This creates a top down register usage
377   /// reduction list scheduler.
378   ScheduleDAG* createTDRRListDAGScheduler(SelectionDAGISel *IS,
379                                           SelectionDAG *DAG,
380                                           MachineBasicBlock *BB);
381   
382   /// createTDListDAGScheduler - This creates a top-down list scheduler with
383   /// a hazard recognizer.
384   ScheduleDAG* createTDListDAGScheduler(SelectionDAGISel *IS,
385                                         SelectionDAG *DAG,
386                                         MachineBasicBlock *BB);
387                                         
388   /// createDefaultScheduler - This creates an instruction scheduler appropriate
389   /// for the target.
390   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
391                                       SelectionDAG *DAG,
392                                       MachineBasicBlock *BB);
393
394   class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
395     SUnit *Node;
396     unsigned Operand;
397
398     SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
399   public:
400     bool operator==(const SUnitIterator& x) const {
401       return Operand == x.Operand;
402     }
403     bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
404
405     const SUnitIterator &operator=(const SUnitIterator &I) {
406       assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
407       Operand = I.Operand;
408       return *this;
409     }
410
411     pointer operator*() const {
412       return Node->Preds[Operand].Dep;
413     }
414     pointer operator->() const { return operator*(); }
415
416     SUnitIterator& operator++() {                // Preincrement
417       ++Operand;
418       return *this;
419     }
420     SUnitIterator operator++(int) { // Postincrement
421       SUnitIterator tmp = *this; ++*this; return tmp;
422     }
423
424     static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
425     static SUnitIterator end  (SUnit *N) {
426       return SUnitIterator(N, N->Preds.size());
427     }
428
429     unsigned getOperand() const { return Operand; }
430     const SUnit *getNode() const { return Node; }
431     bool isCtrlDep() const { return Node->Preds[Operand].isCtrl; }
432   };
433
434   template <> struct GraphTraits<SUnit*> {
435     typedef SUnit NodeType;
436     typedef SUnitIterator ChildIteratorType;
437     static inline NodeType *getEntryNode(SUnit *N) { return N; }
438     static inline ChildIteratorType child_begin(NodeType *N) {
439       return SUnitIterator::begin(N);
440     }
441     static inline ChildIteratorType child_end(NodeType *N) {
442       return SUnitIterator::end(N);
443     }
444   };
445
446   template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
447     typedef std::vector<SUnit>::iterator nodes_iterator;
448     static nodes_iterator nodes_begin(ScheduleDAG *G) {
449       return G->SUnits.begin();
450     }
451     static nodes_iterator nodes_end(ScheduleDAG *G) {
452       return G->SUnits.end();
453     }
454   };
455 }
456
457 #endif