1 //===- lib/CodeGen/MachineTraceMetrics.h - Super-scalar metrics -*- 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 defines the interface for the MachineTraceMetrics analysis pass
11 // that estimates CPU resource usage and critical data dependency paths through
12 // preferred traces. This is useful for super-scalar CPUs where execution speed
13 // can be limited both by data dependencies and by limited execution resources.
15 // Out-of-order CPUs will often be executing instructions from multiple basic
16 // blocks at the same time. This makes it difficult to estimate the resource
17 // usage accurately in a single basic block. Resources can be estimated better
18 // by looking at a trace through the current basic block.
20 // For every block, the MachineTraceMetrics pass will pick a preferred trace
21 // that passes through the block. The trace is chosen based on loop structure,
22 // branch probabilities, and resource usage. The intention is to pick likely
23 // traces that would be the most affected by code transformations.
25 // It is expensive to compute a full arbitrary trace for every block, so to
26 // save some computations, traces are chosen to be convergent. This means that
27 // if the traces through basic blocks A and B ever cross when moving away from
28 // A and B, they never diverge again. This applies in both directions - If the
29 // traces meet above A and B, they won't diverge when going further back.
31 // Traces tend to align with loops. The trace through a block in an inner loop
32 // will begin at the loop entry block and end at a back edge. If there are
33 // nested loops, the trace may begin and end at those instead.
35 // For each trace, we compute the critical path length, which is the number of
36 // cycles required to execute the trace when execution is limited by data
37 // dependencies only. We also compute the resource height, which is the number
38 // of cycles required to execute all instructions in the trace when ignoring
41 // Every instruction in the current block has a slack - the number of cycles
42 // execution of the instruction can be delayed without extending the critical
45 //===----------------------------------------------------------------------===//
47 #ifndef LLVM_CODEGEN_MACHINE_TRACE_METRICS_H
48 #define LLVM_CODEGEN_MACHINE_TRACE_METRICS_H
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/DenseMap.h"
52 #include "llvm/CodeGen/MachineFunctionPass.h"
53 #include "llvm/CodeGen/TargetSchedule.h"
57 class InstrItineraryData;
58 class MachineBasicBlock;
61 class MachineLoopInfo;
62 class MachineRegisterInfo;
63 class TargetInstrInfo;
64 class TargetRegisterInfo;
67 class MachineTraceMetrics : public MachineFunctionPass {
68 const MachineFunction *MF;
69 const TargetInstrInfo *TII;
70 const TargetRegisterInfo *TRI;
71 const MachineRegisterInfo *MRI;
72 const MachineLoopInfo *Loops;
73 TargetSchedModel SchedModel;
79 MachineTraceMetrics();
80 void getAnalysisUsage(AnalysisUsage&) const;
81 bool runOnMachineFunction(MachineFunction&);
83 void verifyAnalysis() const;
85 friend class Ensemble;
88 /// Per-basic block information that doesn't depend on the trace through the
90 struct FixedBlockInfo {
91 /// The number of non-trivial instructions in the block.
92 /// Doesn't count PHI and COPY instructions that are likely to be removed.
95 /// True when the block contains calls.
98 FixedBlockInfo() : InstrCount(~0u), HasCalls(false) {}
100 /// Returns true when resource information for this block has been computed.
101 bool hasResources() const { return InstrCount != ~0u; }
103 /// Invalidate resource information.
104 void invalidate() { InstrCount = ~0u; }
107 /// Get the fixed resource information about MBB. Compute it on demand.
108 const FixedBlockInfo *getResources(const MachineBasicBlock*);
110 /// A virtual register or regunit required by a basic block or its trace
113 /// The virtual register required, or a register unit.
116 /// For virtual registers: Minimum height of the defining instruction.
117 /// For regunits: Height of the highest user in the trace.
120 LiveInReg(unsigned Reg, unsigned Height = 0) : Reg(Reg), Height(Height) {}
123 /// Per-basic block information that relates to a specific trace through the
124 /// block. Convergent traces means that only one of these is required per
125 /// block in a trace ensemble.
126 struct TraceBlockInfo {
127 /// Trace predecessor, or NULL for the first block in the trace.
128 /// Valid when hasValidDepth().
129 const MachineBasicBlock *Pred;
131 /// Trace successor, or NULL for the last block in the trace.
132 /// Valid when hasValidHeight().
133 const MachineBasicBlock *Succ;
135 /// The block number of the head of the trace. (When hasValidDepth()).
138 /// The block number of the tail of the trace. (When hasValidHeight()).
141 /// Accumulated number of instructions in the trace above this block.
142 /// Does not include instructions in this block.
145 /// Accumulated number of instructions in the trace below this block.
146 /// Includes instructions in this block.
147 unsigned InstrHeight;
151 InstrDepth(~0u), InstrHeight(~0u),
152 HasValidInstrDepths(false), HasValidInstrHeights(false) {}
154 /// Returns true if the depth resources have been computed from the trace
155 /// above this block.
156 bool hasValidDepth() const { return InstrDepth != ~0u; }
158 /// Returns true if the height resources have been computed from the trace
159 /// below this block.
160 bool hasValidHeight() const { return InstrHeight != ~0u; }
162 /// Invalidate depth resources when some block above this one has changed.
163 void invalidateDepth() { InstrDepth = ~0u; HasValidInstrDepths = false; }
165 /// Invalidate height resources when a block below this one has changed.
166 void invalidateHeight() { InstrHeight = ~0u; HasValidInstrHeights = false; }
168 /// Assuming that this is a dominator of TBI, determine if it contains
169 /// useful instruction depths. A dominating block can be above the current
170 /// trace head, and any dependencies from such a far away dominator are not
171 /// expected to affect the critical path.
173 /// Also returns true when TBI == this.
174 bool isUsefulDominator(const TraceBlockInfo &TBI) const {
175 // The trace for TBI may not even be calculated yet.
176 if (!hasValidDepth() || !TBI.hasValidDepth())
178 // Instruction depths are only comparable if the traces share a head.
179 if (Head != TBI.Head)
181 // It is almost always the case that TBI belongs to the same trace as
182 // this block, but rare convoluted cases involving irreducible control
183 // flow, a dominator may share a trace head without actually being on the
184 // same trace as TBI. This is not a big problem as long as it doesn't
185 // increase the instruction depth.
186 return HasValidInstrDepths && InstrDepth <= TBI.InstrDepth;
189 // Data-dependency-related information. Per-instruction depth and height
190 // are computed from data dependencies in the current trace, using
193 /// Instruction depths have been computed. This implies hasValidDepth().
194 bool HasValidInstrDepths;
196 /// Instruction heights have been computed. This implies hasValidHeight().
197 bool HasValidInstrHeights;
199 /// Critical path length. This is the number of cycles in the longest data
200 /// dependency chain through the trace. This is only valid when both
201 /// HasValidInstrDepths and HasValidInstrHeights are set.
202 unsigned CriticalPath;
204 /// Live-in registers. These registers are defined above the current block
205 /// and used by this block or a block below it.
206 /// This does not include PHI uses in the current block, but it does
207 /// include PHI uses in deeper blocks.
208 SmallVector<LiveInReg, 4> LiveIns;
210 void print(raw_ostream&) const;
213 /// InstrCycles represents the cycle height and depth of an instruction in a
216 /// Earliest issue cycle as determined by data dependencies and instruction
217 /// latencies from the beginning of the trace. Data dependencies from
218 /// before the trace are not included.
221 /// Minimum number of cycles from this instruction is issued to the of the
222 /// trace, as determined by data dependencies and instruction latencies.
226 /// A trace represents a plausible sequence of executed basic blocks that
227 /// passes through the current basic block one. The Trace class serves as a
228 /// handle to internal cached data structures.
233 unsigned getBlockNum() const { return &TBI - &TE.BlockInfo[0]; }
236 explicit Trace(Ensemble &te, TraceBlockInfo &tbi) : TE(te), TBI(tbi) {}
237 void print(raw_ostream&) const;
239 /// Compute the total number of instructions in the trace.
240 unsigned getInstrCount() const {
241 return TBI.InstrDepth + TBI.InstrHeight;
244 /// Return the resource depth of the top/bottom of the trace center block.
245 /// This is the number of cycles required to execute all instructions from
246 /// the trace head to the trace center block. The resource depth only
247 /// considers execution resources, it ignores data dependencies.
248 /// When Bottom is set, instructions in the trace center block are included.
249 unsigned getResourceDepth(bool Bottom) const;
251 /// Return the resource length of the trace. This is the number of cycles
252 /// required to execute the instructions in the trace if they were all
253 /// independent, exposing the maximum instruction-level parallelism.
255 /// Any blocks in Extrablocks are included as if they were part of the
257 unsigned getResourceLength(ArrayRef<const MachineBasicBlock*> Extrablocks =
258 ArrayRef<const MachineBasicBlock*>()) const;
260 /// Return the length of the (data dependency) critical path through the
262 unsigned getCriticalPath() const { return TBI.CriticalPath; }
264 /// Return the depth and height of MI. The depth is only valid for
265 /// instructions in or above the trace center block. The height is only
266 /// valid for instructions in or below the trace center block.
267 InstrCycles getInstrCycles(const MachineInstr *MI) const {
268 return TE.Cycles.lookup(MI);
271 /// Return the slack of MI. This is the number of cycles MI can be delayed
272 /// before the critical path becomes longer.
273 /// MI must be an instruction in the trace center block.
274 unsigned getInstrSlack(const MachineInstr *MI) const;
276 /// Return the Depth of a PHI instruction in a trace center block successor.
277 /// The PHI does not have to be part of the trace.
278 unsigned getPHIDepth(const MachineInstr *PHI) const;
281 /// A trace ensemble is a collection of traces selected using the same
282 /// strategy, for example 'minimum resource height'. There is one trace for
283 /// every block in the function.
285 SmallVector<TraceBlockInfo, 4> BlockInfo;
286 DenseMap<const MachineInstr*, InstrCycles> Cycles;
289 void computeTrace(const MachineBasicBlock*);
290 void computeDepthResources(const MachineBasicBlock*);
291 void computeHeightResources(const MachineBasicBlock*);
292 unsigned computeCrossBlockCriticalPath(const TraceBlockInfo&);
293 void computeInstrDepths(const MachineBasicBlock*);
294 void computeInstrHeights(const MachineBasicBlock*);
295 void addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
296 ArrayRef<const MachineBasicBlock*> Trace);
299 MachineTraceMetrics &MTM;
300 virtual const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) =0;
301 virtual const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) =0;
302 explicit Ensemble(MachineTraceMetrics*);
303 const MachineLoop *getLoopFor(const MachineBasicBlock*) const;
304 const TraceBlockInfo *getDepthResources(const MachineBasicBlock*) const;
305 const TraceBlockInfo *getHeightResources(const MachineBasicBlock*) const;
309 virtual const char *getName() const =0;
310 void print(raw_ostream&) const;
311 void invalidate(const MachineBasicBlock *MBB);
314 /// Get the trace that passes through MBB.
315 /// The trace is computed on demand.
316 Trace getTrace(const MachineBasicBlock *MBB);
319 /// Strategies for selecting traces.
321 /// Select the trace through a block that has the fewest instructions.
327 /// Get the trace ensemble representing the given trace selection strategy.
328 /// The returned Ensemble object is owned by the MachineTraceMetrics analysis,
329 /// and valid for the lifetime of the analysis pass.
330 Ensemble *getEnsemble(Strategy);
332 /// Invalidate cached information about MBB. This must be called *before* MBB
333 /// is erased, or the CFG is otherwise changed.
335 /// This invalidates per-block information about resource usage for MBB only,
336 /// and it invalidates per-trace information for any trace that passes
339 /// Call Ensemble::getTrace() again to update any trace handles.
340 void invalidate(const MachineBasicBlock *MBB);
343 // One entry per basic block, indexed by block number.
344 SmallVector<FixedBlockInfo, 4> BlockInfo;
346 // One ensemble per strategy.
347 Ensemble* Ensembles[TS_NumStrategies];
350 inline raw_ostream &operator<<(raw_ostream &OS,
351 const MachineTraceMetrics::Trace &Tr) {
356 inline raw_ostream &operator<<(raw_ostream &OS,
357 const MachineTraceMetrics::Ensemble &En) {
361 } // end namespace llvm