1 //==- ScheduleDAGInstrs.h - MachineInstr Scheduling --------------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ScheduleDAGInstrs class, which implements
11 // scheduling for a MachineInstr-based dependency graph.
13 //===----------------------------------------------------------------------===//
15 #ifndef SCHEDULEDAGINSTRS_H
16 #define SCHEDULEDAGINSTRS_H
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"
28 class MachineLoopInfo;
29 class MachineDominatorTree;
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.
37 class LLVM_LIBRARY_VISIBILITY LoopDependencies {
38 const MachineLoopInfo &MLI;
39 const MachineDominatorTree &MDT;
42 typedef std::map<unsigned, std::pair<const MachineOperand *, unsigned> >
46 LoopDependencies(const MachineLoopInfo &mli,
47 const MachineDominatorTree &mdt) :
50 /// VisitLoop - Clear out any previous state and analyze the given loop.
52 void VisitLoop(const MachineLoop *Loop) {
53 assert(Deps.empty() && "stale loop dependencies");
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);
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);
69 void VisitRegion(const MachineDomTreeNode *Node,
70 const MachineBasicBlock *MBB,
71 const MachineLoop *Loop,
72 const SmallSet<unsigned, 8> &LoopLiveIns) {
74 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
76 const MachineInstr *MI = I;
77 if (MI->isDebugValue())
79 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
80 const MachineOperand &MO = MI->getOperand(i);
81 if (!MO.isReg() || !MO.isUse())
83 unsigned MOReg = MO.getReg();
84 if (LoopLiveIns.count(MOReg))
85 Deps.insert(std::make_pair(MOReg, std::make_pair(&MO, Count)));
87 ++Count; // Not every iteration due to dbg_value above.
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);
101 /// ScheduleDAGInstrs - A ScheduleDAG subclass for scheduling lists of
103 class LLVM_LIBRARY_VISIBILITY ScheduleDAGInstrs : public ScheduleDAG {
105 const MachineLoopInfo &MLI;
106 const MachineDominatorTree &MDT;
107 const MachineFrameInfo *MFI;
108 const InstrItineraryData *InstrItins;
110 /// isPostRA flag indicates vregs cannot be present.
113 /// Live Intervals provides reaching defs in preRA scheduling.
116 /// State specific to the current scheduling region.
119 // The block in which to insert instructions
120 MachineBasicBlock *BB;
122 // The beginning of the range to
123 // be scheduled. The range extends
125 MachineBasicBlock::iterator Begin;
127 // The position to insert instructions
128 MachineBasicBlock::iterator InsertPos;
130 // The index in BB of InsertPos.
131 unsigned InsertPosIndex;
133 /// After calling BuildSchedGraph, each machine instruction in the current
134 /// scheduling region is mapped to an SUnit.
135 DenseMap<MachineInstr*, SUnit*> MISUnitMap;
137 /// UnitLatencies (misnamed) flag avoids computing def-use latencies, using
138 /// the def-side latency only.
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.
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;
151 typedef SparseSet<unsigned>::const_iterator const_iterator;
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(); }
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);
163 /// Returns true if the map is empty.
164 bool empty() const { return PhysRegSet.empty(); }
166 /// Clear the map without deallocating storage.
169 bool contains(unsigned Reg) const { return PhysRegSet.count(Reg); }
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");
180 /// Erase an existing element without freeing memory.
181 void erase(unsigned Reg) {
182 PhysRegSet.erase(Reg);
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.
193 /// An individual mapping from virtual register number to SUnit.
198 VReg2SUnit(unsigned reg, SUnit *su): VirtReg(reg), SU(su) {}
200 unsigned getSparseSetKey() const {
201 return TargetRegisterInfo::virtReg2Index(VirtReg);
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;
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;
217 /// LoopRegs - Track which registers are used for loop-carried dependencies.
219 LoopDependencies LoopRegs;
223 /// DbgValues - Remember instruction that preceeds DBG_VALUE.
224 typedef std::vector<std::pair<MachineInstr *, MachineInstr *> >
226 DbgValueVector DbgValues;
227 MachineInstr *FirstDbgValue;
230 explicit ScheduleDAGInstrs(MachineFunction &mf,
231 const MachineLoopInfo &mli,
232 const MachineDominatorTree &mdt,
234 LiveIntervals *LIS = 0);
236 virtual ~ScheduleDAGInstrs() {}
238 /// begin - Return an iterator to the top of the current scheduling region.
239 MachineBasicBlock::iterator begin() const { return Begin; }
241 /// end - Return an iterator to the bottom of the current scheduling region.
242 MachineBasicBlock::iterator end() const { return InsertPos; }
244 /// NewSUnit - Creates a new SUnit and return a ptr to it.
246 SUnit *NewSUnit(MachineInstr *MI) {
248 const SUnit *Addr = SUnits.empty() ? 0 : &SUnits[0];
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();
257 /// StartBlock - Prepare to perform scheduling in the given block.
259 virtual void StartBlock(MachineBasicBlock *BB);
261 /// FinishBlock - Clean up after scheduling in the given block.
263 virtual void FinishBlock();
265 /// Initialize the scheduler state for the next scheduling region.
266 virtual void enterRegion(MachineBasicBlock *bb,
267 MachineBasicBlock::iterator begin,
268 MachineBasicBlock::iterator end,
271 /// Notify that the scheduler has finished scheduling the current region.
272 virtual void exitRegion();
274 /// BuildSchedGraph - Build SUnits from the MachineBasicBlock that we are
276 void BuildSchedGraph(AliasAnalysis *AA);
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();
287 /// ComputeLatency - Compute node latency.
289 virtual void ComputeLatency(SUnit *SU);
291 /// ComputeOperandLatency - Override dependence edge latency using
292 /// operand use/def information
294 virtual void ComputeOperandLatency(SUnit *Def, SUnit *Use,
297 /// Schedule - Order nodes according to selected style, filling
298 /// in the Sequence member.
300 /// Typically, a scheduling algorithm will implement Schedule() without
301 /// overriding enterRegion() or exitRegion().
302 virtual void Schedule() = 0;
304 virtual void dumpNode(const SUnit *SU) const;
306 /// Return a label for a DAG node that points to an instruction.
307 virtual std::string getGraphNodeLabel(const SUnit *SU) const;
309 /// Return a label for the region of code covered by the DAG.
310 virtual std::string getDAGName() const;
313 SUnit *getSUnit(MachineInstr *MI) const {
314 DenseMap<MachineInstr*, SUnit*>::const_iterator I = MISUnitMap.find(MI);
315 if (I == MISUnitMap.end())
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);
326 VReg2SUnitMap::iterator findVRegDef(unsigned VirtReg) {
327 return VRegDefs.find(TargetRegisterInfo::virtReg2Index(VirtReg));