ScheduleDAGInstrs: Rework schedule graph builder.
[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 LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
16 #define LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
17
18 #include "llvm/ADT/SparseMultiSet.h"
19 #include "llvm/ADT/SparseSet.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
25 namespace llvm {
26   class MachineFrameInfo;
27   class MachineLoopInfo;
28   class MachineDominatorTree;
29   class LiveIntervals;
30   class RegPressureTracker;
31   class PressureDiffs;
32
33   /// An individual mapping from virtual register number to SUnit.
34   struct VReg2SUnit {
35     unsigned VirtReg;
36     LaneBitmask LaneMask;
37     SUnit *SU;
38
39     VReg2SUnit(unsigned VReg, LaneBitmask LaneMask, SUnit *SU)
40       : VirtReg(VReg), LaneMask(LaneMask), SU(SU) {}
41
42     unsigned getSparseSetIndex() const {
43       return TargetRegisterInfo::virtReg2Index(VirtReg);
44     }
45   };
46
47   /// Mapping from virtual register to SUnit including an operand index.
48   struct VReg2SUnitOperIdx : public VReg2SUnit {
49     unsigned OperandIndex;
50
51     VReg2SUnitOperIdx(unsigned VReg, LaneBitmask LaneMask,
52                       unsigned OperandIndex, SUnit *SU)
53       : VReg2SUnit(VReg, LaneMask, SU), OperandIndex(OperandIndex) {}
54   };
55
56   /// Record a physical register access.
57   /// For non-data-dependent uses, OpIdx == -1.
58   struct PhysRegSUOper {
59     SUnit *SU;
60     int OpIdx;
61     unsigned Reg;
62
63     PhysRegSUOper(SUnit *su, int op, unsigned R): SU(su), OpIdx(op), Reg(R) {}
64
65     unsigned getSparseSetIndex() const { return Reg; }
66   };
67
68   /// Use a SparseMultiSet to track physical registers. Storage is only
69   /// allocated once for the pass. It can be cleared in constant time and reused
70   /// without any frees.
71   typedef SparseMultiSet<PhysRegSUOper, llvm::identity<unsigned>, uint16_t>
72   Reg2SUnitsMap;
73
74   /// Use SparseSet as a SparseMap by relying on the fact that it never
75   /// compares ValueT's, only unsigned keys. This allows the set to be cleared
76   /// between scheduling regions in constant time as long as ValueT does not
77   /// require a destructor.
78   typedef SparseSet<VReg2SUnit, VirtReg2IndexFunctor> VReg2SUnitMap;
79
80   /// Track local uses of virtual registers. These uses are gathered by the DAG
81   /// builder and may be consulted by the scheduler to avoid iterating an entire
82   /// vreg use list.
83   typedef SparseMultiSet<VReg2SUnit, VirtReg2IndexFunctor> VReg2SUnitMultiMap;
84
85   typedef SparseMultiSet<VReg2SUnitOperIdx, VirtReg2IndexFunctor>
86     VReg2SUnitOperIdxMultiMap;
87
88   /// ScheduleDAGInstrs - A ScheduleDAG subclass for scheduling lists of
89   /// MachineInstrs.
90   class ScheduleDAGInstrs : public ScheduleDAG {
91   protected:
92     const MachineLoopInfo *MLI;
93     const MachineFrameInfo *MFI;
94
95     /// Live Intervals provides reaching defs in preRA scheduling.
96     LiveIntervals *LIS;
97
98     /// TargetSchedModel provides an interface to the machine model.
99     TargetSchedModel SchedModel;
100
101     /// True if the DAG builder should remove kill flags (in preparation for
102     /// rescheduling).
103     bool RemoveKillFlags;
104
105     /// The standard DAG builder does not normally include terminators as DAG
106     /// nodes because it does not create the necessary dependencies to prevent
107     /// reordering. A specialized scheduler can override
108     /// TargetInstrInfo::isSchedulingBoundary then enable this flag to indicate
109     /// it has taken responsibility for scheduling the terminator correctly.
110     bool CanHandleTerminators;
111
112     /// Whether lane masks should get tracked.
113     bool TrackLaneMasks;
114
115     /// State specific to the current scheduling region.
116     /// ------------------------------------------------
117
118     /// The block in which to insert instructions
119     MachineBasicBlock *BB;
120
121     /// The beginning of the range to be scheduled.
122     MachineBasicBlock::iterator RegionBegin;
123
124     /// The end of the range to be scheduled.
125     MachineBasicBlock::iterator RegionEnd;
126
127     /// Instructions in this region (distance(RegionBegin, RegionEnd)).
128     unsigned NumRegionInstrs;
129
130     /// After calling BuildSchedGraph, each machine instruction in the current
131     /// scheduling region is mapped to an SUnit.
132     DenseMap<MachineInstr*, SUnit*> MISUnitMap;
133
134     /// After calling BuildSchedGraph, each vreg used in the scheduling region
135     /// is mapped to a set of SUnits. These include all local vreg uses, not
136     /// just the uses for a singly defined vreg.
137     VReg2SUnitMultiMap VRegUses;
138
139     /// State internal to DAG building.
140     /// -------------------------------
141
142     /// Defs, Uses - Remember where defs and uses of each register are as we
143     /// iterate upward through the instructions. This is allocated here instead
144     /// of inside BuildSchedGraph to avoid the need for it to be initialized and
145     /// destructed for each block.
146     Reg2SUnitsMap Defs;
147     Reg2SUnitsMap Uses;
148
149     /// Tracks the last instruction(s) in this region defining each virtual
150     /// register. There may be multiple current definitions for a register with
151     /// disjunct lanemasks.
152     VReg2SUnitMultiMap CurrentVRegDefs;
153     /// Tracks the last instructions in this region using each virtual register.
154     VReg2SUnitOperIdxMultiMap CurrentVRegUses;
155
156     /// PendingLoads - Remember where unknown loads are after the most recent
157     /// unknown store, as we iterate. As with Defs and Uses, this is here
158     /// to minimize construction/destruction.
159     std::vector<SUnit *> PendingLoads;
160
161     /// DbgValues - Remember instruction that precedes DBG_VALUE.
162     /// These are generated by buildSchedGraph but persist so they can be
163     /// referenced when emitting the final schedule.
164     typedef std::vector<std::pair<MachineInstr *, MachineInstr *> >
165       DbgValueVector;
166     DbgValueVector DbgValues;
167     MachineInstr *FirstDbgValue;
168
169     /// Set of live physical registers for updating kill flags.
170     BitVector LiveRegs;
171
172   public:
173     explicit ScheduleDAGInstrs(MachineFunction &mf,
174                                const MachineLoopInfo *mli,
175                                LiveIntervals *LIS = nullptr,
176                                bool RemoveKillFlags = false);
177
178     ~ScheduleDAGInstrs() override {}
179
180     /// \brief Expose LiveIntervals for use in DAG mutators and such.
181     LiveIntervals *getLIS() const { return LIS; }
182
183     /// \brief Get the machine model for instruction scheduling.
184     const TargetSchedModel *getSchedModel() const { return &SchedModel; }
185
186     /// \brief Resolve and cache a resolved scheduling class for an SUnit.
187     const MCSchedClassDesc *getSchedClass(SUnit *SU) const {
188       if (!SU->SchedClass && SchedModel.hasInstrSchedModel())
189         SU->SchedClass = SchedModel.resolveSchedClass(SU->getInstr());
190       return SU->SchedClass;
191     }
192
193     /// begin - Return an iterator to the top of the current scheduling region.
194     MachineBasicBlock::iterator begin() const { return RegionBegin; }
195
196     /// end - Return an iterator to the bottom of the current scheduling region.
197     MachineBasicBlock::iterator end() const { return RegionEnd; }
198
199     /// newSUnit - Creates a new SUnit and return a ptr to it.
200     SUnit *newSUnit(MachineInstr *MI);
201
202     /// getSUnit - Return an existing SUnit for this MI, or NULL.
203     SUnit *getSUnit(MachineInstr *MI) const;
204
205     /// startBlock - Prepare to perform scheduling in the given block.
206     virtual void startBlock(MachineBasicBlock *BB);
207
208     /// finishBlock - Clean up after scheduling in the given block.
209     virtual void finishBlock();
210
211     /// Initialize the scheduler state for the next scheduling region.
212     virtual void enterRegion(MachineBasicBlock *bb,
213                              MachineBasicBlock::iterator begin,
214                              MachineBasicBlock::iterator end,
215                              unsigned regioninstrs);
216
217     /// Notify that the scheduler has finished scheduling the current region.
218     virtual void exitRegion();
219
220     /// buildSchedGraph - Build SUnits from the MachineBasicBlock that we are
221     /// input.
222     void buildSchedGraph(AliasAnalysis *AA,
223                          RegPressureTracker *RPTracker = nullptr,
224                          PressureDiffs *PDiffs = nullptr,
225                          bool TrackLaneMasks = false);
226
227     /// addSchedBarrierDeps - Add dependencies from instructions in the current
228     /// list of instructions being scheduled to scheduling barrier. We want to
229     /// make sure instructions which define registers that are either used by
230     /// the terminator or are live-out are properly scheduled. This is
231     /// especially important when the definition latency of the return value(s)
232     /// are too high to be hidden by the branch or when the liveout registers
233     /// used by instructions in the fallthrough block.
234     void addSchedBarrierDeps();
235
236     /// schedule - Order nodes according to selected style, filling
237     /// in the Sequence member.
238     ///
239     /// Typically, a scheduling algorithm will implement schedule() without
240     /// overriding enterRegion() or exitRegion().
241     virtual void schedule() = 0;
242
243     /// finalizeSchedule - Allow targets to perform final scheduling actions at
244     /// the level of the whole MachineFunction. By default does nothing.
245     virtual void finalizeSchedule() {}
246
247     void dumpNode(const SUnit *SU) const override;
248
249     /// Return a label for a DAG node that points to an instruction.
250     std::string getGraphNodeLabel(const SUnit *SU) const override;
251
252     /// Return a label for the region of code covered by the DAG.
253     std::string getDAGName() const override;
254
255     /// \brief Fix register kill flags that scheduling has made invalid.
256     void fixupKills(MachineBasicBlock *MBB);
257   protected:
258     void initSUnits();
259     void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx);
260     void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
261     void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
262     void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
263
264     /// \brief PostRA helper for rewriting kill flags.
265     void startBlockForKills(MachineBasicBlock *BB);
266
267     /// \brief Toggle a register operand kill flag.
268     ///
269     /// Other adjustments may be made to the instruction if necessary. Return
270     /// true if the operand has been deleted, false if not.
271     bool toggleKillFlag(MachineInstr *MI, MachineOperand &MO);
272
273     /// Returns a mask for which lanes get read/written by the given (register)
274     /// machine operand.
275     LaneBitmask getLaneMaskForMO(const MachineOperand &MO) const;
276
277     void collectVRegUses(SUnit *SU);
278   };
279
280   /// newSUnit - Creates a new SUnit and return a ptr to it.
281   inline SUnit *ScheduleDAGInstrs::newSUnit(MachineInstr *MI) {
282 #ifndef NDEBUG
283     const SUnit *Addr = SUnits.empty() ? nullptr : &SUnits[0];
284 #endif
285     SUnits.emplace_back(MI, (unsigned)SUnits.size());
286     assert((Addr == nullptr || Addr == &SUnits[0]) &&
287            "SUnits std::vector reallocated on the fly!");
288     SUnits.back().OrigNode = &SUnits.back();
289     return &SUnits.back();
290   }
291
292   /// getSUnit - Return an existing SUnit for this MI, or NULL.
293   inline SUnit *ScheduleDAGInstrs::getSUnit(MachineInstr *MI) const {
294     DenseMap<MachineInstr*, SUnit*>::const_iterator I = MISUnitMap.find(MI);
295     if (I == MISUnitMap.end())
296       return nullptr;
297     return I->second;
298   }
299 } // namespace llvm
300
301 #endif