blob: 272a55fb944311c089f2324c59414b1aa4d7687c [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
10#define DEBUG_TYPE "early-ifcvt"
11#include "MachineTraceMetrics.h"
12#include "llvm/CodeGen/MachineBasicBlock.h"
13#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
14#include "llvm/CodeGen/MachineLoopInfo.h"
15#include "llvm/CodeGen/MachineRegisterInfo.h"
16#include "llvm/CodeGen/Passes.h"
17#include "llvm/Target/TargetInstrInfo.h"
18#include "llvm/Target/TargetRegisterInfo.h"
19#include "llvm/Support/Debug.h"
20#include "llvm/Support/raw_ostream.h"
21#include "llvm/ADT/PostOrderIterator.h"
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +000022#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000023
24using namespace llvm;
25
26char MachineTraceMetrics::ID = 0;
27char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
28
29INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
30 "machine-trace-metrics", "Machine Trace Metrics", false, true)
31INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
32INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
33INITIALIZE_PASS_END(MachineTraceMetrics,
34 "machine-trace-metrics", "Machine Trace Metrics", false, true)
35
36MachineTraceMetrics::MachineTraceMetrics()
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +000037 : MachineFunctionPass(ID), MF(0), TII(0), TRI(0), MRI(0), Loops(0) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000038 std::fill(Ensembles, array_endof(Ensembles), (Ensemble*)0);
39}
40
41void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.setPreservesAll();
43 AU.addRequired<MachineBranchProbabilityInfo>();
44 AU.addRequired<MachineLoopInfo>();
45 MachineFunctionPass::getAnalysisUsage(AU);
46}
47
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000048bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
49 MF = &Func;
50 TII = MF->getTarget().getInstrInfo();
51 TRI = MF->getTarget().getRegisterInfo();
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +000052 ItinData = MF->getTarget().getInstrItineraryData();
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000053 MRI = &MF->getRegInfo();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000054 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000055 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000056 return false;
57}
58
59void MachineTraceMetrics::releaseMemory() {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +000060 MF = 0;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000061 BlockInfo.clear();
62 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
63 delete Ensembles[i];
64 Ensembles[i] = 0;
65 }
66}
67
68//===----------------------------------------------------------------------===//
69// Fixed block information
70//===----------------------------------------------------------------------===//
71//
72// The number of instructions in a basic block and the CPU resources used by
73// those instructions don't depend on any given trace strategy.
74
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000075/// Compute the resource usage in basic block MBB.
76const MachineTraceMetrics::FixedBlockInfo*
77MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
78 assert(MBB && "No basic block");
79 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
80 if (FBI->hasResources())
81 return FBI;
82
83 // Compute resource usage in the block.
84 // FIXME: Compute per-functional unit counts.
85 FBI->HasCalls = false;
86 unsigned InstrCount = 0;
87 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
88 I != E; ++I) {
89 const MachineInstr *MI = I;
Jakob Stoklund Olesen3f63a582012-07-30 18:34:14 +000090 if (MI->isTransient())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000091 continue;
92 ++InstrCount;
93 if (MI->isCall())
94 FBI->HasCalls = true;
95 }
96 FBI->InstrCount = InstrCount;
97 return FBI;
98}
99
100//===----------------------------------------------------------------------===//
101// Ensemble utility functions
102//===----------------------------------------------------------------------===//
103
104MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000105 : MTM(*ct) {
106 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000107}
108
109// Virtual destructor serves as an anchor.
110MachineTraceMetrics::Ensemble::~Ensemble() {}
111
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000112const MachineLoop*
113MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000114 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000115}
116
117// Update resource-related information in the TraceBlockInfo for MBB.
118// Only update resources related to the trace above MBB.
119void MachineTraceMetrics::Ensemble::
120computeDepthResources(const MachineBasicBlock *MBB) {
121 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
122
123 // Compute resources from trace above. The top block is simple.
124 if (!TBI->Pred) {
125 TBI->InstrDepth = 0;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000126 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000127 return;
128 }
129
130 // Compute from the block above. A post-order traversal ensures the
131 // predecessor is always computed first.
132 TraceBlockInfo *PredTBI = &BlockInfo[TBI->Pred->getNumber()];
133 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000134 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000135 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000136 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000137}
138
139// Update resource-related information in the TraceBlockInfo for MBB.
140// Only update resources related to the trace below MBB.
141void MachineTraceMetrics::Ensemble::
142computeHeightResources(const MachineBasicBlock *MBB) {
143 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
144
145 // Compute resources for the current block.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000146 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000147
148 // The trace tail is done.
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000149 if (!TBI->Succ) {
150 TBI->Tail = MBB->getNumber();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000151 return;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000152 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000153
154 // Compute from the block below. A post-order traversal ensures the
155 // predecessor is always computed first.
156 TraceBlockInfo *SuccTBI = &BlockInfo[TBI->Succ->getNumber()];
157 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
158 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000159 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000160}
161
162// Check if depth resources for MBB are valid and return the TBI.
163// Return NULL if the resources have been invalidated.
164const MachineTraceMetrics::TraceBlockInfo*
165MachineTraceMetrics::Ensemble::
166getDepthResources(const MachineBasicBlock *MBB) const {
167 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
168 return TBI->hasValidDepth() ? TBI : 0;
169}
170
171// Check if height resources for MBB are valid and return the TBI.
172// Return NULL if the resources have been invalidated.
173const MachineTraceMetrics::TraceBlockInfo*
174MachineTraceMetrics::Ensemble::
175getHeightResources(const MachineBasicBlock *MBB) const {
176 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
177 return TBI->hasValidHeight() ? TBI : 0;
178}
179
180//===----------------------------------------------------------------------===//
181// Trace Selection Strategies
182//===----------------------------------------------------------------------===//
183//
184// A trace selection strategy is implemented as a sub-class of Ensemble. The
185// trace through a block B is computed by two DFS traversals of the CFG
186// starting from B. One upwards, and one downwards. During the upwards DFS,
187// pickTracePred() is called on the post-ordered blocks. During the downwards
188// DFS, pickTraceSucc() is called in a post-order.
189//
190
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000191// We never allow traces that leave loops, but we do allow traces to enter
192// nested loops. We also never allow traces to contain back-edges.
193//
194// This means that a loop header can never appear above the center block of a
195// trace, except as the trace head. Below the center block, loop exiting edges
196// are banned.
197//
198// Return true if an edge from the From loop to the To loop is leaving a loop.
199// Either of To and From can be null.
200static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
201 return From && !From->contains(To);
202}
203
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000204// MinInstrCountEnsemble - Pick the trace that executes the least number of
205// instructions.
206namespace {
207class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +0000208 const char *getName() const { return "MinInstr"; }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000209 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*);
210 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*);
211
212public:
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000213 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
214 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000215};
216}
217
218// Select the preferred predecessor for MBB.
219const MachineBasicBlock*
220MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
221 if (MBB->pred_empty())
222 return 0;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000223 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000224 // Don't leave loops, and never follow back-edges.
225 if (CurLoop && MBB == CurLoop->getHeader())
226 return 0;
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000227 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000228 const MachineBasicBlock *Best = 0;
229 unsigned BestDepth = 0;
230 for (MachineBasicBlock::const_pred_iterator
231 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
232 const MachineBasicBlock *Pred = *I;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000233 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
234 getDepthResources(Pred);
235 assert(PredTBI && "Predecessor must be visited first");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000236 // Pick the predecessor that would give this block the smallest InstrDepth.
237 unsigned Depth = PredTBI->InstrDepth + CurCount;
238 if (!Best || Depth < BestDepth)
239 Best = Pred, BestDepth = Depth;
240 }
241 return Best;
242}
243
244// Select the preferred successor for MBB.
245const MachineBasicBlock*
246MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
247 if (MBB->pred_empty())
248 return 0;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000249 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000250 const MachineBasicBlock *Best = 0;
251 unsigned BestHeight = 0;
252 for (MachineBasicBlock::const_succ_iterator
253 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
254 const MachineBasicBlock *Succ = *I;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000255 // Don't consider back-edges.
256 if (CurLoop && Succ == CurLoop->getHeader())
257 continue;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000258 // Don't consider successors exiting CurLoop.
259 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000260 continue;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000261 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
262 getHeightResources(Succ);
263 assert(SuccTBI && "Successor must be visited first");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000264 // Pick the successor that would give this block the smallest InstrHeight.
265 unsigned Height = SuccTBI->InstrHeight;
266 if (!Best || Height < BestHeight)
267 Best = Succ, BestHeight = Height;
268 }
269 return Best;
270}
271
272// Get an Ensemble sub-class for the requested trace strategy.
273MachineTraceMetrics::Ensemble *
274MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
275 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
276 Ensemble *&E = Ensembles[strategy];
277 if (E)
278 return E;
279
280 // Allocate new Ensemble on demand.
281 switch (strategy) {
282 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
283 default: llvm_unreachable("Invalid trace strategy enum");
284 }
285}
286
287void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
288 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
289 BlockInfo[MBB->getNumber()].invalidate();
290 for (unsigned i = 0; i != TS_NumStrategies; ++i)
291 if (Ensembles[i])
292 Ensembles[i]->invalidate(MBB);
293}
294
Jakob Stoklund Olesenef6c76c2012-07-30 20:57:50 +0000295void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +0000296 if (!MF)
297 return;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000298#ifndef NDEBUG
299 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
300 for (unsigned i = 0; i != TS_NumStrategies; ++i)
301 if (Ensembles[i])
302 Ensembles[i]->verify();
303#endif
304}
305
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000306//===----------------------------------------------------------------------===//
307// Trace building
308//===----------------------------------------------------------------------===//
309//
310// Traces are built by two CFG traversals. To avoid recomputing too much, use a
311// set abstraction that confines the search to the current loop, and doesn't
312// revisit blocks.
313
314namespace {
315struct LoopBounds {
316 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
317 const MachineLoopInfo *Loops;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000318 bool Downward;
319 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000320 const MachineLoopInfo *loops)
321 : Blocks(blocks), Loops(loops), Downward(false) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000322};
323}
324
325// Specialize po_iterator_storage in order to prune the post-order traversal so
326// it is limited to the current loop and doesn't traverse the loop back edges.
327namespace llvm {
328template<>
329class po_iterator_storage<LoopBounds, true> {
330 LoopBounds &LB;
331public:
332 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
333 void finishPostorder(const MachineBasicBlock*) {}
334
335 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
336 // Skip already visited To blocks.
337 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
338 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
339 return false;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000340 // From is null once when To is the trace center block.
341 if (!From)
342 return true;
343 const MachineLoop *FromLoop = LB.Loops->getLoopFor(From);
344 if (!FromLoop)
345 return true;
346 // Don't follow backedges, don't leave FromLoop when going upwards.
347 if ((LB.Downward ? To : From) == FromLoop->getHeader())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000348 return false;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000349 // Don't leave FromLoop.
350 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000351 return false;
352 // This is a new block. The PO traversal will compute height/depth
353 // resources, causing us to reject new edges to To. This only works because
354 // we reject back-edges, so the CFG is cycle-free.
355 return true;
356 }
357};
358}
359
360/// Compute the trace through MBB.
361void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
362 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
363 << MBB->getNumber() << '\n');
364 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000365 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000366
367 // Run an upwards post-order search for the trace start.
368 Bounds.Downward = false;
369 typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
370 for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
371 I != E; ++I) {
372 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
373 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
374 // All the predecessors have been visited, pick the preferred one.
375 TBI.Pred = pickTracePred(*I);
376 DEBUG({
377 if (TBI.Pred)
378 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
379 else
380 dbgs() << "null\n";
381 });
382 // The trace leading to I is now known, compute the depth resources.
383 computeDepthResources(*I);
384 }
385
386 // Run a downwards post-order search for the trace end.
387 Bounds.Downward = true;
388 typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
389 for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
390 I != E; ++I) {
391 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
392 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
393 // All the successors have been visited, pick the preferred one.
Jakob Stoklund Olesen0fc44862012-07-26 19:42:56 +0000394 TBI.Succ = pickTraceSucc(*I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000395 DEBUG({
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000396 if (TBI.Succ)
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000397 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
398 else
399 dbgs() << "null\n";
400 });
401 // The trace leaving I is now known, compute the height resources.
402 computeHeightResources(*I);
403 }
404}
405
406/// Invalidate traces through BadMBB.
407void
408MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
409 SmallVector<const MachineBasicBlock*, 16> WorkList;
410 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
411
412 // Invalidate height resources of blocks above MBB.
413 if (BadTBI.hasValidHeight()) {
414 BadTBI.invalidateHeight();
415 WorkList.push_back(BadMBB);
416 do {
417 const MachineBasicBlock *MBB = WorkList.pop_back_val();
418 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
419 << " height.\n");
420 // Find any MBB predecessors that have MBB as their preferred successor.
421 // They are the only ones that need to be invalidated.
422 for (MachineBasicBlock::const_pred_iterator
423 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
424 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000425 if (!TBI.hasValidHeight())
426 continue;
427 if (TBI.Succ == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000428 TBI.invalidateHeight();
429 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000430 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000431 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000432 // Verify that TBI.Succ is actually a *I successor.
433 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000434 }
435 } while (!WorkList.empty());
436 }
437
438 // Invalidate depth resources of blocks below MBB.
439 if (BadTBI.hasValidDepth()) {
440 BadTBI.invalidateDepth();
441 WorkList.push_back(BadMBB);
442 do {
443 const MachineBasicBlock *MBB = WorkList.pop_back_val();
444 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
445 << " depth.\n");
446 // Find any MBB successors that have MBB as their preferred predecessor.
447 // They are the only ones that need to be invalidated.
448 for (MachineBasicBlock::const_succ_iterator
449 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
450 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000451 if (!TBI.hasValidDepth())
452 continue;
453 if (TBI.Pred == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000454 TBI.invalidateDepth();
455 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000456 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000457 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000458 // Verify that TBI.Pred is actually a *I predecessor.
459 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000460 }
461 } while (!WorkList.empty());
462 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000463
464 // Clear any per-instruction data. We only have to do this for BadMBB itself
465 // because the instructions in that block may change. Other blocks may be
466 // invalidated, but their instructions will stay the same, so there is no
467 // need to erase the Cycle entries. They will be overwritten when we
468 // recompute.
469 for (MachineBasicBlock::const_iterator I = BadMBB->begin(), E = BadMBB->end();
470 I != E; ++I)
471 Cycles.erase(I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000472}
473
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000474void MachineTraceMetrics::Ensemble::verify() const {
475#ifndef NDEBUG
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000476 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000477 "Outdated BlockInfo size");
478 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
479 const TraceBlockInfo &TBI = BlockInfo[Num];
480 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000481 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000482 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
483 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
484 "Trace is broken, depth should have been invalidated.");
485 const MachineLoop *Loop = getLoopFor(MBB);
486 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
487 }
488 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000489 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000490 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
491 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
492 "Trace is broken, height should have been invalidated.");
493 const MachineLoop *Loop = getLoopFor(MBB);
494 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
495 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
496 "Trace contains backedge");
497 }
498 }
499#endif
500}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000501
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000502//===----------------------------------------------------------------------===//
503// Data Dependencies
504//===----------------------------------------------------------------------===//
505//
506// Compute the depth and height of each instruction based on data dependencies
507// and instruction latencies. These cycle numbers assume that the CPU can issue
508// an infinite number of instructions per cycle as long as their dependencies
509// are ready.
510
511// A data dependency is represented as a defining MI and operand numbers on the
512// defining and using MI.
513namespace {
514struct DataDep {
515 const MachineInstr *DefMI;
516 unsigned DefOp;
517 unsigned UseOp;
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000518
519 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
520 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
521
522 /// Create a DataDep from an SSA form virtual register.
523 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
524 : UseOp(UseOp) {
525 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
526 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
527 assert(!DefI.atEnd() && "Register has no defs");
528 DefMI = &*DefI;
529 DefOp = DefI.getOperandNo();
530 assert((++DefI).atEnd() && "Register has multiple defs");
531 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000532};
533}
534
535// Get the input data dependencies that must be ready before UseMI can issue.
536// Return true if UseMI has any physreg operands.
537static bool getDataDeps(const MachineInstr *UseMI,
538 SmallVectorImpl<DataDep> &Deps,
539 const MachineRegisterInfo *MRI) {
540 bool HasPhysRegs = false;
541 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
542 if (!MO->isReg())
543 continue;
544 unsigned Reg = MO->getReg();
545 if (!Reg)
546 continue;
547 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
548 HasPhysRegs = true;
549 continue;
550 }
551 // Collect virtual register reads.
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000552 if (MO->readsReg())
553 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000554 }
555 return HasPhysRegs;
556}
557
558// Get the input data dependencies of a PHI instruction, using Pred as the
559// preferred predecessor.
560// This will add at most one dependency to Deps.
561static void getPHIDeps(const MachineInstr *UseMI,
562 SmallVectorImpl<DataDep> &Deps,
563 const MachineBasicBlock *Pred,
564 const MachineRegisterInfo *MRI) {
565 // No predecessor at the beginning of a trace. Ignore dependencies.
566 if (!Pred)
567 return;
568 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
569 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
570 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
571 unsigned Reg = UseMI->getOperand(i).getReg();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000572 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000573 return;
574 }
575 }
576}
577
578// Keep track of physreg data dependencies by recording each live register unit.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000579// Associate each regunit with an instruction operand. Depending on the
580// direction instructions are scanned, it could be the operand that defined the
581// regunit, or the highest operand to read the regunit.
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000582namespace {
583struct LiveRegUnit {
584 unsigned RegUnit;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000585 unsigned Cycle;
586 const MachineInstr *MI;
587 unsigned Op;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000588
589 unsigned getSparseSetIndex() const { return RegUnit; }
590
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000591 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(0), Op(0) {}
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000592};
593}
594
595// Identify physreg dependencies for UseMI, and update the live regunit
596// tracking set when scanning instructions downwards.
597static void updatePhysDepsDownwards(const MachineInstr *UseMI,
598 SmallVectorImpl<DataDep> &Deps,
599 SparseSet<LiveRegUnit> &RegUnits,
600 const TargetRegisterInfo *TRI) {
601 SmallVector<unsigned, 8> Kills;
602 SmallVector<unsigned, 8> LiveDefOps;
603
604 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
605 if (!MO->isReg())
606 continue;
607 unsigned Reg = MO->getReg();
608 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
609 continue;
610 // Track live defs and kills for updating RegUnits.
611 if (MO->isDef()) {
612 if (MO->isDead())
613 Kills.push_back(Reg);
614 else
615 LiveDefOps.push_back(MO.getOperandNo());
616 } else if (MO->isKill())
617 Kills.push_back(Reg);
618 // Identify dependencies.
619 if (!MO->readsReg())
620 continue;
621 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
622 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
623 if (I == RegUnits.end())
624 continue;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000625 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000626 break;
627 }
628 }
629
630 // Update RegUnits to reflect live registers after UseMI.
631 // First kills.
632 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
633 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
634 RegUnits.erase(*Units);
635
636 // Second, live defs.
637 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
638 unsigned DefOp = LiveDefOps[i];
639 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
640 Units.isValid(); ++Units) {
641 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000642 LRU.MI = UseMI;
643 LRU.Op = DefOp;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000644 }
645 }
646}
647
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000648/// Compute instruction depths for all instructions above or in MBB in its
649/// trace. This assumes that the trace through MBB has already been computed.
650void MachineTraceMetrics::Ensemble::
651computeInstrDepths(const MachineBasicBlock *MBB) {
652 // The top of the trace may already be computed, and HasValidInstrDepths
653 // implies Head->HasValidInstrDepths, so we only need to start from the first
654 // block in the trace that needs to be recomputed.
655 SmallVector<const MachineBasicBlock*, 8> Stack;
656 do {
657 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
658 assert(TBI.hasValidDepth() && "Incomplete trace");
659 if (TBI.HasValidInstrDepths)
660 break;
661 Stack.push_back(MBB);
662 MBB = TBI.Pred;
663 } while (MBB);
664
665 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
666 // in the trace. We should track any live-out physregs that were defined in
667 // the trace. This is quite rare in SSA form, typically created by CSE
668 // hoisting a compare.
669 SparseSet<LiveRegUnit> RegUnits;
670 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
671
672 // Go through trace blocks in top-down order, stopping after the center block.
673 SmallVector<DataDep, 8> Deps;
674 while (!Stack.empty()) {
675 MBB = Stack.pop_back_val();
676 DEBUG(dbgs() << "Depths for BB#" << MBB->getNumber() << ":\n");
677 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
678 TBI.HasValidInstrDepths = true;
679 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
680 I != E; ++I) {
681 const MachineInstr *UseMI = I;
682
683 // Collect all data dependencies.
684 Deps.clear();
685 if (UseMI->isPHI())
686 getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
687 else if (getDataDeps(UseMI, Deps, MTM.MRI))
688 updatePhysDepsDownwards(UseMI, Deps, RegUnits, MTM.TRI);
689
690 // Filter and process dependencies, computing the earliest issue cycle.
691 unsigned Cycle = 0;
692 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
693 const DataDep &Dep = Deps[i];
694 const TraceBlockInfo&DepTBI =
695 BlockInfo[Dep.DefMI->getParent()->getNumber()];
696 // Ignore dependencies from outside the current trace.
697 if (!DepTBI.hasValidDepth() || DepTBI.Head != TBI.Head)
698 continue;
699 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
700 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
701 // Add latency if DefMI is a real instruction. Transients get latency 0.
702 if (!Dep.DefMI->isTransient())
703 DepCycle += MTM.TII->computeOperandLatency(MTM.ItinData,
704 Dep.DefMI, Dep.DefOp,
705 UseMI, Dep.UseOp,
706 /* FindMin = */ false);
707 Cycle = std::max(Cycle, DepCycle);
708 }
709 // Remember the instruction depth.
710 Cycles[UseMI].Depth = Cycle;
711 DEBUG(dbgs() << Cycle << '\t' << *UseMI);
712 }
713 }
714}
715
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000716// Identify physreg dependencies for MI when scanning instructions upwards.
717// Return the issue height of MI after considering any live regunits.
718// Height is the issue height computed from virtual register dependencies alone.
719static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
720 SparseSet<LiveRegUnit> &RegUnits,
721 const InstrItineraryData *ItinData,
722 const TargetInstrInfo *TII,
723 const TargetRegisterInfo *TRI) {
724 SmallVector<unsigned, 8> ReadOps;
725 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
726 if (!MO->isReg())
727 continue;
728 unsigned Reg = MO->getReg();
729 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
730 continue;
731 if (MO->readsReg())
732 ReadOps.push_back(MO.getOperandNo());
733 if (!MO->isDef())
734 continue;
735 // This is a def of Reg. Remove corresponding entries from RegUnits, and
736 // update MI Height to consider the physreg dependencies.
737 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
738 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
739 if (I == RegUnits.end())
740 continue;
741 unsigned DepHeight = I->Cycle;
742 if (!MI->isTransient()) {
743 // We may not know the UseMI of this dependency, if it came from the
744 // live-in list.
745 if (I->MI)
746 DepHeight += TII->computeOperandLatency(ItinData,
747 MI, MO.getOperandNo(),
748 I->MI, I->Op);
749 else
750 // No UseMI. Just use the MI latency instead.
751 DepHeight += TII->getInstrLatency(ItinData, MI);
752 }
753 Height = std::max(Height, DepHeight);
754 // This regunit is dead above MI.
755 RegUnits.erase(I);
756 }
757 }
758
759 // Now we know the height of MI. Update any regunits read.
760 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
761 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
762 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
763 LiveRegUnit &LRU = RegUnits[*Units];
764 // Set the height to the highest reader of the unit.
765 if (LRU.Cycle <= Height && LRU.MI != MI) {
766 LRU.Cycle = Height;
767 LRU.MI = MI;
768 LRU.Op = ReadOps[i];
769 }
770 }
771 }
772
773 return Height;
774}
775
776
777typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
778
779// Push the height of DefMI upwards if required to match UseMI.
780// Return true if this is the first time DefMI was seen.
781static bool pushDepHeight(const DataDep &Dep,
782 const MachineInstr *UseMI, unsigned UseHeight,
783 MIHeightMap &Heights,
784 const InstrItineraryData *ItinData,
785 const TargetInstrInfo *TII) {
786 // Adjust height by Dep.DefMI latency.
787 if (!Dep.DefMI->isTransient())
788 UseHeight += TII->computeOperandLatency(ItinData, Dep.DefMI, Dep.DefOp,
789 UseMI, Dep.UseOp);
790
791 // Update Heights[DefMI] to be the maximum height seen.
792 MIHeightMap::iterator I;
793 bool New;
794 tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
795 if (New)
796 return true;
797
798 // DefMI has been pushed before. Give it the max height.
799 if (I->second < UseHeight)
800 I->second = UseHeight;
801 return false;
802}
803
804/// Assuming that DefMI was used by Trace.back(), add it to the live-in lists
805/// of all the blocks in Trace. Stop when reaching the block that contains
806/// DefMI.
807void MachineTraceMetrics::Ensemble::
808addLiveIns(const MachineInstr *DefMI,
809 ArrayRef<const MachineBasicBlock*> Trace) {
810 assert(!Trace.empty() && "Trace should contain at least one block");
811 unsigned Reg = DefMI->getOperand(0).getReg();
812 assert(TargetRegisterInfo::isVirtualRegister(Reg));
813 const MachineBasicBlock *DefMBB = DefMI->getParent();
814
815 // Reg is live-in to all blocks in Trace that follow DefMBB.
816 for (unsigned i = Trace.size(); i; --i) {
817 const MachineBasicBlock *MBB = Trace[i-1];
818 if (MBB == DefMBB)
819 return;
820 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
821 // Just add the register. The height will be updated later.
822 TBI.LiveIns.push_back(Reg);
823 }
824}
825
826/// Compute instruction heights in the trace through MBB. This updates MBB and
827/// the blocks below it in the trace. It is assumed that the trace has already
828/// been computed.
829void MachineTraceMetrics::Ensemble::
830computeInstrHeights(const MachineBasicBlock *MBB) {
831 // The bottom of the trace may already be computed.
832 // Find the blocks that need updating.
833 SmallVector<const MachineBasicBlock*, 8> Stack;
834 do {
835 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
836 assert(TBI.hasValidHeight() && "Incomplete trace");
837 if (TBI.HasValidInstrHeights)
838 break;
839 Stack.push_back(MBB);
840 TBI.LiveIns.clear();
841 MBB = TBI.Succ;
842 } while (MBB);
843
844 // As we move upwards in the trace, keep track of instructions that are
845 // required by deeper trace instructions. Map MI -> height required so far.
846 MIHeightMap Heights;
847
848 // For physregs, the def isn't known when we see the use.
849 // Instead, keep track of the highest use of each regunit.
850 SparseSet<LiveRegUnit> RegUnits;
851 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
852
853 // If the bottom of the trace was already precomputed, initialize heights
854 // from its live-in list.
855 // MBB is the highest precomputed block in the trace.
856 if (MBB) {
857 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
858 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
859 LiveInReg LI = TBI.LiveIns[i];
860 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
861 // For virtual registers, the def latency is included.
862 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
863 if (Height < LI.Height)
864 Height = LI.Height;
865 } else {
866 // For register units, the def latency is not included because we don't
867 // know the def yet.
868 RegUnits[LI.Reg].Cycle = LI.Height;
869 }
870 }
871 }
872
873 // Go through the trace blocks in bottom-up order.
874 SmallVector<DataDep, 8> Deps;
875 for (;!Stack.empty(); Stack.pop_back()) {
876 MBB = Stack.back();
877 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
878 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
879 TBI.HasValidInstrHeights = true;
880
881 // Get dependencies from PHIs in the trace successor.
882 if (TBI.Succ) {
883 for (MachineBasicBlock::const_iterator
884 I = TBI.Succ->begin(), E = TBI.Succ->end();
885 I != E && !I->isPHI(); ++I) {
886 const MachineInstr *PHI = I;
887 Deps.clear();
888 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
889 if (!Deps.empty())
890 if (pushDepHeight(Deps.front(), PHI, Cycles.lookup(PHI).Height,
891 Heights, MTM.ItinData, MTM.TII))
892 addLiveIns(Deps.front().DefMI, Stack);
893 }
894 }
895
896 // Go through the block backwards.
897 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
898 BI != BB;) {
899 const MachineInstr *MI = --BI;
900
901 // Find the MI height as determined by virtual register uses in the
902 // trace below.
903 unsigned Cycle = 0;
904 MIHeightMap::iterator HeightI = Heights.find(MI);
905 if (HeightI != Heights.end()) {
906 Cycle = HeightI->second;
907 // We won't be seeing any more MI uses.
908 Heights.erase(HeightI);
909 }
910
911 // Don't process PHI deps. They depend on the specific predecessor, and
912 // we'll get them when visiting the predecessor.
913 Deps.clear();
914 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
915
916 // There may also be regunit dependencies to include in the height.
917 if (HasPhysRegs)
918 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
919 MTM.ItinData, MTM.TII, MTM.TRI);
920
921 DEBUG(dbgs() << Cycle << '\t' << *MI);
922 Cycles[MI].Height = Cycle;
923
924 // Update the required height of any virtual registers read by MI.
925 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
926 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.ItinData, MTM.TII))
927 addLiveIns(Deps[i].DefMI, Stack);
928 }
929
930 // Update virtual live-in heights. They were added by addLiveIns() with a 0
931 // height because the final height isn't known until now.
932 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
933 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
934 LiveInReg &LIR = TBI.LiveIns[i];
935 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
936 LIR.Height = Heights.lookup(DefMI);
937 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
938 }
939
940 // Transfer the live regunits to the live-in list.
941 for (SparseSet<LiveRegUnit>::const_iterator
942 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
943 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
944 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
945 << '@' << RI->Cycle);
946 }
947 DEBUG(dbgs() << '\n');
948 }
949}
950
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000951MachineTraceMetrics::Trace
952MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
953 // FIXME: Check cache tags, recompute as needed.
954 computeTrace(MBB);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000955 computeInstrDepths(MBB);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000956 computeInstrHeights(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000957 return Trace(*this, BlockInfo[MBB->getNumber()]);
958}
959
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +0000960void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
961 OS << getName() << " ensemble:\n";
962 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
963 OS << " BB#" << i << '\t';
964 BlockInfo[i].print(OS);
965 OS << '\n';
966 }
967}
968
969void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
970 if (hasValidDepth()) {
971 OS << "depth=" << InstrDepth;
972 if (Pred)
973 OS << " pred=BB#" << Pred->getNumber();
974 else
975 OS << " pred=null";
976 OS << " head=BB#" << Head;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000977 if (HasValidInstrDepths)
978 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +0000979 } else
980 OS << "depth invalid";
981 OS << ", ";
982 if (hasValidHeight()) {
983 OS << "height=" << InstrHeight;
984 if (Succ)
985 OS << " succ=BB#" << Succ->getNumber();
986 else
987 OS << " succ=null";
988 OS << " tail=BB#" << Tail;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000989 if (HasValidInstrHeights)
990 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +0000991 } else
992 OS << "height invalid";
993}
994
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000995void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000996 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
997
998 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
999 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001000 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1001 OS << ' ' << getInstrCount() << " instrs.";
1002
1003 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001004 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001005 while (Block->hasValidDepth() && Block->Pred) {
1006 unsigned Num = Block->Pred->getNumber();
1007 OS << " <- BB#" << Num;
1008 Block = &TE.BlockInfo[Num];
1009 }
1010
1011 Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001012 OS << "\n ";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001013 while (Block->hasValidHeight() && Block->Succ) {
1014 unsigned Num = Block->Succ->getNumber();
1015 OS << " -> BB#" << Num;
1016 Block = &TE.BlockInfo[Num];
1017 }
1018 OS << '\n';
1019}