Try to clarify this comment some.
[oota-llvm.git] / lib / CodeGen / ScheduleDAGInstrs.h
1 //==- ScheduleDAGInstrs.h - MachineInstr Scheduling --------------*- 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 ScheduleDAGInstrs class, which implements
11 // scheduling for a MachineInstr-based dependency graph.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef SCHEDULEDAGINSTRS_H
16 #define SCHEDULEDAGINSTRS_H
17
18 #include "llvm/CodeGen/MachineDominators.h"
19 #include "llvm/CodeGen/MachineLoopInfo.h"
20 #include "llvm/CodeGen/ScheduleDAG.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Target/TargetRegisterInfo.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SparseSet.h"
25 #include <map>
26
27 namespace llvm {
28   class MachineLoopInfo;
29   class MachineDominatorTree;
30   class LiveIntervals;
31
32   /// LoopDependencies - This class analyzes loop-oriented register
33   /// dependencies, which are used to guide scheduling decisions.
34   /// For example, loop induction variable increments should be
35   /// scheduled as soon as possible after the variable's last use.
36   ///
37   class LLVM_LIBRARY_VISIBILITY LoopDependencies {
38     const MachineLoopInfo &MLI;
39     const MachineDominatorTree &MDT;
40
41   public:
42     typedef std::map<unsigned, std::pair<const MachineOperand *, unsigned> >
43       LoopDeps;
44     LoopDeps Deps;
45
46     LoopDependencies(const MachineLoopInfo &mli,
47                      const MachineDominatorTree &mdt) :
48       MLI(mli), MDT(mdt) {}
49
50     /// VisitLoop - Clear out any previous state and analyze the given loop.
51     ///
52     void VisitLoop(const MachineLoop *Loop) {
53       assert(Deps.empty() && "stale loop dependencies");
54
55       MachineBasicBlock *Header = Loop->getHeader();
56       SmallSet<unsigned, 8> LoopLiveIns;
57       for (MachineBasicBlock::livein_iterator LI = Header->livein_begin(),
58            LE = Header->livein_end(); LI != LE; ++LI)
59         LoopLiveIns.insert(*LI);
60
61       const MachineDomTreeNode *Node = MDT.getNode(Header);
62       const MachineBasicBlock *MBB = Node->getBlock();
63       assert(Loop->contains(MBB) &&
64              "Loop does not contain header!");
65       VisitRegion(Node, MBB, Loop, LoopLiveIns);
66     }
67
68   private:
69     void VisitRegion(const MachineDomTreeNode *Node,
70                      const MachineBasicBlock *MBB,
71                      const MachineLoop *Loop,
72                      const SmallSet<unsigned, 8> &LoopLiveIns) {
73       unsigned Count = 0;
74       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
75            I != E; ++I) {
76         const MachineInstr *MI = I;
77         if (MI->isDebugValue())
78           continue;
79         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
80           const MachineOperand &MO = MI->getOperand(i);
81           if (!MO.isReg() || !MO.isUse())
82             continue;
83           unsigned MOReg = MO.getReg();
84           if (LoopLiveIns.count(MOReg))
85             Deps.insert(std::make_pair(MOReg, std::make_pair(&MO, Count)));
86         }
87         ++Count; // Not every iteration due to dbg_value above.
88       }
89
90       const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
91       for (std::vector<MachineDomTreeNode*>::const_iterator I =
92            Children.begin(), E = Children.end(); I != E; ++I) {
93         const MachineDomTreeNode *ChildNode = *I;
94         MachineBasicBlock *ChildBlock = ChildNode->getBlock();
95         if (Loop->contains(ChildBlock))
96           VisitRegion(ChildNode, ChildBlock, Loop, LoopLiveIns);
97       }
98     }
99   };
100
101   /// ScheduleDAGInstrs - A ScheduleDAG subclass for scheduling lists of
102   /// MachineInstrs.
103   class LLVM_LIBRARY_VISIBILITY ScheduleDAGInstrs : public ScheduleDAG {
104   protected:
105     const MachineLoopInfo &MLI;
106     const MachineDominatorTree &MDT;
107     const MachineFrameInfo *MFI;
108     const InstrItineraryData *InstrItins;
109
110     /// isPostRA flag indicates vregs cannot be present.
111     bool IsPostRA;
112
113     /// Live Intervals provides reaching defs in preRA scheduling.
114     LiveIntervals *LIS;
115
116     /// State specific to the current scheduling region.
117     ///
118
119     // The block in which to insert instructions
120     MachineBasicBlock *BB;
121
122     // The beginning of the range to
123     // be scheduled. The range extends
124     // to InsertPos.
125     MachineBasicBlock::iterator Begin;
126
127     // The position to insert instructions
128     MachineBasicBlock::iterator InsertPos;
129
130     // The index in BB of InsertPos.
131     unsigned InsertPosIndex;
132
133     /// After calling BuildSchedGraph, each machine instruction in the current
134     /// scheduling region is mapped to an SUnit.
135     DenseMap<MachineInstr*, SUnit*> MISUnitMap;
136
137     /// UnitLatencies (misnamed) flag avoids computing def-use latencies, using
138     /// the def-side latency only.
139     bool UnitLatencies;
140
141     /// Combine a SparseSet with a 1x1 vector to track physical registers.
142     /// The SparseSet allows iterating over the (few) live registers for quickly
143     /// comparing against a regmask or clearing the set.
144     ///
145     /// Storage for the map is allocated once for the pass. The map can be
146     /// cleared between scheduling regions without freeing unused entries.
147     class Reg2SUnitsMap {
148       SparseSet<unsigned> PhysRegSet;
149       std::vector<std::vector<SUnit*> > SUnits;
150     public:
151       typedef SparseSet<unsigned>::const_iterator const_iterator;
152
153       // Allow iteration over register numbers (keys) in the map. If needed, we
154       // can provide an iterator over SUnits (values) as well.
155       const_iterator reg_begin() const { return PhysRegSet.begin(); }
156       const_iterator reg_end() const { return PhysRegSet.end(); }
157
158       /// Initialize the map with the number of registers.
159       /// If the map is already large enough, no allocation occurs.
160       /// For simplicity we expect the map to be empty().
161       void setRegLimit(unsigned Limit);
162
163       /// Returns true if the map is empty.
164       bool empty() const { return PhysRegSet.empty(); }
165
166       /// Clear the map without deallocating storage.
167       void clear();
168
169       bool contains(unsigned Reg) const { return PhysRegSet.count(Reg); }
170
171       /// If this register is mapped, return its existing SUnits vector.
172       /// Otherwise map the register and return an empty SUnits vector.
173       std::vector<SUnit *> &operator[](unsigned Reg) {
174         bool New = PhysRegSet.insert(Reg).second;
175         assert((!New || SUnits[Reg].empty()) && "stale SUnits vector");
176         (void)New;
177         return SUnits[Reg];
178       }
179
180       /// Erase an existing element without freeing memory.
181       void erase(unsigned Reg) {
182         PhysRegSet.erase(Reg);
183         SUnits[Reg].clear();
184       }
185     };
186     /// Defs, Uses - Remember where defs and uses of each register are as we
187     /// iterate upward through the instructions. This is allocated here instead
188     /// of inside BuildSchedGraph to avoid the need for it to be initialized and
189     /// destructed for each block.
190     Reg2SUnitsMap Defs;
191     Reg2SUnitsMap Uses;
192
193     /// An individual mapping from virtual register number to SUnit.
194     struct VReg2SUnit {
195       unsigned VirtReg;
196       SUnit *SU;
197
198       VReg2SUnit(unsigned reg, SUnit *su): VirtReg(reg), SU(su) {}
199
200       unsigned getSparseSetKey() const {
201         return TargetRegisterInfo::virtReg2Index(VirtReg);
202       }
203     };
204     /// Use SparseSet as a SparseMap by relying on the fact that it never
205     /// compares ValueT's, only unsigned keys. This allows the set to be cleared
206     /// between scheduling regions in constant time as long as ValueT does not
207     /// require a destructor.
208     typedef SparseSet<VReg2SUnit> VReg2SUnitMap;
209     /// Track the last instructon in this region defining each virtual register.
210     VReg2SUnitMap VRegDefs;
211
212     /// PendingLoads - Remember where unknown loads are after the most recent
213     /// unknown store, as we iterate. As with Defs and Uses, this is here
214     /// to minimize construction/destruction.
215     std::vector<SUnit *> PendingLoads;
216
217     /// LoopRegs - Track which registers are used for loop-carried dependencies.
218     ///
219     LoopDependencies LoopRegs;
220
221   protected:
222
223     /// DbgValues - Remember instruction that preceeds DBG_VALUE.
224     typedef std::vector<std::pair<MachineInstr *, MachineInstr *> >
225       DbgValueVector;
226     DbgValueVector DbgValues;
227     MachineInstr *FirstDbgValue;
228
229   public:
230     explicit ScheduleDAGInstrs(MachineFunction &mf,
231                                const MachineLoopInfo &mli,
232                                const MachineDominatorTree &mdt,
233                                bool IsPostRAFlag,
234                                LiveIntervals *LIS = 0);
235
236     virtual ~ScheduleDAGInstrs() {}
237
238     /// begin - Return an iterator to the top of the current scheduling region.
239     MachineBasicBlock::iterator begin() const { return Begin; }
240
241     /// end - Return an iterator to the bottom of the current scheduling region.
242     MachineBasicBlock::iterator end() const { return InsertPos; }
243
244     /// NewSUnit - Creates a new SUnit and return a ptr to it.
245     ///
246     SUnit *NewSUnit(MachineInstr *MI) {
247 #ifndef NDEBUG
248       const SUnit *Addr = SUnits.empty() ? 0 : &SUnits[0];
249 #endif
250       SUnits.push_back(SUnit(MI, (unsigned)SUnits.size()));
251       assert((Addr == 0 || Addr == &SUnits[0]) &&
252              "SUnits std::vector reallocated on the fly!");
253       SUnits.back().OrigNode = &SUnits.back();
254       return &SUnits.back();
255     }
256
257     /// StartBlock - Prepare to perform scheduling in the given block.
258     ///
259     virtual void StartBlock(MachineBasicBlock *BB);
260
261     /// FinishBlock - Clean up after scheduling in the given block.
262     ///
263     virtual void FinishBlock();
264
265     /// Initialize the scheduler state for the next scheduling region.
266     virtual void enterRegion(MachineBasicBlock *bb,
267                              MachineBasicBlock::iterator begin,
268                              MachineBasicBlock::iterator end,
269                              unsigned endcount);
270
271     /// Notify that the scheduler has finished scheduling the current region.
272     virtual void exitRegion();
273
274     /// BuildSchedGraph - Build SUnits from the MachineBasicBlock that we are
275     /// input.
276     void BuildSchedGraph(AliasAnalysis *AA);
277
278     /// AddSchedBarrierDeps - Add dependencies from instructions in the current
279     /// list of instructions being scheduled to scheduling barrier. We want to
280     /// make sure instructions which define registers that are either used by
281     /// the terminator or are live-out are properly scheduled. This is
282     /// especially important when the definition latency of the return value(s)
283     /// are too high to be hidden by the branch or when the liveout registers
284     /// used by instructions in the fallthrough block.
285     void AddSchedBarrierDeps();
286
287     /// ComputeLatency - Compute node latency.
288     ///
289     virtual void ComputeLatency(SUnit *SU);
290
291     /// ComputeOperandLatency - Override dependence edge latency using
292     /// operand use/def information
293     ///
294     virtual void ComputeOperandLatency(SUnit *Def, SUnit *Use,
295                                        SDep& dep) const;
296
297     /// Schedule - Order nodes according to selected style, filling
298     /// in the Sequence member.
299     ///
300     /// Typically, a scheduling algorithm will implement Schedule() without
301     /// overriding enterRegion() or exitRegion().
302     virtual void Schedule() = 0;
303
304     virtual void dumpNode(const SUnit *SU) const;
305
306     /// Return a label for a DAG node that points to an instruction.
307     virtual std::string getGraphNodeLabel(const SUnit *SU) const;
308
309     /// Return a label for the region of code covered by the DAG.
310     virtual std::string getDAGName() const;
311
312   protected:
313     SUnit *getSUnit(MachineInstr *MI) const {
314       DenseMap<MachineInstr*, SUnit*>::const_iterator I = MISUnitMap.find(MI);
315       if (I == MISUnitMap.end())
316         return 0;
317       return I->second;
318     }
319
320     void initSUnits();
321     void addPhysRegDataDeps(SUnit *SU, const MachineOperand &MO);
322     void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
323     void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
324     void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
325
326     VReg2SUnitMap::iterator findVRegDef(unsigned VirtReg) {
327       return VRegDefs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
328     }
329   };
330 }
331
332 #endif