blob: 00f702c846c5d931ed68dada29ed46df2c8c985a [file] [log] [blame]
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001//===- lib/CodeGen/MachineTraceMetrics.cpp ----------------------*- 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
Jakob Stoklund Olesena35bf502012-08-10 22:27:29 +000010#define DEBUG_TYPE "machine-trace-metrics"
Jakob Stoklund Olesen5ed625c2013-01-17 01:06:04 +000011#include "llvm/CodeGen/MachineTraceMetrics.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000012#include "llvm/ADT/PostOrderIterator.h"
13#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000014#include "llvm/CodeGen/MachineBasicBlock.h"
15#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
16#include "llvm/CodeGen/MachineLoopInfo.h"
17#include "llvm/CodeGen/MachineRegisterInfo.h"
18#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000019#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "llvm/Support/Debug.h"
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000021#include "llvm/Support/Format.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000023#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetRegisterInfo.h"
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000025#include "llvm/Target/TargetSubtargetInfo.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000026
27using namespace llvm;
28
29char MachineTraceMetrics::ID = 0;
30char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
31
32INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
33 "machine-trace-metrics", "Machine Trace Metrics", false, true)
34INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
35INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
36INITIALIZE_PASS_END(MachineTraceMetrics,
37 "machine-trace-metrics", "Machine Trace Metrics", false, true)
38
39MachineTraceMetrics::MachineTraceMetrics()
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +000040 : MachineFunctionPass(ID), MF(0), TII(0), TRI(0), MRI(0), Loops(0) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000041 std::fill(Ensembles, array_endof(Ensembles), (Ensemble*)0);
42}
43
44void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.setPreservesAll();
46 AU.addRequired<MachineBranchProbabilityInfo>();
47 AU.addRequired<MachineLoopInfo>();
48 MachineFunctionPass::getAnalysisUsage(AU);
49}
50
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000051bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
52 MF = &Func;
53 TII = MF->getTarget().getInstrInfo();
54 TRI = MF->getTarget().getRegisterInfo();
55 MRI = &MF->getRegInfo();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000056 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000057 const TargetSubtargetInfo &ST =
58 MF->getTarget().getSubtarget<TargetSubtargetInfo>();
59 SchedModel.init(*ST.getSchedModel(), &ST, TII);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000060 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000061 ProcResourceCycles.resize(MF->getNumBlockIDs() *
62 SchedModel.getNumProcResourceKinds());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000063 return false;
64}
65
66void MachineTraceMetrics::releaseMemory() {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +000067 MF = 0;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000068 BlockInfo.clear();
69 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
70 delete Ensembles[i];
71 Ensembles[i] = 0;
72 }
73}
74
75//===----------------------------------------------------------------------===//
76// Fixed block information
77//===----------------------------------------------------------------------===//
78//
79// The number of instructions in a basic block and the CPU resources used by
80// those instructions don't depend on any given trace strategy.
81
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000082/// Compute the resource usage in basic block MBB.
83const MachineTraceMetrics::FixedBlockInfo*
84MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
85 assert(MBB && "No basic block");
86 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
87 if (FBI->hasResources())
88 return FBI;
89
90 // Compute resource usage in the block.
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000091 FBI->HasCalls = false;
92 unsigned InstrCount = 0;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000093
94 // Add up per-processor resource cycles as well.
95 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
96 SmallVector<unsigned, 32> PRCycles(PRKinds);
97
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000098 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
99 I != E; ++I) {
100 const MachineInstr *MI = I;
Jakob Stoklund Olesen3f63a582012-07-30 18:34:14 +0000101 if (MI->isTransient())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000102 continue;
103 ++InstrCount;
104 if (MI->isCall())
105 FBI->HasCalls = true;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000106
107 // Count processor resources used.
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000108 if (!SchedModel.hasInstrSchedModel())
109 continue;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000110 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(MI);
111 if (!SC->isValid())
112 continue;
113
114 for (TargetSchedModel::ProcResIter
115 PI = SchedModel.getWriteProcResBegin(SC),
116 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
117 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
118 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
119 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000120 }
121 FBI->InstrCount = InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000122
123 // Scale the resource cycles so they are comparable.
124 unsigned PROffset = MBB->getNumber() * PRKinds;
125 for (unsigned K = 0; K != PRKinds; ++K)
126 ProcResourceCycles[PROffset + K] =
127 PRCycles[K] * SchedModel.getResourceFactor(K);
128
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000129 return FBI;
130}
131
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000132ArrayRef<unsigned>
133MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
134 assert(BlockInfo[MBBNum].hasResources() &&
135 "getResources() must be called before getProcResourceCycles()");
136 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000137 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
138 return ArrayRef<unsigned>(ProcResourceCycles.data() + MBBNum * PRKinds,
139 PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000140}
141
142
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000143//===----------------------------------------------------------------------===//
144// Ensemble utility functions
145//===----------------------------------------------------------------------===//
146
147MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000148 : MTM(*ct) {
149 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000150 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
151 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
152 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000153}
154
155// Virtual destructor serves as an anchor.
156MachineTraceMetrics::Ensemble::~Ensemble() {}
157
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000158const MachineLoop*
159MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000160 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000161}
162
163// Update resource-related information in the TraceBlockInfo for MBB.
164// Only update resources related to the trace above MBB.
165void MachineTraceMetrics::Ensemble::
166computeDepthResources(const MachineBasicBlock *MBB) {
167 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000168 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
169 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000170
171 // Compute resources from trace above. The top block is simple.
172 if (!TBI->Pred) {
173 TBI->InstrDepth = 0;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000174 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000175 std::fill(ProcResourceDepths.begin() + PROffset,
176 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000177 return;
178 }
179
180 // Compute from the block above. A post-order traversal ensures the
181 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000182 unsigned PredNum = TBI->Pred->getNumber();
183 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000184 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000185 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000186 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000187 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000188
189 // Compute per-resource depths.
190 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
191 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
192 for (unsigned K = 0; K != PRKinds; ++K)
193 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000194}
195
196// Update resource-related information in the TraceBlockInfo for MBB.
197// Only update resources related to the trace below MBB.
198void MachineTraceMetrics::Ensemble::
199computeHeightResources(const MachineBasicBlock *MBB) {
200 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000201 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
202 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000203
204 // Compute resources for the current block.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000205 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000206 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000207
208 // The trace tail is done.
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000209 if (!TBI->Succ) {
210 TBI->Tail = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000211 std::copy(PRCycles.begin(), PRCycles.end(),
212 ProcResourceHeights.begin() + PROffset);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000213 return;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000214 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000215
216 // Compute from the block below. A post-order traversal ensures the
217 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000218 unsigned SuccNum = TBI->Succ->getNumber();
219 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000220 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
221 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000222 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000223
224 // Compute per-resource heights.
225 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
226 for (unsigned K = 0; K != PRKinds; ++K)
227 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000228}
229
230// Check if depth resources for MBB are valid and return the TBI.
231// Return NULL if the resources have been invalidated.
232const MachineTraceMetrics::TraceBlockInfo*
233MachineTraceMetrics::Ensemble::
234getDepthResources(const MachineBasicBlock *MBB) const {
235 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
236 return TBI->hasValidDepth() ? TBI : 0;
237}
238
239// Check if height resources for MBB are valid and return the TBI.
240// Return NULL if the resources have been invalidated.
241const MachineTraceMetrics::TraceBlockInfo*
242MachineTraceMetrics::Ensemble::
243getHeightResources(const MachineBasicBlock *MBB) const {
244 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
245 return TBI->hasValidHeight() ? TBI : 0;
246}
247
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000248/// Get an array of processor resource depths for MBB. Indexed by processor
249/// resource kind, this array contains the scaled processor resources consumed
250/// by all blocks preceding MBB in its trace. It does not include instructions
251/// in MBB.
252///
253/// Compare TraceBlockInfo::InstrDepth.
254ArrayRef<unsigned>
255MachineTraceMetrics::Ensemble::
256getProcResourceDepths(unsigned MBBNum) const {
257 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000258 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
259 return ArrayRef<unsigned>(ProcResourceDepths.data() + MBBNum * PRKinds,
260 PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000261}
262
263/// Get an array of processor resource heights for MBB. Indexed by processor
264/// resource kind, this array contains the scaled processor resources consumed
265/// by this block and all blocks following it in its trace.
266///
267/// Compare TraceBlockInfo::InstrHeight.
268ArrayRef<unsigned>
269MachineTraceMetrics::Ensemble::
270getProcResourceHeights(unsigned MBBNum) const {
271 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000272 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
273 return ArrayRef<unsigned>(ProcResourceHeights.data() + MBBNum * PRKinds,
274 PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000275}
276
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000277//===----------------------------------------------------------------------===//
278// Trace Selection Strategies
279//===----------------------------------------------------------------------===//
280//
281// A trace selection strategy is implemented as a sub-class of Ensemble. The
282// trace through a block B is computed by two DFS traversals of the CFG
283// starting from B. One upwards, and one downwards. During the upwards DFS,
284// pickTracePred() is called on the post-ordered blocks. During the downwards
285// DFS, pickTraceSucc() is called in a post-order.
286//
287
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000288// We never allow traces that leave loops, but we do allow traces to enter
289// nested loops. We also never allow traces to contain back-edges.
290//
291// This means that a loop header can never appear above the center block of a
292// trace, except as the trace head. Below the center block, loop exiting edges
293// are banned.
294//
295// Return true if an edge from the From loop to the To loop is leaving a loop.
296// Either of To and From can be null.
297static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
298 return From && !From->contains(To);
299}
300
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000301// MinInstrCountEnsemble - Pick the trace that executes the least number of
302// instructions.
303namespace {
304class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +0000305 const char *getName() const { return "MinInstr"; }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000306 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*);
307 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*);
308
309public:
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000310 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
311 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000312};
313}
314
315// Select the preferred predecessor for MBB.
316const MachineBasicBlock*
317MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
318 if (MBB->pred_empty())
319 return 0;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000320 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000321 // Don't leave loops, and never follow back-edges.
322 if (CurLoop && MBB == CurLoop->getHeader())
323 return 0;
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000324 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000325 const MachineBasicBlock *Best = 0;
326 unsigned BestDepth = 0;
327 for (MachineBasicBlock::const_pred_iterator
328 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
329 const MachineBasicBlock *Pred = *I;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000330 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
331 getDepthResources(Pred);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000332 // Ignore cycles that aren't natural loops.
333 if (!PredTBI)
334 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000335 // Pick the predecessor that would give this block the smallest InstrDepth.
336 unsigned Depth = PredTBI->InstrDepth + CurCount;
337 if (!Best || Depth < BestDepth)
338 Best = Pred, BestDepth = Depth;
339 }
340 return Best;
341}
342
343// Select the preferred successor for MBB.
344const MachineBasicBlock*
345MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
346 if (MBB->pred_empty())
347 return 0;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000348 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000349 const MachineBasicBlock *Best = 0;
350 unsigned BestHeight = 0;
351 for (MachineBasicBlock::const_succ_iterator
352 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
353 const MachineBasicBlock *Succ = *I;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000354 // Don't consider back-edges.
355 if (CurLoop && Succ == CurLoop->getHeader())
356 continue;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000357 // Don't consider successors exiting CurLoop.
358 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000359 continue;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000360 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
361 getHeightResources(Succ);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000362 // Ignore cycles that aren't natural loops.
363 if (!SuccTBI)
364 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000365 // Pick the successor that would give this block the smallest InstrHeight.
366 unsigned Height = SuccTBI->InstrHeight;
367 if (!Best || Height < BestHeight)
368 Best = Succ, BestHeight = Height;
369 }
370 return Best;
371}
372
373// Get an Ensemble sub-class for the requested trace strategy.
374MachineTraceMetrics::Ensemble *
375MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
376 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
377 Ensemble *&E = Ensembles[strategy];
378 if (E)
379 return E;
380
381 // Allocate new Ensemble on demand.
382 switch (strategy) {
383 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
384 default: llvm_unreachable("Invalid trace strategy enum");
385 }
386}
387
388void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
389 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
390 BlockInfo[MBB->getNumber()].invalidate();
391 for (unsigned i = 0; i != TS_NumStrategies; ++i)
392 if (Ensembles[i])
393 Ensembles[i]->invalidate(MBB);
394}
395
Jakob Stoklund Olesenef6c76c2012-07-30 20:57:50 +0000396void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +0000397 if (!MF)
398 return;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000399#ifndef NDEBUG
400 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
401 for (unsigned i = 0; i != TS_NumStrategies; ++i)
402 if (Ensembles[i])
403 Ensembles[i]->verify();
404#endif
405}
406
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000407//===----------------------------------------------------------------------===//
408// Trace building
409//===----------------------------------------------------------------------===//
410//
411// Traces are built by two CFG traversals. To avoid recomputing too much, use a
412// set abstraction that confines the search to the current loop, and doesn't
413// revisit blocks.
414
415namespace {
416struct LoopBounds {
417 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000418 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000419 const MachineLoopInfo *Loops;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000420 bool Downward;
421 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000422 const MachineLoopInfo *loops)
423 : Blocks(blocks), Loops(loops), Downward(false) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000424};
425}
426
427// Specialize po_iterator_storage in order to prune the post-order traversal so
428// it is limited to the current loop and doesn't traverse the loop back edges.
429namespace llvm {
430template<>
431class po_iterator_storage<LoopBounds, true> {
432 LoopBounds &LB;
433public:
434 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
435 void finishPostorder(const MachineBasicBlock*) {}
436
437 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
438 // Skip already visited To blocks.
439 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
440 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
441 return false;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000442 // From is null once when To is the trace center block.
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000443 if (From) {
444 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
445 // Don't follow backedges, don't leave FromLoop when going upwards.
446 if ((LB.Downward ? To : From) == FromLoop->getHeader())
447 return false;
448 // Don't leave FromLoop.
449 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
450 return false;
451 }
452 }
453 // To is a new block. Mark the block as visited in case the CFG has cycles
454 // that MachineLoopInfo didn't recognize as a natural loop.
455 return LB.Visited.insert(To);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000456 }
457};
458}
459
460/// Compute the trace through MBB.
461void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
462 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
463 << MBB->getNumber() << '\n');
464 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000465 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000466
467 // Run an upwards post-order search for the trace start.
468 Bounds.Downward = false;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000469 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000470 typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
471 for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
472 I != E; ++I) {
473 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
474 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
475 // All the predecessors have been visited, pick the preferred one.
476 TBI.Pred = pickTracePred(*I);
477 DEBUG({
478 if (TBI.Pred)
479 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
480 else
481 dbgs() << "null\n";
482 });
483 // The trace leading to I is now known, compute the depth resources.
484 computeDepthResources(*I);
485 }
486
487 // Run a downwards post-order search for the trace end.
488 Bounds.Downward = true;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000489 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000490 typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
491 for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
492 I != E; ++I) {
493 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
494 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
495 // All the successors have been visited, pick the preferred one.
Jakob Stoklund Olesen0fc44862012-07-26 19:42:56 +0000496 TBI.Succ = pickTraceSucc(*I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000497 DEBUG({
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000498 if (TBI.Succ)
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000499 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
500 else
501 dbgs() << "null\n";
502 });
503 // The trace leaving I is now known, compute the height resources.
504 computeHeightResources(*I);
505 }
506}
507
508/// Invalidate traces through BadMBB.
509void
510MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
511 SmallVector<const MachineBasicBlock*, 16> WorkList;
512 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
513
514 // Invalidate height resources of blocks above MBB.
515 if (BadTBI.hasValidHeight()) {
516 BadTBI.invalidateHeight();
517 WorkList.push_back(BadMBB);
518 do {
519 const MachineBasicBlock *MBB = WorkList.pop_back_val();
520 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
521 << " height.\n");
522 // Find any MBB predecessors that have MBB as their preferred successor.
523 // They are the only ones that need to be invalidated.
524 for (MachineBasicBlock::const_pred_iterator
525 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
526 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000527 if (!TBI.hasValidHeight())
528 continue;
529 if (TBI.Succ == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000530 TBI.invalidateHeight();
531 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000532 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000533 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000534 // Verify that TBI.Succ is actually a *I successor.
535 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000536 }
537 } while (!WorkList.empty());
538 }
539
540 // Invalidate depth resources of blocks below MBB.
541 if (BadTBI.hasValidDepth()) {
542 BadTBI.invalidateDepth();
543 WorkList.push_back(BadMBB);
544 do {
545 const MachineBasicBlock *MBB = WorkList.pop_back_val();
546 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
547 << " depth.\n");
548 // Find any MBB successors that have MBB as their preferred predecessor.
549 // They are the only ones that need to be invalidated.
550 for (MachineBasicBlock::const_succ_iterator
551 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
552 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000553 if (!TBI.hasValidDepth())
554 continue;
555 if (TBI.Pred == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000556 TBI.invalidateDepth();
557 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000558 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000559 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000560 // Verify that TBI.Pred is actually a *I predecessor.
561 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000562 }
563 } while (!WorkList.empty());
564 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000565
566 // Clear any per-instruction data. We only have to do this for BadMBB itself
567 // because the instructions in that block may change. Other blocks may be
568 // invalidated, but their instructions will stay the same, so there is no
569 // need to erase the Cycle entries. They will be overwritten when we
570 // recompute.
571 for (MachineBasicBlock::const_iterator I = BadMBB->begin(), E = BadMBB->end();
572 I != E; ++I)
573 Cycles.erase(I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000574}
575
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000576void MachineTraceMetrics::Ensemble::verify() const {
577#ifndef NDEBUG
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000578 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000579 "Outdated BlockInfo size");
580 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
581 const TraceBlockInfo &TBI = BlockInfo[Num];
582 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000583 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000584 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
585 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
586 "Trace is broken, depth should have been invalidated.");
587 const MachineLoop *Loop = getLoopFor(MBB);
588 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
589 }
590 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000591 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000592 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
593 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
594 "Trace is broken, height should have been invalidated.");
595 const MachineLoop *Loop = getLoopFor(MBB);
596 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
597 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
598 "Trace contains backedge");
599 }
600 }
601#endif
602}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000603
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000604//===----------------------------------------------------------------------===//
605// Data Dependencies
606//===----------------------------------------------------------------------===//
607//
608// Compute the depth and height of each instruction based on data dependencies
609// and instruction latencies. These cycle numbers assume that the CPU can issue
610// an infinite number of instructions per cycle as long as their dependencies
611// are ready.
612
613// A data dependency is represented as a defining MI and operand numbers on the
614// defining and using MI.
615namespace {
616struct DataDep {
617 const MachineInstr *DefMI;
618 unsigned DefOp;
619 unsigned UseOp;
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000620
621 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
622 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
623
624 /// Create a DataDep from an SSA form virtual register.
625 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
626 : UseOp(UseOp) {
627 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
628 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
629 assert(!DefI.atEnd() && "Register has no defs");
630 DefMI = &*DefI;
631 DefOp = DefI.getOperandNo();
632 assert((++DefI).atEnd() && "Register has multiple defs");
633 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000634};
635}
636
637// Get the input data dependencies that must be ready before UseMI can issue.
638// Return true if UseMI has any physreg operands.
639static bool getDataDeps(const MachineInstr *UseMI,
640 SmallVectorImpl<DataDep> &Deps,
641 const MachineRegisterInfo *MRI) {
642 bool HasPhysRegs = false;
643 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
644 if (!MO->isReg())
645 continue;
646 unsigned Reg = MO->getReg();
647 if (!Reg)
648 continue;
649 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
650 HasPhysRegs = true;
651 continue;
652 }
653 // Collect virtual register reads.
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000654 if (MO->readsReg())
655 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000656 }
657 return HasPhysRegs;
658}
659
660// Get the input data dependencies of a PHI instruction, using Pred as the
661// preferred predecessor.
662// This will add at most one dependency to Deps.
663static void getPHIDeps(const MachineInstr *UseMI,
664 SmallVectorImpl<DataDep> &Deps,
665 const MachineBasicBlock *Pred,
666 const MachineRegisterInfo *MRI) {
667 // No predecessor at the beginning of a trace. Ignore dependencies.
668 if (!Pred)
669 return;
670 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
671 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
672 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
673 unsigned Reg = UseMI->getOperand(i).getReg();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000674 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000675 return;
676 }
677 }
678}
679
680// Keep track of physreg data dependencies by recording each live register unit.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000681// Associate each regunit with an instruction operand. Depending on the
682// direction instructions are scanned, it could be the operand that defined the
683// regunit, or the highest operand to read the regunit.
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000684namespace {
685struct LiveRegUnit {
686 unsigned RegUnit;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000687 unsigned Cycle;
688 const MachineInstr *MI;
689 unsigned Op;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000690
691 unsigned getSparseSetIndex() const { return RegUnit; }
692
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000693 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(0), Op(0) {}
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000694};
695}
696
697// Identify physreg dependencies for UseMI, and update the live regunit
698// tracking set when scanning instructions downwards.
699static void updatePhysDepsDownwards(const MachineInstr *UseMI,
700 SmallVectorImpl<DataDep> &Deps,
701 SparseSet<LiveRegUnit> &RegUnits,
702 const TargetRegisterInfo *TRI) {
703 SmallVector<unsigned, 8> Kills;
704 SmallVector<unsigned, 8> LiveDefOps;
705
706 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
707 if (!MO->isReg())
708 continue;
709 unsigned Reg = MO->getReg();
710 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
711 continue;
712 // Track live defs and kills for updating RegUnits.
713 if (MO->isDef()) {
714 if (MO->isDead())
715 Kills.push_back(Reg);
716 else
717 LiveDefOps.push_back(MO.getOperandNo());
718 } else if (MO->isKill())
719 Kills.push_back(Reg);
720 // Identify dependencies.
721 if (!MO->readsReg())
722 continue;
723 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
724 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
725 if (I == RegUnits.end())
726 continue;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000727 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000728 break;
729 }
730 }
731
732 // Update RegUnits to reflect live registers after UseMI.
733 // First kills.
734 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
735 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
736 RegUnits.erase(*Units);
737
738 // Second, live defs.
739 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
740 unsigned DefOp = LiveDefOps[i];
741 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
742 Units.isValid(); ++Units) {
743 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000744 LRU.MI = UseMI;
745 LRU.Op = DefOp;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000746 }
747 }
748}
749
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000750/// The length of the critical path through a trace is the maximum of two path
751/// lengths:
752///
753/// 1. The maximum height+depth over all instructions in the trace center block.
754///
755/// 2. The longest cross-block dependency chain. For small blocks, it is
756/// possible that the critical path through the trace doesn't include any
757/// instructions in the block.
758///
759/// This function computes the second number from the live-in list of the
760/// center block.
761unsigned MachineTraceMetrics::Ensemble::
762computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
763 assert(TBI.HasValidInstrDepths && "Missing depth info");
764 assert(TBI.HasValidInstrHeights && "Missing height info");
765 unsigned MaxLen = 0;
766 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
767 const LiveInReg &LIR = TBI.LiveIns[i];
768 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
769 continue;
770 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
771 // Ignore dependencies outside the current trace.
772 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000773 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000774 continue;
775 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
776 MaxLen = std::max(MaxLen, Len);
777 }
778 return MaxLen;
779}
780
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000781/// Compute instruction depths for all instructions above or in MBB in its
782/// trace. This assumes that the trace through MBB has already been computed.
783void MachineTraceMetrics::Ensemble::
784computeInstrDepths(const MachineBasicBlock *MBB) {
785 // The top of the trace may already be computed, and HasValidInstrDepths
786 // implies Head->HasValidInstrDepths, so we only need to start from the first
787 // block in the trace that needs to be recomputed.
788 SmallVector<const MachineBasicBlock*, 8> Stack;
789 do {
790 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
791 assert(TBI.hasValidDepth() && "Incomplete trace");
792 if (TBI.HasValidInstrDepths)
793 break;
794 Stack.push_back(MBB);
795 MBB = TBI.Pred;
796 } while (MBB);
797
798 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
799 // in the trace. We should track any live-out physregs that were defined in
800 // the trace. This is quite rare in SSA form, typically created by CSE
801 // hoisting a compare.
802 SparseSet<LiveRegUnit> RegUnits;
803 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
804
805 // Go through trace blocks in top-down order, stopping after the center block.
806 SmallVector<DataDep, 8> Deps;
807 while (!Stack.empty()) {
808 MBB = Stack.pop_back_val();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000809 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000810 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
811 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000812 TBI.CriticalPath = 0;
813
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000814 // Print out resource depths here as well.
815 DEBUG({
816 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
817 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
818 for (unsigned K = 0; K != PRDepths.size(); ++K)
819 if (PRDepths[K]) {
820 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
821 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
822 << MTM.SchedModel.getProcResource(K)->Name << " ("
823 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
824 }
825 });
826
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000827 // Also compute the critical path length through MBB when possible.
828 if (TBI.HasValidInstrHeights)
829 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
830
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000831 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
832 I != E; ++I) {
833 const MachineInstr *UseMI = I;
834
835 // Collect all data dependencies.
836 Deps.clear();
837 if (UseMI->isPHI())
838 getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
839 else if (getDataDeps(UseMI, Deps, MTM.MRI))
840 updatePhysDepsDownwards(UseMI, Deps, RegUnits, MTM.TRI);
841
842 // Filter and process dependencies, computing the earliest issue cycle.
843 unsigned Cycle = 0;
844 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
845 const DataDep &Dep = Deps[i];
846 const TraceBlockInfo&DepTBI =
847 BlockInfo[Dep.DefMI->getParent()->getNumber()];
848 // Ignore dependencies from outside the current trace.
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000849 if (!DepTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000850 continue;
851 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
852 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
853 // Add latency if DefMI is a real instruction. Transients get latency 0.
854 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000855 DepCycle += MTM.SchedModel
856 .computeOperandLatency(Dep.DefMI, Dep.DefOp, UseMI, Dep.UseOp,
857 /* FindMin = */ false);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000858 Cycle = std::max(Cycle, DepCycle);
859 }
860 // Remember the instruction depth.
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000861 InstrCycles &MICycles = Cycles[UseMI];
862 MICycles.Depth = Cycle;
863
864 if (!TBI.HasValidInstrHeights) {
865 DEBUG(dbgs() << Cycle << '\t' << *UseMI);
866 continue;
867 }
868 // Update critical path length.
869 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
870 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *UseMI);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000871 }
872 }
873}
874
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000875// Identify physreg dependencies for MI when scanning instructions upwards.
876// Return the issue height of MI after considering any live regunits.
877// Height is the issue height computed from virtual register dependencies alone.
878static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
879 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000880 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000881 const TargetInstrInfo *TII,
882 const TargetRegisterInfo *TRI) {
883 SmallVector<unsigned, 8> ReadOps;
884 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
885 if (!MO->isReg())
886 continue;
887 unsigned Reg = MO->getReg();
888 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
889 continue;
890 if (MO->readsReg())
891 ReadOps.push_back(MO.getOperandNo());
892 if (!MO->isDef())
893 continue;
894 // This is a def of Reg. Remove corresponding entries from RegUnits, and
895 // update MI Height to consider the physreg dependencies.
896 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
897 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
898 if (I == RegUnits.end())
899 continue;
900 unsigned DepHeight = I->Cycle;
901 if (!MI->isTransient()) {
902 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000903 // live-in list. SchedModel can handle a NULL UseMI.
904 DepHeight += SchedModel
905 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op,
906 /* FindMin = */ false);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000907 }
908 Height = std::max(Height, DepHeight);
909 // This regunit is dead above MI.
910 RegUnits.erase(I);
911 }
912 }
913
914 // Now we know the height of MI. Update any regunits read.
915 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
916 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
917 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
918 LiveRegUnit &LRU = RegUnits[*Units];
919 // Set the height to the highest reader of the unit.
920 if (LRU.Cycle <= Height && LRU.MI != MI) {
921 LRU.Cycle = Height;
922 LRU.MI = MI;
923 LRU.Op = ReadOps[i];
924 }
925 }
926 }
927
928 return Height;
929}
930
931
932typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
933
934// Push the height of DefMI upwards if required to match UseMI.
935// Return true if this is the first time DefMI was seen.
936static bool pushDepHeight(const DataDep &Dep,
937 const MachineInstr *UseMI, unsigned UseHeight,
938 MIHeightMap &Heights,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000939 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000940 const TargetInstrInfo *TII) {
941 // Adjust height by Dep.DefMI latency.
942 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000943 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
944 UseMI, Dep.UseOp, false);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000945
946 // Update Heights[DefMI] to be the maximum height seen.
947 MIHeightMap::iterator I;
948 bool New;
949 tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
950 if (New)
951 return true;
952
953 // DefMI has been pushed before. Give it the max height.
954 if (I->second < UseHeight)
955 I->second = UseHeight;
956 return false;
957}
958
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000959/// Assuming that the virtual register defined by DefMI:DefOp was used by
960/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
961/// when reaching the block that contains DefMI.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000962void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000963addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000964 ArrayRef<const MachineBasicBlock*> Trace) {
965 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000966 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000967 assert(TargetRegisterInfo::isVirtualRegister(Reg));
968 const MachineBasicBlock *DefMBB = DefMI->getParent();
969
970 // Reg is live-in to all blocks in Trace that follow DefMBB.
971 for (unsigned i = Trace.size(); i; --i) {
972 const MachineBasicBlock *MBB = Trace[i-1];
973 if (MBB == DefMBB)
974 return;
975 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
976 // Just add the register. The height will be updated later.
977 TBI.LiveIns.push_back(Reg);
978 }
979}
980
981/// Compute instruction heights in the trace through MBB. This updates MBB and
982/// the blocks below it in the trace. It is assumed that the trace has already
983/// been computed.
984void MachineTraceMetrics::Ensemble::
985computeInstrHeights(const MachineBasicBlock *MBB) {
986 // The bottom of the trace may already be computed.
987 // Find the blocks that need updating.
988 SmallVector<const MachineBasicBlock*, 8> Stack;
989 do {
990 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
991 assert(TBI.hasValidHeight() && "Incomplete trace");
992 if (TBI.HasValidInstrHeights)
993 break;
994 Stack.push_back(MBB);
995 TBI.LiveIns.clear();
996 MBB = TBI.Succ;
997 } while (MBB);
998
999 // As we move upwards in the trace, keep track of instructions that are
1000 // required by deeper trace instructions. Map MI -> height required so far.
1001 MIHeightMap Heights;
1002
1003 // For physregs, the def isn't known when we see the use.
1004 // Instead, keep track of the highest use of each regunit.
1005 SparseSet<LiveRegUnit> RegUnits;
1006 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1007
1008 // If the bottom of the trace was already precomputed, initialize heights
1009 // from its live-in list.
1010 // MBB is the highest precomputed block in the trace.
1011 if (MBB) {
1012 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1013 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1014 LiveInReg LI = TBI.LiveIns[i];
1015 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1016 // For virtual registers, the def latency is included.
1017 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1018 if (Height < LI.Height)
1019 Height = LI.Height;
1020 } else {
1021 // For register units, the def latency is not included because we don't
1022 // know the def yet.
1023 RegUnits[LI.Reg].Cycle = LI.Height;
1024 }
1025 }
1026 }
1027
1028 // Go through the trace blocks in bottom-up order.
1029 SmallVector<DataDep, 8> Deps;
1030 for (;!Stack.empty(); Stack.pop_back()) {
1031 MBB = Stack.back();
1032 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1033 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1034 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001035 TBI.CriticalPath = 0;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001036
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001037 DEBUG({
1038 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1039 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1040 for (unsigned K = 0; K != PRHeights.size(); ++K)
1041 if (PRHeights[K]) {
1042 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1043 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1044 << MTM.SchedModel.getProcResource(K)->Name << " ("
1045 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1046 }
1047 });
1048
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001049 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001050 const MachineBasicBlock *Succ = TBI.Succ;
1051 // If MBB is the last block in the trace, and it has a back-edge to the
1052 // loop header, get loop-carried dependencies from PHIs in the header. For
1053 // that purpose, pretend that all the loop header PHIs have height 0.
1054 if (!Succ)
1055 if (const MachineLoop *Loop = getLoopFor(MBB))
1056 if (MBB->isSuccessor(Loop->getHeader()))
1057 Succ = Loop->getHeader();
1058
1059 if (Succ) {
1060 for (MachineBasicBlock::const_iterator I = Succ->begin(), E = Succ->end();
Jakob Stoklund Olesen7a8f3112012-08-07 18:32:57 +00001061 I != E && I->isPHI(); ++I) {
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001062 const MachineInstr *PHI = I;
1063 Deps.clear();
1064 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001065 if (!Deps.empty()) {
1066 // Loop header PHI heights are all 0.
1067 unsigned Height = TBI.Succ ? Cycles.lookup(PHI).Height : 0;
1068 DEBUG(dbgs() << "pred\t" << Height << '\t' << *PHI);
1069 if (pushDepHeight(Deps.front(), PHI, Height,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001070 Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001071 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001072 }
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001073 }
1074 }
1075
1076 // Go through the block backwards.
1077 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1078 BI != BB;) {
1079 const MachineInstr *MI = --BI;
1080
1081 // Find the MI height as determined by virtual register uses in the
1082 // trace below.
1083 unsigned Cycle = 0;
1084 MIHeightMap::iterator HeightI = Heights.find(MI);
1085 if (HeightI != Heights.end()) {
1086 Cycle = HeightI->second;
1087 // We won't be seeing any more MI uses.
1088 Heights.erase(HeightI);
1089 }
1090
1091 // Don't process PHI deps. They depend on the specific predecessor, and
1092 // we'll get them when visiting the predecessor.
1093 Deps.clear();
1094 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1095
1096 // There may also be regunit dependencies to include in the height.
1097 if (HasPhysRegs)
1098 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001099 MTM.SchedModel, MTM.TII, MTM.TRI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001100
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001101 // Update the required height of any virtual registers read by MI.
1102 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001103 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001104 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001105
1106 InstrCycles &MICycles = Cycles[MI];
1107 MICycles.Height = Cycle;
1108 if (!TBI.HasValidInstrDepths) {
1109 DEBUG(dbgs() << Cycle << '\t' << *MI);
1110 continue;
1111 }
1112 // Update critical path length.
1113 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1114 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001115 }
1116
1117 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1118 // height because the final height isn't known until now.
1119 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
1120 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1121 LiveInReg &LIR = TBI.LiveIns[i];
1122 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1123 LIR.Height = Heights.lookup(DefMI);
1124 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1125 }
1126
1127 // Transfer the live regunits to the live-in list.
1128 for (SparseSet<LiveRegUnit>::const_iterator
1129 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1130 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1131 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1132 << '@' << RI->Cycle);
1133 }
1134 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001135
1136 if (!TBI.HasValidInstrDepths)
1137 continue;
1138 // Add live-ins to the critical path length.
1139 TBI.CriticalPath = std::max(TBI.CriticalPath,
1140 computeCrossBlockCriticalPath(TBI));
1141 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001142 }
1143}
1144
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001145MachineTraceMetrics::Trace
1146MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1147 // FIXME: Check cache tags, recompute as needed.
1148 computeTrace(MBB);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001149 computeInstrDepths(MBB);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001150 computeInstrHeights(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001151 return Trace(*this, BlockInfo[MBB->getNumber()]);
1152}
1153
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001154unsigned
1155MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1156 assert(MI && "Not an instruction.");
1157 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1158 "MI must be in the trace center block");
1159 InstrCycles Cyc = getInstrCycles(MI);
1160 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1161}
1162
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001163unsigned
1164MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1165 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1166 SmallVector<DataDep, 1> Deps;
1167 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1168 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1169 DataDep &Dep = Deps.front();
1170 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1171 // Add latency if DefMI is a real instruction. Transients get latency 0.
1172 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001173 DepCycle += TE.MTM.SchedModel
1174 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp, false);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001175 return DepCycle;
1176}
1177
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001178unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001179 // Find the limiting processor resource.
1180 // Numbers have been pre-scaled to be comparable.
1181 unsigned PRMax = 0;
1182 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1183 if (Bottom) {
1184 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1185 for (unsigned K = 0; K != PRDepths.size(); ++K)
1186 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1187 } else {
1188 for (unsigned K = 0; K != PRDepths.size(); ++K)
1189 PRMax = std::max(PRMax, PRDepths[K]);
1190 }
1191 // Convert to cycle count.
1192 PRMax = TE.MTM.getCycles(PRMax);
1193
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001194 unsigned Instrs = TBI.InstrDepth;
1195 if (Bottom)
1196 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001197 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1198 Instrs /= IW;
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001199 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001200 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001201}
1202
Andrew Trick3aa53942013-04-27 03:54:20 +00001203
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001204unsigned MachineTraceMetrics::Trace::
Andrew Trick3aa53942013-04-27 03:54:20 +00001205getResourceLength(ArrayRef<const MachineBasicBlock*> Extrablocks,
1206 ArrayRef<const MCSchedClassDesc*> ExtraInstrs) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001207 // Add up resources above and below the center block.
1208 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1209 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1210 unsigned PRMax = 0;
1211 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1212 unsigned PRCycles = PRDepths[K] + PRHeights[K];
1213 for (unsigned I = 0; I != Extrablocks.size(); ++I)
1214 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
Andrew Trick3aa53942013-04-27 03:54:20 +00001215 for (unsigned I = 0; I != ExtraInstrs.size(); ++I) {
1216 const MCSchedClassDesc* SC = ExtraInstrs[I];
1217 if (!SC->isValid())
1218 continue;
1219 for (TargetSchedModel::ProcResIter
1220 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1221 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
1222 if (PI->ProcResourceIdx != K)
1223 continue;
1224 PRCycles += (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(K));
1225 }
1226 }
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001227 PRMax = std::max(PRMax, PRCycles);
1228 }
1229 // Convert to cycle count.
1230 PRMax = TE.MTM.getCycles(PRMax);
1231
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001232 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1233 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1234 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001235 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1236 Instrs /= IW;
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001237 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001238 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001239}
1240
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001241void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1242 OS << getName() << " ensemble:\n";
1243 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1244 OS << " BB#" << i << '\t';
1245 BlockInfo[i].print(OS);
1246 OS << '\n';
1247 }
1248}
1249
1250void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1251 if (hasValidDepth()) {
1252 OS << "depth=" << InstrDepth;
1253 if (Pred)
1254 OS << " pred=BB#" << Pred->getNumber();
1255 else
1256 OS << " pred=null";
1257 OS << " head=BB#" << Head;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001258 if (HasValidInstrDepths)
1259 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001260 } else
1261 OS << "depth invalid";
1262 OS << ", ";
1263 if (hasValidHeight()) {
1264 OS << "height=" << InstrHeight;
1265 if (Succ)
1266 OS << " succ=BB#" << Succ->getNumber();
1267 else
1268 OS << " succ=null";
1269 OS << " tail=BB#" << Tail;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001270 if (HasValidInstrHeights)
1271 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001272 } else
1273 OS << "height invalid";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001274 if (HasValidInstrDepths && HasValidInstrHeights)
1275 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001276}
1277
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001278void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001279 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1280
1281 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1282 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001283 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1284 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001285 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1286 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001287
1288 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001289 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001290 while (Block->hasValidDepth() && Block->Pred) {
1291 unsigned Num = Block->Pred->getNumber();
1292 OS << " <- BB#" << Num;
1293 Block = &TE.BlockInfo[Num];
1294 }
1295
1296 Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001297 OS << "\n ";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001298 while (Block->hasValidHeight() && Block->Succ) {
1299 unsigned Num = Block->Succ->getNumber();
1300 OS << " -> BB#" << Num;
1301 Block = &TE.BlockInfo[Num];
1302 }
1303 OS << '\n';
1304}