rename DenseMap to IndexedMap.
[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/SmallSet.h"
20
21 namespace llvm {
22   struct InstrStage;
23   class MachineConstantPool;
24   class MachineModuleInfo;
25   class MachineInstr;
26   class MRegisterInfo;
27   class SelectionDAG;
28   class SelectionDAGISel;
29   class SSARegMap;
30   class TargetInstrInfo;
31   class TargetInstrDescriptor;
32   class TargetMachine;
33
34   /// HazardRecognizer - This determines whether or not an instruction can be
35   /// issued this cycle, and whether or not a noop needs to be inserted to handle
36   /// the hazard.
37   class HazardRecognizer {
38   public:
39     virtual ~HazardRecognizer();
40     
41     enum HazardType {
42       NoHazard,      // This instruction can be emitted at this cycle.
43       Hazard,        // This instruction can't be emitted at this cycle.
44       NoopHazard     // This instruction can't be emitted, and needs noops.
45     };
46     
47     /// getHazardType - Return the hazard type of emitting this node.  There are
48     /// three possible results.  Either:
49     ///  * NoHazard: it is legal to issue this instruction on this cycle.
50     ///  * Hazard: issuing this instruction would stall the machine.  If some
51     ///     other instruction is available, issue it first.
52     ///  * NoopHazard: issuing this instruction would break the program.  If
53     ///     some other instruction can be issued, do so, otherwise issue a noop.
54     virtual HazardType getHazardType(SDNode *Node) {
55       return NoHazard;
56     }
57     
58     /// EmitInstruction - This callback is invoked when an instruction is
59     /// emitted, to advance the hazard state.
60     virtual void EmitInstruction(SDNode *Node) {
61     }
62     
63     /// AdvanceCycle - This callback is invoked when no instructions can be
64     /// issued on this cycle without a hazard.  This should increment the
65     /// internal state of the hazard recognizer so that previously "Hazard"
66     /// instructions will now not be hazards.
67     virtual void AdvanceCycle() {
68     }
69     
70     /// EmitNoop - This callback is invoked when a noop was added to the
71     /// instruction stream.
72     virtual void EmitNoop() {
73     }
74   };
75   
76   /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
77   /// a group of nodes flagged together.
78   struct SUnit {
79     SDNode *Node;                       // Representative node.
80     SmallVector<SDNode*,4> FlaggedNodes;// All nodes flagged to Node.
81     
82     // Preds/Succs - The SUnits before/after us in the graph.  The boolean value
83     // is true if the edge is a token chain edge, false if it is a value edge. 
84     SmallVector<std::pair<SUnit*,bool>, 4> Preds;  // All sunit predecessors.
85     SmallVector<std::pair<SUnit*,bool>, 4> Succs;  // All sunit successors.
86
87     typedef SmallVector<std::pair<SUnit*,bool>, 4>::iterator pred_iterator;
88     typedef SmallVector<std::pair<SUnit*,bool>, 4>::iterator succ_iterator;
89     typedef SmallVector<std::pair<SUnit*,bool>, 4>::const_iterator 
90       const_pred_iterator;
91     typedef SmallVector<std::pair<SUnit*,bool>, 4>::const_iterator 
92       const_succ_iterator;
93     
94     short NumPreds;                     // # of preds.
95     short NumSuccs;                     // # of sucss.
96     short NumPredsLeft;                 // # of preds not scheduled.
97     short NumSuccsLeft;                 // # of succs not scheduled.
98     short NumChainPredsLeft;            // # of chain preds not scheduled.
99     short NumChainSuccsLeft;            // # of chain succs not scheduled.
100     bool isTwoAddress     : 1;          // Is a two-address instruction.
101     bool isCommutable     : 1;          // Is a commutable instruction.
102     bool isPending        : 1;          // True once pending.
103     bool isAvailable      : 1;          // True once available.
104     bool isScheduled      : 1;          // True once scheduled.
105     unsigned short Latency;             // Node latency.
106     unsigned CycleBound;                // Upper/lower cycle to be scheduled at.
107     unsigned Cycle;                     // Once scheduled, the cycle of the op.
108     unsigned Depth;                     // Node depth;
109     unsigned Height;                    // Node height;
110     unsigned NodeNum;                   // Entry # of node in the node vector.
111     
112     SUnit(SDNode *node, unsigned nodenum)
113       : Node(node), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
114         NumChainPredsLeft(0), NumChainSuccsLeft(0),
115         isTwoAddress(false), isCommutable(false),
116         isPending(false), isAvailable(false), isScheduled(false),
117         Latency(0), CycleBound(0), Cycle(0), Depth(0), Height(0),
118         NodeNum(nodenum) {}
119     
120     /// addPred - This adds the specified node as a pred of the current node if
121     /// not already.  This returns true if this is a new pred.
122     bool addPred(SUnit *N, bool isChain) {
123       for (unsigned i = 0, e = Preds.size(); i != e; ++i)
124         if (Preds[i].first == N && Preds[i].second == isChain)
125           return false;
126       Preds.push_back(std::make_pair(N, isChain));
127       return true;
128     }
129
130     /// addSucc - This adds the specified node as a succ of the current node if
131     /// not already.  This returns true if this is a new succ.
132     bool addSucc(SUnit *N, bool isChain) {
133       for (unsigned i = 0, e = Succs.size(); i != e; ++i)
134         if (Succs[i].first == N && Succs[i].second == isChain)
135           return false;
136       Succs.push_back(std::make_pair(N, isChain));
137       return true;
138     }
139     
140     void dump(const SelectionDAG *G) const;
141     void dumpAll(const SelectionDAG *G) const;
142   };
143
144   //===--------------------------------------------------------------------===//
145   /// SchedulingPriorityQueue - This interface is used to plug different
146   /// priorities computation algorithms into the list scheduler. It implements
147   /// the interface of a standard priority queue, where nodes are inserted in 
148   /// arbitrary order and returned in priority order.  The computation of the
149   /// priority and the representation of the queue are totally up to the
150   /// implementation to decide.
151   /// 
152   class SchedulingPriorityQueue {
153   public:
154     virtual ~SchedulingPriorityQueue() {}
155   
156     virtual void initNodes(std::map<SDNode*, SUnit*> &SUMap,
157                            std::vector<SUnit> &SUnits) = 0;
158     virtual void releaseState() = 0;
159   
160     virtual bool empty() const = 0;
161     virtual void push(SUnit *U) = 0;
162   
163     virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
164     virtual SUnit *pop() = 0;
165
166     /// ScheduledNode - As each node is scheduled, this method is invoked.  This
167     /// allows the priority function to adjust the priority of node that have
168     /// already been emitted.
169     virtual void ScheduledNode(SUnit *Node) {}
170   };
171
172   class ScheduleDAG {
173   public:
174     SelectionDAG &DAG;                    // DAG of the current basic block
175     MachineBasicBlock *BB;                // Current basic block
176     const TargetMachine &TM;              // Target processor
177     const TargetInstrInfo *TII;           // Target instruction information
178     const MRegisterInfo *MRI;             // Target processor register info
179     SSARegMap *RegMap;                    // Virtual/real register map
180     MachineConstantPool *ConstPool;       // Target constant pool
181     std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
182                                           // represent noop instructions.
183     std::map<SDNode*, SUnit*> SUnitMap;   // SDNode to SUnit mapping (n -> 1).
184     std::vector<SUnit> SUnits;            // The scheduling units.
185     SmallSet<SDNode*, 16> CommuteSet;     // Nodes the should be commuted.
186
187     ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
188                 const TargetMachine &tm)
189       : DAG(dag), BB(bb), TM(tm) {}
190
191     virtual ~ScheduleDAG() {}
192
193     /// Run - perform scheduling.
194     ///
195     MachineBasicBlock *Run();
196
197     /// isPassiveNode - Return true if the node is a non-scheduled leaf.
198     ///
199     static bool isPassiveNode(SDNode *Node) {
200       if (isa<ConstantSDNode>(Node))       return true;
201       if (isa<RegisterSDNode>(Node))       return true;
202       if (isa<GlobalAddressSDNode>(Node))  return true;
203       if (isa<BasicBlockSDNode>(Node))     return true;
204       if (isa<FrameIndexSDNode>(Node))     return true;
205       if (isa<ConstantPoolSDNode>(Node))   return true;
206       if (isa<JumpTableSDNode>(Node))      return true;
207       if (isa<ExternalSymbolSDNode>(Node)) return true;
208       return false;
209     }
210
211     /// NewSUnit - Creates a new SUnit and return a ptr to it.
212     ///
213     SUnit *NewSUnit(SDNode *N) {
214       SUnits.push_back(SUnit(N, SUnits.size()));
215       return &SUnits.back();
216     }
217
218     /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
219     /// This SUnit graph is similar to the SelectionDAG, but represents flagged
220     /// together nodes with a single SUnit.
221     void BuildSchedUnits();
222
223     /// CalculateDepths, CalculateHeights - Calculate node depth / height.
224     ///
225     void CalculateDepths();
226     void CalculateHeights();
227
228     /// CountResults - The results of target nodes have register or immediate
229     /// operands first, then an optional chain, and optional flag operands
230     /// (which do not go into the machine instrs.)
231     static unsigned CountResults(SDNode *Node);
232
233     /// CountOperands  The inputs to target nodes have any actual inputs first,
234     /// followed by an optional chain operand, then flag operands.  Compute the
235     /// number of actual operands that  will go into the machine instr.
236     static unsigned CountOperands(SDNode *Node);
237
238     /// EmitNode - Generate machine code for an node and needed dependencies.
239     /// VRBaseMap contains, for each already emitted node, the first virtual
240     /// register number for the results of the node.
241     ///
242     void EmitNode(SDNode *Node, std::map<SDNode*, unsigned> &VRBaseMap);
243     
244     /// EmitNoop - Emit a noop instruction.
245     ///
246     void EmitNoop();
247     
248     void EmitSchedule();
249
250     void dumpSchedule() const;
251
252     /// Schedule - Order nodes according to selected style.
253     ///
254     virtual void Schedule() {}
255
256   private:
257     void AddOperand(MachineInstr *MI, SDOperand Op, unsigned IIOpNum,
258                     const TargetInstrDescriptor *II,
259                     std::map<SDNode*, unsigned> &VRBaseMap);
260   };
261
262   /// createBFS_DAGScheduler - This creates a simple breadth first instruction
263   /// scheduler.
264   ScheduleDAG *createBFS_DAGScheduler(SelectionDAGISel *IS,
265                                       SelectionDAG *DAG,
266                                       MachineBasicBlock *BB);
267   
268   /// createSimpleDAGScheduler - This creates a simple two pass instruction
269   /// scheduler using instruction itinerary.
270   ScheduleDAG* createSimpleDAGScheduler(SelectionDAGISel *IS,
271                                         SelectionDAG *DAG,
272                                         MachineBasicBlock *BB);
273
274   /// createNoItinsDAGScheduler - This creates a simple two pass instruction
275   /// scheduler without using instruction itinerary.
276   ScheduleDAG* createNoItinsDAGScheduler(SelectionDAGISel *IS,
277                                          SelectionDAG *DAG,
278                                          MachineBasicBlock *BB);
279
280   /// createBURRListDAGScheduler - This creates a bottom up register usage
281   /// reduction list scheduler.
282   ScheduleDAG* createBURRListDAGScheduler(SelectionDAGISel *IS,
283                                           SelectionDAG *DAG,
284                                           MachineBasicBlock *BB);
285   
286   /// createTDRRListDAGScheduler - This creates a top down register usage
287   /// reduction list scheduler.
288   ScheduleDAG* createTDRRListDAGScheduler(SelectionDAGISel *IS,
289                                           SelectionDAG *DAG,
290                                           MachineBasicBlock *BB);
291   
292   /// createTDListDAGScheduler - This creates a top-down list scheduler with
293   /// a hazard recognizer.
294   ScheduleDAG* createTDListDAGScheduler(SelectionDAGISel *IS,
295                                         SelectionDAG *DAG,
296                                         MachineBasicBlock *BB);
297                                         
298   /// createDefaultScheduler - This creates an instruction scheduler appropriate
299   /// for the target.
300   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
301                                       SelectionDAG *DAG,
302                                       MachineBasicBlock *BB);
303 }
304
305 #endif