2d4592bbe63cc2ca47f6132e581bddd141ac8d6a
[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/MachineBasicBlock.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/GraphTraits.h"
22 #include "llvm/ADT/SmallSet.h"
23
24 namespace llvm {
25   struct InstrStage;
26   struct SUnit;
27   class MachineConstantPool;
28   class MachineFunction;
29   class MachineModuleInfo;
30   class MachineRegisterInfo;
31   class MachineInstr;
32   class TargetRegisterInfo;
33   class SelectionDAG;
34   class SelectionDAGISel;
35   class TargetInstrInfo;
36   class TargetInstrDesc;
37   class TargetLowering;
38   class TargetMachine;
39   class TargetRegisterClass;
40
41   /// HazardRecognizer - This determines whether or not an instruction can be
42   /// issued this cycle, and whether or not a noop needs to be inserted to handle
43   /// the hazard.
44   class HazardRecognizer {
45   public:
46     virtual ~HazardRecognizer();
47     
48     enum HazardType {
49       NoHazard,      // This instruction can be emitted at this cycle.
50       Hazard,        // This instruction can't be emitted at this cycle.
51       NoopHazard     // This instruction can't be emitted, and needs noops.
52     };
53     
54     /// getHazardType - Return the hazard type of emitting this node.  There are
55     /// three possible results.  Either:
56     ///  * NoHazard: it is legal to issue this instruction on this cycle.
57     ///  * Hazard: issuing this instruction would stall the machine.  If some
58     ///     other instruction is available, issue it first.
59     ///  * NoopHazard: issuing this instruction would break the program.  If
60     ///     some other instruction can be issued, do so, otherwise issue a noop.
61     virtual HazardType getHazardType(SDNode *) {
62       return NoHazard;
63     }
64     
65     /// EmitInstruction - This callback is invoked when an instruction is
66     /// emitted, to advance the hazard state.
67     virtual void EmitInstruction(SDNode *) {}
68     
69     /// AdvanceCycle - This callback is invoked when no instructions can be
70     /// issued on this cycle without a hazard.  This should increment the
71     /// internal state of the hazard recognizer so that previously "Hazard"
72     /// instructions will now not be hazards.
73     virtual void AdvanceCycle() {}
74     
75     /// EmitNoop - This callback is invoked when a noop was added to the
76     /// instruction stream.
77     virtual void EmitNoop() {}
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   private:
96     SDNode *Node;                       // Representative node.
97   public:
98     SUnit *OrigNode;                    // If not this, the node from which
99                                         // this node was cloned.
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 NodeQueueId;               // Queue id of node.
113     unsigned short Latency;             // Node latency.
114     short NumPreds;                     // # of preds.
115     short NumSuccs;                     // # of sucss.
116     short NumPredsLeft;                 // # of preds not scheduled.
117     short NumSuccsLeft;                 // # of succs not scheduled.
118     bool isTwoAddress     : 1;          // Is a two-address instruction.
119     bool isCommutable     : 1;          // Is a commutable instruction.
120     bool hasPhysRegDefs   : 1;          // Has physreg defs that are being used.
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), OrigNode(0), NodeNum(nodenum), NodeQueueId(0), Latency(0),
133         NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0),
134         isTwoAddress(false), isCommutable(false), hasPhysRegDefs(false),
135         isPending(false), isAvailable(false), isScheduled(false),
136         CycleBound(0), Cycle(0), Depth(0), Height(0),
137         CopyDstRC(NULL), CopySrcRC(NULL) {}
138
139     /// setNode - Assign the representative SDNode for this SUnit.
140     void setNode(SDNode *N) { Node = N; }
141
142     /// getNode - Return the representative SDNode for this SUnit.
143     SDNode *getNode() const { return Node; }
144
145     /// addPred - This adds the specified node as a pred of the current node if
146     /// not already.  This returns true if this is a new pred.
147     bool addPred(SUnit *N, bool isCtrl, bool isSpecial,
148                  unsigned PhyReg = 0, int Cost = 1) {
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].isSpecial == isSpecial)
152           return false;
153       Preds.push_back(SDep(N, PhyReg, Cost, isCtrl, isSpecial));
154       N->Succs.push_back(SDep(this, PhyReg, Cost, isCtrl, isSpecial));
155       if (!isCtrl) {
156         ++NumPreds;
157         ++N->NumSuccs;
158       }
159       if (!N->isScheduled)
160         ++NumPredsLeft;
161       if (!isScheduled)
162         ++N->NumSuccsLeft;
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             --NumPreds;
183             --N->NumSuccs;
184           }
185           if (!N->isScheduled)
186             --NumPredsLeft;
187           if (!isScheduled)
188             --N->NumSuccsLeft;
189           return true;
190         }
191       return false;
192     }
193
194     bool isPred(SUnit *N) {
195       for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
196         if (Preds[i].Dep == N)
197           return true;
198       return false;
199     }
200     
201     bool isSucc(SUnit *N) {
202       for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i)
203         if (Succs[i].Dep == N)
204           return true;
205       return false;
206     }
207     
208     void dump(const SelectionDAG *G) const;
209     void dumpAll(const SelectionDAG *G) const;
210   };
211
212   //===--------------------------------------------------------------------===//
213   /// SchedulingPriorityQueue - This interface is used to plug different
214   /// priorities computation algorithms into the list scheduler. It implements
215   /// the interface of a standard priority queue, where nodes are inserted in 
216   /// arbitrary order and returned in priority order.  The computation of the
217   /// priority and the representation of the queue are totally up to the
218   /// implementation to decide.
219   /// 
220   class SchedulingPriorityQueue {
221   public:
222     virtual ~SchedulingPriorityQueue() {}
223   
224     virtual void initNodes(std::vector<SUnit> &SUnits) = 0;
225     virtual void addNode(const SUnit *SU) = 0;
226     virtual void updateNode(const SUnit *SU) = 0;
227     virtual void releaseState() = 0;
228
229     virtual unsigned size() const = 0;
230     virtual bool empty() const = 0;
231     virtual void push(SUnit *U) = 0;
232   
233     virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
234     virtual SUnit *pop() = 0;
235
236     virtual void remove(SUnit *SU) = 0;
237
238     /// ScheduledNode - As each node is scheduled, this method is invoked.  This
239     /// allows the priority function to adjust the priority of related
240     /// unscheduled nodes, for example.
241     ///
242     virtual void ScheduledNode(SUnit *) {}
243
244     virtual void UnscheduledNode(SUnit *) {}
245   };
246
247   class ScheduleDAG {
248   public:
249     SelectionDAG *DAG;                    // DAG of the current basic block
250     MachineBasicBlock *BB;                // Current basic block
251     const TargetMachine &TM;              // Target processor
252     const TargetInstrInfo *TII;           // Target instruction information
253     const TargetRegisterInfo *TRI;        // Target processor register info
254     TargetLowering *TLI;                  // Target lowering info
255     MachineFunction *MF;                  // Machine function
256     MachineRegisterInfo &MRI;             // Virtual/real register map
257     MachineConstantPool *ConstPool;       // Target constant pool
258     std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
259                                           // represent noop instructions.
260     std::vector<SUnit> SUnits;            // The scheduling units.
261     SmallSet<SDNode*, 16> CommuteSet;     // Nodes that should be commuted.
262
263     ScheduleDAG(SelectionDAG *dag, MachineBasicBlock *bb,
264                 const TargetMachine &tm);
265
266     virtual ~ScheduleDAG() {}
267
268     /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered
269     /// using 'dot'.
270     ///
271     void viewGraph();
272   
273     /// Run - perform scheduling.
274     ///
275     void Run();
276
277     /// isPassiveNode - Return true if the node is a non-scheduled leaf.
278     ///
279     static bool isPassiveNode(SDNode *Node) {
280       if (isa<ConstantSDNode>(Node))       return true;
281       if (isa<ConstantFPSDNode>(Node))     return true;
282       if (isa<RegisterSDNode>(Node))       return true;
283       if (isa<GlobalAddressSDNode>(Node))  return true;
284       if (isa<BasicBlockSDNode>(Node))     return true;
285       if (isa<FrameIndexSDNode>(Node))     return true;
286       if (isa<ConstantPoolSDNode>(Node))   return true;
287       if (isa<JumpTableSDNode>(Node))      return true;
288       if (isa<ExternalSymbolSDNode>(Node)) return true;
289       if (isa<MemOperandSDNode>(Node))     return true;
290       if (Node->getOpcode() == ISD::EntryToken) return true;
291       return false;
292     }
293
294     /// NewSUnit - Creates a new SUnit and return a ptr to it.
295     ///
296     SUnit *NewSUnit(SDNode *N) {
297       SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
298       SUnits.back().OrigNode = &SUnits.back();
299       return &SUnits.back();
300     }
301
302     /// Clone - Creates a clone of the specified SUnit. It does not copy the
303     /// predecessors / successors info nor the temporary scheduling states.
304     SUnit *Clone(SUnit *N);
305     
306     /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
307     /// This SUnit graph is similar to the SelectionDAG, but represents flagged
308     /// together nodes with a single SUnit.
309     void BuildSchedUnits();
310
311     /// ComputeLatency - Compute node latency.
312     ///
313     void ComputeLatency(SUnit *SU);
314
315     /// CalculateDepths, CalculateHeights - Calculate node depth / height.
316     ///
317     void CalculateDepths();
318     void CalculateHeights();
319
320     /// CountResults - The results of target nodes have register or immediate
321     /// operands first, then an optional chain, and optional flag operands
322     /// (which do not go into the machine instrs.)
323     static unsigned CountResults(SDNode *Node);
324
325     /// CountOperands - The inputs to target nodes have any actual inputs first,
326     /// followed by special operands that describe memory references, then an
327     /// optional chain operand, then flag operands.  Compute the number of
328     /// actual operands that will go into the resulting MachineInstr.
329     static unsigned CountOperands(SDNode *Node);
330
331     /// ComputeMemOperandsEnd - Find the index one past the last
332     /// MemOperandSDNode operand
333     static unsigned ComputeMemOperandsEnd(SDNode *Node);
334
335     /// EmitNode - Generate machine code for an node and needed dependencies.
336     /// VRBaseMap contains, for each already emitted node, the first virtual
337     /// register number for the results of the node.
338     ///
339     void EmitNode(SDNode *Node, bool IsClone,
340                   DenseMap<SDValue, unsigned> &VRBaseMap);
341     
342     /// EmitNoop - Emit a noop instruction.
343     ///
344     void EmitNoop();
345
346     MachineBasicBlock *EmitSchedule();
347
348     void dumpSchedule() const;
349
350     /// Schedule - Order nodes according to selected style, filling
351     /// in the Sequence member.
352     ///
353     virtual void Schedule() = 0;
354
355   private:
356     /// EmitSubregNode - Generate machine code for subreg nodes.
357     ///
358     void EmitSubregNode(SDNode *Node, 
359                         DenseMap<SDValue, unsigned> &VRBaseMap);
360
361     /// getVR - Return the virtual register corresponding to the specified result
362     /// of the specified node.
363     unsigned getVR(SDValue Op, DenseMap<SDValue, unsigned> &VRBaseMap);
364   
365     /// getDstOfCopyToRegUse - If the only use of the specified result number of
366     /// node is a CopyToReg, return its destination register. Return 0 otherwise.
367     unsigned getDstOfOnlyCopyToRegUse(SDNode *Node, unsigned ResNo) const;
368
369     void AddOperand(MachineInstr *MI, SDValue Op, unsigned IIOpNum,
370                     const TargetInstrDesc *II,
371                     DenseMap<SDValue, unsigned> &VRBaseMap);
372     void AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO);
373
374     void EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
375
376     /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
377     /// implicit physical register output.
378     void EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone,
379                          unsigned SrcReg,
380                          DenseMap<SDValue, unsigned> &VRBaseMap);
381     
382     void CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
383                                 const TargetInstrDesc &II,
384                                 DenseMap<SDValue, unsigned> &VRBaseMap);
385
386     /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
387     /// physical register has only a single copy use, then coalesced the copy
388     /// if possible.
389     void EmitLiveInCopy(MachineBasicBlock *MBB,
390                         MachineBasicBlock::iterator &InsertPos,
391                         unsigned VirtReg, unsigned PhysReg,
392                         const TargetRegisterClass *RC,
393                         DenseMap<MachineInstr*, unsigned> &CopyRegMap);
394
395     /// EmitLiveInCopies - If this is the first basic block in the function,
396     /// and if it has live ins that need to be copied into vregs, emit the
397     /// copies into the top of the block.
398     void EmitLiveInCopies(MachineBasicBlock *MBB);
399   };
400
401   /// createBURRListDAGScheduler - This creates a bottom up register usage
402   /// reduction list scheduler.
403   ScheduleDAG* createBURRListDAGScheduler(SelectionDAGISel *IS,
404                                           SelectionDAG *DAG,
405                                           const TargetMachine *TM,
406                                           MachineBasicBlock *BB,
407                                           bool Fast);
408   
409   /// createTDRRListDAGScheduler - This creates a top down register usage
410   /// reduction list scheduler.
411   ScheduleDAG* createTDRRListDAGScheduler(SelectionDAGISel *IS,
412                                           SelectionDAG *DAG,
413                                           const TargetMachine *TM,
414                                           MachineBasicBlock *BB,
415                                           bool Fast);
416   
417   /// createTDListDAGScheduler - This creates a top-down list scheduler with
418   /// a hazard recognizer.
419   ScheduleDAG* createTDListDAGScheduler(SelectionDAGISel *IS,
420                                         SelectionDAG *DAG,
421                                         const TargetMachine *TM,
422                                         MachineBasicBlock *BB,
423                                         bool Fast);
424                                         
425   /// createFastDAGScheduler - This creates a "fast" scheduler.
426   ///
427   ScheduleDAG *createFastDAGScheduler(SelectionDAGISel *IS,
428                                       SelectionDAG *DAG,
429                                       const TargetMachine *TM,
430                                       MachineBasicBlock *BB,
431                                       bool Fast);
432
433   /// createDefaultScheduler - This creates an instruction scheduler appropriate
434   /// for the target.
435   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
436                                       SelectionDAG *DAG,
437                                       const TargetMachine *TM,
438                                       MachineBasicBlock *BB,
439                                       bool Fast);
440
441   class SUnitIterator : public forward_iterator<SUnit, ptrdiff_t> {
442     SUnit *Node;
443     unsigned Operand;
444
445     SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {}
446   public:
447     bool operator==(const SUnitIterator& x) const {
448       return Operand == x.Operand;
449     }
450     bool operator!=(const SUnitIterator& x) const { return !operator==(x); }
451
452     const SUnitIterator &operator=(const SUnitIterator &I) {
453       assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
454       Operand = I.Operand;
455       return *this;
456     }
457
458     pointer operator*() const {
459       return Node->Preds[Operand].Dep;
460     }
461     pointer operator->() const { return operator*(); }
462
463     SUnitIterator& operator++() {                // Preincrement
464       ++Operand;
465       return *this;
466     }
467     SUnitIterator operator++(int) { // Postincrement
468       SUnitIterator tmp = *this; ++*this; return tmp;
469     }
470
471     static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); }
472     static SUnitIterator end  (SUnit *N) {
473       return SUnitIterator(N, (unsigned)N->Preds.size());
474     }
475
476     unsigned getOperand() const { return Operand; }
477     const SUnit *getNode() const { return Node; }
478     bool isCtrlDep() const { return Node->Preds[Operand].isCtrl; }
479     bool isSpecialDep() const { return Node->Preds[Operand].isSpecial; }
480   };
481
482   template <> struct GraphTraits<SUnit*> {
483     typedef SUnit NodeType;
484     typedef SUnitIterator ChildIteratorType;
485     static inline NodeType *getEntryNode(SUnit *N) { return N; }
486     static inline ChildIteratorType child_begin(NodeType *N) {
487       return SUnitIterator::begin(N);
488     }
489     static inline ChildIteratorType child_end(NodeType *N) {
490       return SUnitIterator::end(N);
491     }
492   };
493
494   template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> {
495     typedef std::vector<SUnit>::iterator nodes_iterator;
496     static nodes_iterator nodes_begin(ScheduleDAG *G) {
497       return G->SUnits.begin();
498     }
499     static nodes_iterator nodes_end(ScheduleDAG *G) {
500       return G->SUnits.end();
501     }
502   };
503 }
504
505 #endif