misched: Remove LoopDependencies heuristic.
[oota-llvm.git] / include / llvm / 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/CodeGen/TargetSchedule.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SparseSet.h"
26 #include <map>
27
28 namespace llvm {
29   class MachineLoopInfo;
30   class MachineDominatorTree;
31   class LiveIntervals;
32   class RegPressureTracker;
33
34   /// An individual mapping from virtual register number to SUnit.
35   struct VReg2SUnit {
36     unsigned VirtReg;
37     SUnit *SU;
38
39     VReg2SUnit(unsigned reg, SUnit *su): VirtReg(reg), SU(su) {}
40
41     unsigned getSparseSetIndex() const {
42       return TargetRegisterInfo::virtReg2Index(VirtReg);
43     }
44   };
45
46   /// Record a physical register access.
47   /// For non data-dependent uses, OpIdx == -1.
48   struct PhysRegSUOper {
49     SUnit *SU;
50     int OpIdx;
51
52     PhysRegSUOper(SUnit *su, int op): SU(su), OpIdx(op) {}
53   };
54
55   /// Combine a SparseSet with a 1x1 vector to track physical registers.
56   /// The SparseSet allows iterating over the (few) live registers for quickly
57   /// comparing against a regmask or clearing the set.
58   ///
59   /// Storage for the map is allocated once for the pass. The map can be
60   /// cleared between scheduling regions without freeing unused entries.
61   class Reg2SUnitsMap {
62     SparseSet<unsigned> PhysRegSet;
63     std::vector<std::vector<PhysRegSUOper> > SUnits;
64   public:
65     typedef SparseSet<unsigned>::const_iterator const_iterator;
66
67     // Allow iteration over register numbers (keys) in the map. If needed, we
68     // can provide an iterator over SUnits (values) as well.
69     const_iterator reg_begin() const { return PhysRegSet.begin(); }
70     const_iterator reg_end() const { return PhysRegSet.end(); }
71
72     /// Initialize the map with the number of registers.
73     /// If the map is already large enough, no allocation occurs.
74     /// For simplicity we expect the map to be empty().
75     void setRegLimit(unsigned Limit);
76
77     /// Returns true if the map is empty.
78     bool empty() const { return PhysRegSet.empty(); }
79
80     /// Clear the map without deallocating storage.
81     void clear();
82
83     bool contains(unsigned Reg) const { return PhysRegSet.count(Reg); }
84
85     /// If this register is mapped, return its existing SUnits vector.
86     /// Otherwise map the register and return an empty SUnits vector.
87     std::vector<PhysRegSUOper> &operator[](unsigned Reg) {
88       bool New = PhysRegSet.insert(Reg).second;
89       assert((!New || SUnits[Reg].empty()) && "stale SUnits vector");
90       (void)New;
91       return SUnits[Reg];
92     }
93
94     /// Erase an existing element without freeing memory.
95     void erase(unsigned Reg) {
96       PhysRegSet.erase(Reg);
97       SUnits[Reg].clear();
98     }
99   };
100
101   /// Use SparseSet as a SparseMap by relying on the fact that it never
102   /// compares ValueT's, only unsigned keys. This allows the set to be cleared
103   /// between scheduling regions in constant time as long as ValueT does not
104   /// require a destructor.
105   typedef SparseSet<VReg2SUnit, VirtReg2IndexFunctor> VReg2SUnitMap;
106
107   /// ScheduleDAGInstrs - A ScheduleDAG subclass for scheduling lists of
108   /// MachineInstrs.
109   class ScheduleDAGInstrs : public ScheduleDAG {
110   protected:
111     const MachineLoopInfo &MLI;
112     const MachineDominatorTree &MDT;
113     const MachineFrameInfo *MFI;
114     const InstrItineraryData *InstrItins;
115
116     /// Live Intervals provides reaching defs in preRA scheduling.
117     LiveIntervals *LIS;
118
119     /// TargetSchedModel provides an interface to the machine model.
120     TargetSchedModel SchedModel;
121
122     /// isPostRA flag indicates vregs cannot be present.
123     bool IsPostRA;
124
125     /// UnitLatencies (misnamed) flag avoids computing def-use latencies, using
126     /// the def-side latency only.
127     bool UnitLatencies;
128
129     /// The standard DAG builder does not normally include terminators as DAG
130     /// nodes because it does not create the necessary dependencies to prevent
131     /// reordering. A specialized scheduler can overide
132     /// TargetInstrInfo::isSchedulingBoundary then enable this flag to indicate
133     /// it has taken responsibility for scheduling the terminator correctly.
134     bool CanHandleTerminators;
135
136     /// State specific to the current scheduling region.
137     /// ------------------------------------------------
138
139     /// The block in which to insert instructions
140     MachineBasicBlock *BB;
141
142     /// The beginning of the range to be scheduled.
143     MachineBasicBlock::iterator RegionBegin;
144
145     /// The end of the range to be scheduled.
146     MachineBasicBlock::iterator RegionEnd;
147
148     /// The index in BB of RegionEnd.
149     unsigned EndIndex;
150
151     /// After calling BuildSchedGraph, each machine instruction in the current
152     /// scheduling region is mapped to an SUnit.
153     DenseMap<MachineInstr*, SUnit*> MISUnitMap;
154
155     /// State internal to DAG building.
156     /// -------------------------------
157
158     /// Defs, Uses - Remember where defs and uses of each register are as we
159     /// iterate upward through the instructions. This is allocated here instead
160     /// of inside BuildSchedGraph to avoid the need for it to be initialized and
161     /// destructed for each block.
162     Reg2SUnitsMap Defs;
163     Reg2SUnitsMap Uses;
164
165     /// Track the last instructon in this region defining each virtual register.
166     VReg2SUnitMap VRegDefs;
167
168     /// PendingLoads - Remember where unknown loads are after the most recent
169     /// unknown store, as we iterate. As with Defs and Uses, this is here
170     /// to minimize construction/destruction.
171     std::vector<SUnit *> PendingLoads;
172
173     /// DbgValues - Remember instruction that precedes DBG_VALUE.
174     /// These are generated by buildSchedGraph but persist so they can be
175     /// referenced when emitting the final schedule.
176     typedef std::vector<std::pair<MachineInstr *, MachineInstr *> >
177       DbgValueVector;
178     DbgValueVector DbgValues;
179     MachineInstr *FirstDbgValue;
180
181   public:
182     explicit ScheduleDAGInstrs(MachineFunction &mf,
183                                const MachineLoopInfo &mli,
184                                const MachineDominatorTree &mdt,
185                                bool IsPostRAFlag,
186                                LiveIntervals *LIS = 0);
187
188     virtual ~ScheduleDAGInstrs() {}
189
190     /// begin - Return an iterator to the top of the current scheduling region.
191     MachineBasicBlock::iterator begin() const { return RegionBegin; }
192
193     /// end - Return an iterator to the bottom of the current scheduling region.
194     MachineBasicBlock::iterator end() const { return RegionEnd; }
195
196     /// newSUnit - Creates a new SUnit and return a ptr to it.
197     SUnit *newSUnit(MachineInstr *MI);
198
199     /// getSUnit - Return an existing SUnit for this MI, or NULL.
200     SUnit *getSUnit(MachineInstr *MI) const;
201
202     /// startBlock - Prepare to perform scheduling in the given block.
203     virtual void startBlock(MachineBasicBlock *BB);
204
205     /// finishBlock - Clean up after scheduling in the given block.
206     virtual void finishBlock();
207
208     /// Initialize the scheduler state for the next scheduling region.
209     virtual void enterRegion(MachineBasicBlock *bb,
210                              MachineBasicBlock::iterator begin,
211                              MachineBasicBlock::iterator end,
212                              unsigned endcount);
213
214     /// Notify that the scheduler has finished scheduling the current region.
215     virtual void exitRegion();
216
217     /// buildSchedGraph - Build SUnits from the MachineBasicBlock that we are
218     /// input.
219     void buildSchedGraph(AliasAnalysis *AA, RegPressureTracker *RPTracker = 0);
220
221     /// addSchedBarrierDeps - Add dependencies from instructions in the current
222     /// list of instructions being scheduled to scheduling barrier. We want to
223     /// make sure instructions which define registers that are either used by
224     /// the terminator or are live-out are properly scheduled. This is
225     /// especially important when the definition latency of the return value(s)
226     /// are too high to be hidden by the branch or when the liveout registers
227     /// used by instructions in the fallthrough block.
228     void addSchedBarrierDeps();
229
230     /// computeLatency - Compute node latency.
231     ///
232     virtual void computeLatency(SUnit *SU);
233
234     /// schedule - Order nodes according to selected style, filling
235     /// in the Sequence member.
236     ///
237     /// Typically, a scheduling algorithm will implement schedule() without
238     /// overriding enterRegion() or exitRegion().
239     virtual void schedule() = 0;
240
241     /// finalizeSchedule - Allow targets to perform final scheduling actions at
242     /// the level of the whole MachineFunction. By default does nothing.
243     virtual void finalizeSchedule() {}
244
245     virtual void dumpNode(const SUnit *SU) const;
246
247     /// Return a label for a DAG node that points to an instruction.
248     virtual std::string getGraphNodeLabel(const SUnit *SU) const;
249
250     /// Return a label for the region of code covered by the DAG.
251     virtual std::string getDAGName() const;
252
253   protected:
254     void initSUnits();
255     void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx);
256     void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
257     void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
258     void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
259   };
260
261   /// newSUnit - Creates a new SUnit and return a ptr to it.
262   inline SUnit *ScheduleDAGInstrs::newSUnit(MachineInstr *MI) {
263 #ifndef NDEBUG
264     const SUnit *Addr = SUnits.empty() ? 0 : &SUnits[0];
265 #endif
266     SUnits.push_back(SUnit(MI, (unsigned)SUnits.size()));
267     assert((Addr == 0 || Addr == &SUnits[0]) &&
268            "SUnits std::vector reallocated on the fly!");
269     SUnits.back().OrigNode = &SUnits.back();
270     return &SUnits.back();
271   }
272
273   /// getSUnit - Return an existing SUnit for this MI, or NULL.
274   inline SUnit *ScheduleDAGInstrs::getSUnit(MachineInstr *MI) const {
275     DenseMap<MachineInstr*, SUnit*>::const_iterator I = MISUnitMap.find(MI);
276     if (I == MISUnitMap.end())
277       return 0;
278     return I->second;
279   }
280 } // namespace llvm
281
282 #endif