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