blob: 6aa3f679628648197d062d5f598580ea8a4b96e5 [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
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000856 .computeOperandLatency(Dep.DefMI, Dep.DefOp, UseMI, Dep.UseOp);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000857 Cycle = std::max(Cycle, DepCycle);
858 }
859 // Remember the instruction depth.
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000860 InstrCycles &MICycles = Cycles[UseMI];
861 MICycles.Depth = Cycle;
862
863 if (!TBI.HasValidInstrHeights) {
864 DEBUG(dbgs() << Cycle << '\t' << *UseMI);
865 continue;
866 }
867 // Update critical path length.
868 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
869 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *UseMI);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000870 }
871 }
872}
873
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000874// Identify physreg dependencies for MI when scanning instructions upwards.
875// Return the issue height of MI after considering any live regunits.
876// Height is the issue height computed from virtual register dependencies alone.
877static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
878 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000879 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000880 const TargetInstrInfo *TII,
881 const TargetRegisterInfo *TRI) {
882 SmallVector<unsigned, 8> ReadOps;
883 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
884 if (!MO->isReg())
885 continue;
886 unsigned Reg = MO->getReg();
887 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
888 continue;
889 if (MO->readsReg())
890 ReadOps.push_back(MO.getOperandNo());
891 if (!MO->isDef())
892 continue;
893 // This is a def of Reg. Remove corresponding entries from RegUnits, and
894 // update MI Height to consider the physreg dependencies.
895 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
896 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
897 if (I == RegUnits.end())
898 continue;
899 unsigned DepHeight = I->Cycle;
900 if (!MI->isTransient()) {
901 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000902 // live-in list. SchedModel can handle a NULL UseMI.
903 DepHeight += SchedModel
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000904 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000905 }
906 Height = std::max(Height, DepHeight);
907 // This regunit is dead above MI.
908 RegUnits.erase(I);
909 }
910 }
911
912 // Now we know the height of MI. Update any regunits read.
913 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
914 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
915 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
916 LiveRegUnit &LRU = RegUnits[*Units];
917 // Set the height to the highest reader of the unit.
918 if (LRU.Cycle <= Height && LRU.MI != MI) {
919 LRU.Cycle = Height;
920 LRU.MI = MI;
921 LRU.Op = ReadOps[i];
922 }
923 }
924 }
925
926 return Height;
927}
928
929
930typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
931
932// Push the height of DefMI upwards if required to match UseMI.
933// Return true if this is the first time DefMI was seen.
934static bool pushDepHeight(const DataDep &Dep,
935 const MachineInstr *UseMI, unsigned UseHeight,
936 MIHeightMap &Heights,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000937 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000938 const TargetInstrInfo *TII) {
939 // Adjust height by Dep.DefMI latency.
940 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000941 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000942 UseMI, Dep.UseOp);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000943
944 // Update Heights[DefMI] to be the maximum height seen.
945 MIHeightMap::iterator I;
946 bool New;
947 tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
948 if (New)
949 return true;
950
951 // DefMI has been pushed before. Give it the max height.
952 if (I->second < UseHeight)
953 I->second = UseHeight;
954 return false;
955}
956
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000957/// Assuming that the virtual register defined by DefMI:DefOp was used by
958/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
959/// when reaching the block that contains DefMI.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000960void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000961addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000962 ArrayRef<const MachineBasicBlock*> Trace) {
963 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000964 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000965 assert(TargetRegisterInfo::isVirtualRegister(Reg));
966 const MachineBasicBlock *DefMBB = DefMI->getParent();
967
968 // Reg is live-in to all blocks in Trace that follow DefMBB.
969 for (unsigned i = Trace.size(); i; --i) {
970 const MachineBasicBlock *MBB = Trace[i-1];
971 if (MBB == DefMBB)
972 return;
973 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
974 // Just add the register. The height will be updated later.
975 TBI.LiveIns.push_back(Reg);
976 }
977}
978
979/// Compute instruction heights in the trace through MBB. This updates MBB and
980/// the blocks below it in the trace. It is assumed that the trace has already
981/// been computed.
982void MachineTraceMetrics::Ensemble::
983computeInstrHeights(const MachineBasicBlock *MBB) {
984 // The bottom of the trace may already be computed.
985 // Find the blocks that need updating.
986 SmallVector<const MachineBasicBlock*, 8> Stack;
987 do {
988 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
989 assert(TBI.hasValidHeight() && "Incomplete trace");
990 if (TBI.HasValidInstrHeights)
991 break;
992 Stack.push_back(MBB);
993 TBI.LiveIns.clear();
994 MBB = TBI.Succ;
995 } while (MBB);
996
997 // As we move upwards in the trace, keep track of instructions that are
998 // required by deeper trace instructions. Map MI -> height required so far.
999 MIHeightMap Heights;
1000
1001 // For physregs, the def isn't known when we see the use.
1002 // Instead, keep track of the highest use of each regunit.
1003 SparseSet<LiveRegUnit> RegUnits;
1004 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1005
1006 // If the bottom of the trace was already precomputed, initialize heights
1007 // from its live-in list.
1008 // MBB is the highest precomputed block in the trace.
1009 if (MBB) {
1010 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1011 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1012 LiveInReg LI = TBI.LiveIns[i];
1013 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1014 // For virtual registers, the def latency is included.
1015 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1016 if (Height < LI.Height)
1017 Height = LI.Height;
1018 } else {
1019 // For register units, the def latency is not included because we don't
1020 // know the def yet.
1021 RegUnits[LI.Reg].Cycle = LI.Height;
1022 }
1023 }
1024 }
1025
1026 // Go through the trace blocks in bottom-up order.
1027 SmallVector<DataDep, 8> Deps;
1028 for (;!Stack.empty(); Stack.pop_back()) {
1029 MBB = Stack.back();
1030 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1031 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1032 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001033 TBI.CriticalPath = 0;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001034
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001035 DEBUG({
1036 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1037 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1038 for (unsigned K = 0; K != PRHeights.size(); ++K)
1039 if (PRHeights[K]) {
1040 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1041 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1042 << MTM.SchedModel.getProcResource(K)->Name << " ("
1043 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1044 }
1045 });
1046
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001047 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001048 const MachineBasicBlock *Succ = TBI.Succ;
1049 // If MBB is the last block in the trace, and it has a back-edge to the
1050 // loop header, get loop-carried dependencies from PHIs in the header. For
1051 // that purpose, pretend that all the loop header PHIs have height 0.
1052 if (!Succ)
1053 if (const MachineLoop *Loop = getLoopFor(MBB))
1054 if (MBB->isSuccessor(Loop->getHeader()))
1055 Succ = Loop->getHeader();
1056
1057 if (Succ) {
1058 for (MachineBasicBlock::const_iterator I = Succ->begin(), E = Succ->end();
Jakob Stoklund Olesen7a8f3112012-08-07 18:32:57 +00001059 I != E && I->isPHI(); ++I) {
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001060 const MachineInstr *PHI = I;
1061 Deps.clear();
1062 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001063 if (!Deps.empty()) {
1064 // Loop header PHI heights are all 0.
1065 unsigned Height = TBI.Succ ? Cycles.lookup(PHI).Height : 0;
1066 DEBUG(dbgs() << "pred\t" << Height << '\t' << *PHI);
1067 if (pushDepHeight(Deps.front(), PHI, Height,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001068 Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001069 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001070 }
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001071 }
1072 }
1073
1074 // Go through the block backwards.
1075 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1076 BI != BB;) {
1077 const MachineInstr *MI = --BI;
1078
1079 // Find the MI height as determined by virtual register uses in the
1080 // trace below.
1081 unsigned Cycle = 0;
1082 MIHeightMap::iterator HeightI = Heights.find(MI);
1083 if (HeightI != Heights.end()) {
1084 Cycle = HeightI->second;
1085 // We won't be seeing any more MI uses.
1086 Heights.erase(HeightI);
1087 }
1088
1089 // Don't process PHI deps. They depend on the specific predecessor, and
1090 // we'll get them when visiting the predecessor.
1091 Deps.clear();
1092 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1093
1094 // There may also be regunit dependencies to include in the height.
1095 if (HasPhysRegs)
1096 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001097 MTM.SchedModel, MTM.TII, MTM.TRI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001098
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001099 // Update the required height of any virtual registers read by MI.
1100 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001101 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001102 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001103
1104 InstrCycles &MICycles = Cycles[MI];
1105 MICycles.Height = Cycle;
1106 if (!TBI.HasValidInstrDepths) {
1107 DEBUG(dbgs() << Cycle << '\t' << *MI);
1108 continue;
1109 }
1110 // Update critical path length.
1111 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1112 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001113 }
1114
1115 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1116 // height because the final height isn't known until now.
1117 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
1118 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1119 LiveInReg &LIR = TBI.LiveIns[i];
1120 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1121 LIR.Height = Heights.lookup(DefMI);
1122 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1123 }
1124
1125 // Transfer the live regunits to the live-in list.
1126 for (SparseSet<LiveRegUnit>::const_iterator
1127 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1128 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1129 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1130 << '@' << RI->Cycle);
1131 }
1132 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001133
1134 if (!TBI.HasValidInstrDepths)
1135 continue;
1136 // Add live-ins to the critical path length.
1137 TBI.CriticalPath = std::max(TBI.CriticalPath,
1138 computeCrossBlockCriticalPath(TBI));
1139 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001140 }
1141}
1142
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001143MachineTraceMetrics::Trace
1144MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1145 // FIXME: Check cache tags, recompute as needed.
1146 computeTrace(MBB);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001147 computeInstrDepths(MBB);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001148 computeInstrHeights(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001149 return Trace(*this, BlockInfo[MBB->getNumber()]);
1150}
1151
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001152unsigned
1153MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1154 assert(MI && "Not an instruction.");
1155 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1156 "MI must be in the trace center block");
1157 InstrCycles Cyc = getInstrCycles(MI);
1158 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1159}
1160
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001161unsigned
1162MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1163 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1164 SmallVector<DataDep, 1> Deps;
1165 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1166 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1167 DataDep &Dep = Deps.front();
1168 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1169 // Add latency if DefMI is a real instruction. Transients get latency 0.
1170 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001171 DepCycle += TE.MTM.SchedModel
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001172 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001173 return DepCycle;
1174}
1175
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001176unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001177 // Find the limiting processor resource.
1178 // Numbers have been pre-scaled to be comparable.
1179 unsigned PRMax = 0;
1180 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1181 if (Bottom) {
1182 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1183 for (unsigned K = 0; K != PRDepths.size(); ++K)
1184 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1185 } else {
1186 for (unsigned K = 0; K != PRDepths.size(); ++K)
1187 PRMax = std::max(PRMax, PRDepths[K]);
1188 }
1189 // Convert to cycle count.
1190 PRMax = TE.MTM.getCycles(PRMax);
1191
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001192 unsigned Instrs = TBI.InstrDepth;
1193 if (Bottom)
1194 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001195 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1196 Instrs /= IW;
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001197 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001198 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001199}
1200
Andrew Trick3aa53942013-04-27 03:54:20 +00001201
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001202unsigned MachineTraceMetrics::Trace::
Andrew Trick3aa53942013-04-27 03:54:20 +00001203getResourceLength(ArrayRef<const MachineBasicBlock*> Extrablocks,
1204 ArrayRef<const MCSchedClassDesc*> ExtraInstrs) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001205 // Add up resources above and below the center block.
1206 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1207 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1208 unsigned PRMax = 0;
1209 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1210 unsigned PRCycles = PRDepths[K] + PRHeights[K];
1211 for (unsigned I = 0; I != Extrablocks.size(); ++I)
1212 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
Andrew Trick3aa53942013-04-27 03:54:20 +00001213 for (unsigned I = 0; I != ExtraInstrs.size(); ++I) {
1214 const MCSchedClassDesc* SC = ExtraInstrs[I];
1215 if (!SC->isValid())
1216 continue;
1217 for (TargetSchedModel::ProcResIter
1218 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1219 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
1220 if (PI->ProcResourceIdx != K)
1221 continue;
1222 PRCycles += (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(K));
1223 }
1224 }
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001225 PRMax = std::max(PRMax, PRCycles);
1226 }
1227 // Convert to cycle count.
1228 PRMax = TE.MTM.getCycles(PRMax);
1229
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001230 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1231 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1232 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001233 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1234 Instrs /= IW;
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001235 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001236 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001237}
1238
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001239void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1240 OS << getName() << " ensemble:\n";
1241 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1242 OS << " BB#" << i << '\t';
1243 BlockInfo[i].print(OS);
1244 OS << '\n';
1245 }
1246}
1247
1248void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1249 if (hasValidDepth()) {
1250 OS << "depth=" << InstrDepth;
1251 if (Pred)
1252 OS << " pred=BB#" << Pred->getNumber();
1253 else
1254 OS << " pred=null";
1255 OS << " head=BB#" << Head;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001256 if (HasValidInstrDepths)
1257 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001258 } else
1259 OS << "depth invalid";
1260 OS << ", ";
1261 if (hasValidHeight()) {
1262 OS << "height=" << InstrHeight;
1263 if (Succ)
1264 OS << " succ=BB#" << Succ->getNumber();
1265 else
1266 OS << " succ=null";
1267 OS << " tail=BB#" << Tail;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001268 if (HasValidInstrHeights)
1269 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001270 } else
1271 OS << "height invalid";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001272 if (HasValidInstrDepths && HasValidInstrHeights)
1273 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001274}
1275
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001276void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001277 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1278
1279 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1280 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001281 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1282 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001283 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1284 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001285
1286 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001287 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001288 while (Block->hasValidDepth() && Block->Pred) {
1289 unsigned Num = Block->Pred->getNumber();
1290 OS << " <- BB#" << Num;
1291 Block = &TE.BlockInfo[Num];
1292 }
1293
1294 Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001295 OS << "\n ";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001296 while (Block->hasValidHeight() && Block->Succ) {
1297 unsigned Num = Block->Succ->getNumber();
1298 OS << " -> BB#" << Num;
1299 Block = &TE.BlockInfo[Num];
1300 }
1301 OS << '\n';
1302}