misched prep: rename InsertPos to End.
[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 be scheduled.
123     MachineBasicBlock::iterator Begin;
124
125     /// The end of the range to be scheduled.
126     MachineBasicBlock::iterator End;
127
128     /// The index in BB of End.
129     unsigned EndIndex;
130
131     /// After calling BuildSchedGraph, each machine instruction in the current
132     /// scheduling region is mapped to an SUnit.
133     DenseMap<MachineInstr*, SUnit*> MISUnitMap;
134
135     /// UnitLatencies (misnamed) flag avoids computing def-use latencies, using
136     /// the def-side latency only.
137     bool UnitLatencies;
138
139     /// Combine a SparseSet with a 1x1 vector to track physical registers.
140     /// The SparseSet allows iterating over the (few) live registers for quickly
141     /// comparing against a regmask or clearing the set.
142     ///
143     /// Storage for the map is allocated once for the pass. The map can be
144     /// cleared between scheduling regions without freeing unused entries.
145     class Reg2SUnitsMap {
146       SparseSet<unsigned> PhysRegSet;
147       std::vector<std::vector<SUnit*> > SUnits;
148     public:
149       typedef SparseSet<unsigned>::const_iterator const_iterator;
150
151       // Allow iteration over register numbers (keys) in the map. If needed, we
152       // can provide an iterator over SUnits (values) as well.
153       const_iterator reg_begin() const { return PhysRegSet.begin(); }
154       const_iterator reg_end() const { return PhysRegSet.end(); }
155
156       /// Initialize the map with the number of registers.
157       /// If the map is already large enough, no allocation occurs.
158       /// For simplicity we expect the map to be empty().
159       void setRegLimit(unsigned Limit);
160
161       /// Returns true if the map is empty.
162       bool empty() const { return PhysRegSet.empty(); }
163
164       /// Clear the map without deallocating storage.
165       void clear();
166
167       bool contains(unsigned Reg) const { return PhysRegSet.count(Reg); }
168
169       /// If this register is mapped, return its existing SUnits vector.
170       /// Otherwise map the register and return an empty SUnits vector.
171       std::vector<SUnit *> &operator[](unsigned Reg) {
172         bool New = PhysRegSet.insert(Reg).second;
173         assert((!New || SUnits[Reg].empty()) && "stale SUnits vector");
174         (void)New;
175         return SUnits[Reg];
176       }
177
178       /// Erase an existing element without freeing memory.
179       void erase(unsigned Reg) {
180         PhysRegSet.erase(Reg);
181         SUnits[Reg].clear();
182       }
183     };
184     /// Defs, Uses - Remember where defs and uses of each register are as we
185     /// iterate upward through the instructions. This is allocated here instead
186     /// of inside BuildSchedGraph to avoid the need for it to be initialized and
187     /// destructed for each block.
188     Reg2SUnitsMap Defs;
189     Reg2SUnitsMap Uses;
190
191     /// An individual mapping from virtual register number to SUnit.
192     struct VReg2SUnit {
193       unsigned VirtReg;
194       SUnit *SU;
195
196       VReg2SUnit(unsigned reg, SUnit *su): VirtReg(reg), SU(su) {}
197
198       unsigned getSparseSetKey() const {
199         return TargetRegisterInfo::virtReg2Index(VirtReg);
200       }
201     };
202     /// Use SparseSet as a SparseMap by relying on the fact that it never
203     /// compares ValueT's, only unsigned keys. This allows the set to be cleared
204     /// between scheduling regions in constant time as long as ValueT does not
205     /// require a destructor.
206     typedef SparseSet<VReg2SUnit> VReg2SUnitMap;
207     /// Track the last instructon in this region defining each virtual register.
208     VReg2SUnitMap VRegDefs;
209
210     /// PendingLoads - Remember where unknown loads are after the most recent
211     /// unknown store, as we iterate. As with Defs and Uses, this is here
212     /// to minimize construction/destruction.
213     std::vector<SUnit *> PendingLoads;
214
215     /// LoopRegs - Track which registers are used for loop-carried dependencies.
216     ///
217     LoopDependencies LoopRegs;
218
219   protected:
220
221     /// DbgValues - Remember instruction that preceeds DBG_VALUE.
222     typedef std::vector<std::pair<MachineInstr *, MachineInstr *> >
223       DbgValueVector;
224     DbgValueVector DbgValues;
225     MachineInstr *FirstDbgValue;
226
227   public:
228     explicit ScheduleDAGInstrs(MachineFunction &mf,
229                                const MachineLoopInfo &mli,
230                                const MachineDominatorTree &mdt,
231                                bool IsPostRAFlag,
232                                LiveIntervals *LIS = 0);
233
234     virtual ~ScheduleDAGInstrs() {}
235
236     /// begin - Return an iterator to the top of the current scheduling region.
237     MachineBasicBlock::iterator begin() const { return Begin; }
238
239     /// end - Return an iterator to the bottom of the current scheduling region.
240     MachineBasicBlock::iterator end() const { return End; }
241
242     /// NewSUnit - Creates a new SUnit and return a ptr to it.
243     ///
244     SUnit *newSUnit(MachineInstr *MI) {
245 #ifndef NDEBUG
246       const SUnit *Addr = SUnits.empty() ? 0 : &SUnits[0];
247 #endif
248       SUnits.push_back(SUnit(MI, (unsigned)SUnits.size()));
249       assert((Addr == 0 || Addr == &SUnits[0]) &&
250              "SUnits std::vector reallocated on the fly!");
251       SUnits.back().OrigNode = &SUnits.back();
252       return &SUnits.back();
253     }
254
255     /// startBlock - Prepare to perform scheduling in the given block.
256     ///
257     virtual void startBlock(MachineBasicBlock *BB);
258
259     /// finishBlock - Clean up after scheduling in the given block.
260     ///
261     virtual void finishBlock();
262
263     /// Initialize the scheduler state for the next scheduling region.
264     virtual void enterRegion(MachineBasicBlock *bb,
265                              MachineBasicBlock::iterator begin,
266                              MachineBasicBlock::iterator end,
267                              unsigned endcount);
268
269     /// Notify that the scheduler has finished scheduling the current region.
270     virtual void exitRegion();
271
272     /// buildSchedGraph - Build SUnits from the MachineBasicBlock that we are
273     /// input.
274     void buildSchedGraph(AliasAnalysis *AA);
275
276     /// addSchedBarrierDeps - Add dependencies from instructions in the current
277     /// list of instructions being scheduled to scheduling barrier. We want to
278     /// make sure instructions which define registers that are either used by
279     /// the terminator or are live-out are properly scheduled. This is
280     /// especially important when the definition latency of the return value(s)
281     /// are too high to be hidden by the branch or when the liveout registers
282     /// used by instructions in the fallthrough block.
283     void addSchedBarrierDeps();
284
285     /// computeLatency - Compute node latency.
286     ///
287     virtual void computeLatency(SUnit *SU);
288
289     /// computeOperandLatency - Override dependence edge latency using
290     /// operand use/def information
291     ///
292     virtual void computeOperandLatency(SUnit *Def, SUnit *Use,
293                                        SDep& dep) const;
294
295     /// schedule - Order nodes according to selected style, filling
296     /// in the Sequence member.
297     ///
298     /// Typically, a scheduling algorithm will implement schedule() without
299     /// overriding enterRegion() or exitRegion().
300     virtual void schedule() = 0;
301
302     virtual void dumpNode(const SUnit *SU) const;
303
304     /// Return a label for a DAG node that points to an instruction.
305     virtual std::string getGraphNodeLabel(const SUnit *SU) const;
306
307     /// Return a label for the region of code covered by the DAG.
308     virtual std::string getDAGName() const;
309
310   protected:
311     SUnit *getSUnit(MachineInstr *MI) const {
312       DenseMap<MachineInstr*, SUnit*>::const_iterator I = MISUnitMap.find(MI);
313       if (I == MISUnitMap.end())
314         return 0;
315       return I->second;
316     }
317
318     void initSUnits();
319     void addPhysRegDataDeps(SUnit *SU, const MachineOperand &MO);
320     void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
321     void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
322     void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
323
324     VReg2SUnitMap::iterator findVRegDef(unsigned VirtReg) {
325       return VRegDefs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
326     }
327   };
328 }
329
330 #endif