1 //===- lib/CodeGen/MachineTraceMetrics.cpp ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "machine-trace-metrics"
11 #include "llvm/CodeGen/MachineTraceMetrics.h"
12 #include "llvm/ADT/PostOrderIterator.h"
13 #include "llvm/ADT/SparseSet.h"
14 #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"
19 #include "llvm/MC/MCSubtargetInfo.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetSubtargetInfo.h"
29 char MachineTraceMetrics::ID = 0;
30 char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
32 INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
33 "machine-trace-metrics", "Machine Trace Metrics", false, true)
34 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
35 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
36 INITIALIZE_PASS_END(MachineTraceMetrics,
37 "machine-trace-metrics", "Machine Trace Metrics", false, true)
39 MachineTraceMetrics::MachineTraceMetrics()
40 : MachineFunctionPass(ID), MF(nullptr), TII(nullptr), TRI(nullptr),
41 MRI(nullptr), Loops(nullptr) {
42 std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
45 void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addRequired<MachineBranchProbabilityInfo>();
48 AU.addRequired<MachineLoopInfo>();
49 MachineFunctionPass::getAnalysisUsage(AU);
52 bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
54 TII = MF->getTarget().getInstrInfo();
55 TRI = MF->getTarget().getRegisterInfo();
56 MRI = &MF->getRegInfo();
57 Loops = &getAnalysis<MachineLoopInfo>();
58 const TargetSubtargetInfo &ST =
59 MF->getTarget().getSubtarget<TargetSubtargetInfo>();
60 SchedModel.init(*ST.getSchedModel(), &ST, TII);
61 BlockInfo.resize(MF->getNumBlockIDs());
62 ProcResourceCycles.resize(MF->getNumBlockIDs() *
63 SchedModel.getNumProcResourceKinds());
67 void MachineTraceMetrics::releaseMemory() {
70 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
72 Ensembles[i] = nullptr;
76 //===----------------------------------------------------------------------===//
77 // Fixed block information
78 //===----------------------------------------------------------------------===//
80 // The number of instructions in a basic block and the CPU resources used by
81 // those instructions don't depend on any given trace strategy.
83 /// Compute the resource usage in basic block MBB.
84 const MachineTraceMetrics::FixedBlockInfo*
85 MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
86 assert(MBB && "No basic block");
87 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
88 if (FBI->hasResources())
91 // Compute resource usage in the block.
92 FBI->HasCalls = false;
93 unsigned InstrCount = 0;
95 // Add up per-processor resource cycles as well.
96 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
97 SmallVector<unsigned, 32> PRCycles(PRKinds);
99 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
101 const MachineInstr *MI = I;
102 if (MI->isTransient())
106 FBI->HasCalls = true;
108 // Count processor resources used.
109 if (!SchedModel.hasInstrSchedModel())
111 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(MI);
115 for (TargetSchedModel::ProcResIter
116 PI = SchedModel.getWriteProcResBegin(SC),
117 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
118 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
119 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
122 FBI->InstrCount = InstrCount;
124 // Scale the resource cycles so they are comparable.
125 unsigned PROffset = MBB->getNumber() * PRKinds;
126 for (unsigned K = 0; K != PRKinds; ++K)
127 ProcResourceCycles[PROffset + K] =
128 PRCycles[K] * SchedModel.getResourceFactor(K);
134 MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
135 assert(BlockInfo[MBBNum].hasResources() &&
136 "getResources() must be called before getProcResourceCycles()");
137 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
138 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
139 return ArrayRef<unsigned>(ProcResourceCycles.data() + MBBNum * PRKinds,
144 //===----------------------------------------------------------------------===//
145 // Ensemble utility functions
146 //===----------------------------------------------------------------------===//
148 MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
150 BlockInfo.resize(MTM.BlockInfo.size());
151 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
152 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
153 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
156 // Virtual destructor serves as an anchor.
157 MachineTraceMetrics::Ensemble::~Ensemble() {}
160 MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
161 return MTM.Loops->getLoopFor(MBB);
164 // Update resource-related information in the TraceBlockInfo for MBB.
165 // Only update resources related to the trace above MBB.
166 void MachineTraceMetrics::Ensemble::
167 computeDepthResources(const MachineBasicBlock *MBB) {
168 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
169 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
170 unsigned PROffset = MBB->getNumber() * PRKinds;
172 // Compute resources from trace above. The top block is simple.
175 TBI->Head = MBB->getNumber();
176 std::fill(ProcResourceDepths.begin() + PROffset,
177 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
181 // Compute from the block above. A post-order traversal ensures the
182 // predecessor is always computed first.
183 unsigned PredNum = TBI->Pred->getNumber();
184 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
185 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
186 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
187 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
188 TBI->Head = PredTBI->Head;
190 // Compute per-resource depths.
191 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
192 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
193 for (unsigned K = 0; K != PRKinds; ++K)
194 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
197 // Update resource-related information in the TraceBlockInfo for MBB.
198 // Only update resources related to the trace below MBB.
199 void MachineTraceMetrics::Ensemble::
200 computeHeightResources(const MachineBasicBlock *MBB) {
201 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
202 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
203 unsigned PROffset = MBB->getNumber() * PRKinds;
205 // Compute resources for the current block.
206 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
207 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
209 // The trace tail is done.
211 TBI->Tail = MBB->getNumber();
212 std::copy(PRCycles.begin(), PRCycles.end(),
213 ProcResourceHeights.begin() + PROffset);
217 // Compute from the block below. A post-order traversal ensures the
218 // predecessor is always computed first.
219 unsigned SuccNum = TBI->Succ->getNumber();
220 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
221 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
222 TBI->InstrHeight += SuccTBI->InstrHeight;
223 TBI->Tail = SuccTBI->Tail;
225 // Compute per-resource heights.
226 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
227 for (unsigned K = 0; K != PRKinds; ++K)
228 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
231 // Check if depth resources for MBB are valid and return the TBI.
232 // Return NULL if the resources have been invalidated.
233 const MachineTraceMetrics::TraceBlockInfo*
234 MachineTraceMetrics::Ensemble::
235 getDepthResources(const MachineBasicBlock *MBB) const {
236 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
237 return TBI->hasValidDepth() ? TBI : nullptr;
240 // Check if height resources for MBB are valid and return the TBI.
241 // Return NULL if the resources have been invalidated.
242 const MachineTraceMetrics::TraceBlockInfo*
243 MachineTraceMetrics::Ensemble::
244 getHeightResources(const MachineBasicBlock *MBB) const {
245 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
246 return TBI->hasValidHeight() ? TBI : nullptr;
249 /// Get an array of processor resource depths for MBB. Indexed by processor
250 /// resource kind, this array contains the scaled processor resources consumed
251 /// by all blocks preceding MBB in its trace. It does not include instructions
254 /// Compare TraceBlockInfo::InstrDepth.
256 MachineTraceMetrics::Ensemble::
257 getProcResourceDepths(unsigned MBBNum) const {
258 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
259 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
260 return ArrayRef<unsigned>(ProcResourceDepths.data() + MBBNum * PRKinds,
264 /// Get an array of processor resource heights for MBB. Indexed by processor
265 /// resource kind, this array contains the scaled processor resources consumed
266 /// by this block and all blocks following it in its trace.
268 /// Compare TraceBlockInfo::InstrHeight.
270 MachineTraceMetrics::Ensemble::
271 getProcResourceHeights(unsigned MBBNum) const {
272 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
273 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
274 return ArrayRef<unsigned>(ProcResourceHeights.data() + MBBNum * PRKinds,
278 //===----------------------------------------------------------------------===//
279 // Trace Selection Strategies
280 //===----------------------------------------------------------------------===//
282 // A trace selection strategy is implemented as a sub-class of Ensemble. The
283 // trace through a block B is computed by two DFS traversals of the CFG
284 // starting from B. One upwards, and one downwards. During the upwards DFS,
285 // pickTracePred() is called on the post-ordered blocks. During the downwards
286 // DFS, pickTraceSucc() is called in a post-order.
289 // We never allow traces that leave loops, but we do allow traces to enter
290 // nested loops. We also never allow traces to contain back-edges.
292 // This means that a loop header can never appear above the center block of a
293 // trace, except as the trace head. Below the center block, loop exiting edges
296 // Return true if an edge from the From loop to the To loop is leaving a loop.
297 // Either of To and From can be null.
298 static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
299 return From && !From->contains(To);
302 // MinInstrCountEnsemble - Pick the trace that executes the least number of
305 class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
306 const char *getName() const override { return "MinInstr"; }
307 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
308 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
311 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
312 : MachineTraceMetrics::Ensemble(mtm) {}
316 // Select the preferred predecessor for MBB.
317 const MachineBasicBlock*
318 MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
319 if (MBB->pred_empty())
321 const MachineLoop *CurLoop = getLoopFor(MBB);
322 // Don't leave loops, and never follow back-edges.
323 if (CurLoop && MBB == CurLoop->getHeader())
325 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
326 const MachineBasicBlock *Best = nullptr;
327 unsigned BestDepth = 0;
328 for (MachineBasicBlock::const_pred_iterator
329 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
330 const MachineBasicBlock *Pred = *I;
331 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
332 getDepthResources(Pred);
333 // Ignore cycles that aren't natural loops.
336 // Pick the predecessor that would give this block the smallest InstrDepth.
337 unsigned Depth = PredTBI->InstrDepth + CurCount;
338 if (!Best || Depth < BestDepth)
339 Best = Pred, BestDepth = Depth;
344 // Select the preferred successor for MBB.
345 const MachineBasicBlock*
346 MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
347 if (MBB->pred_empty())
349 const MachineLoop *CurLoop = getLoopFor(MBB);
350 const MachineBasicBlock *Best = nullptr;
351 unsigned BestHeight = 0;
352 for (MachineBasicBlock::const_succ_iterator
353 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
354 const MachineBasicBlock *Succ = *I;
355 // Don't consider back-edges.
356 if (CurLoop && Succ == CurLoop->getHeader())
358 // Don't consider successors exiting CurLoop.
359 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
361 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
362 getHeightResources(Succ);
363 // Ignore cycles that aren't natural loops.
366 // Pick the successor that would give this block the smallest InstrHeight.
367 unsigned Height = SuccTBI->InstrHeight;
368 if (!Best || Height < BestHeight)
369 Best = Succ, BestHeight = Height;
374 // Get an Ensemble sub-class for the requested trace strategy.
375 MachineTraceMetrics::Ensemble *
376 MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
377 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
378 Ensemble *&E = Ensembles[strategy];
382 // Allocate new Ensemble on demand.
384 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
385 default: llvm_unreachable("Invalid trace strategy enum");
389 void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
390 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
391 BlockInfo[MBB->getNumber()].invalidate();
392 for (unsigned i = 0; i != TS_NumStrategies; ++i)
394 Ensembles[i]->invalidate(MBB);
397 void MachineTraceMetrics::verifyAnalysis() const {
401 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
402 for (unsigned i = 0; i != TS_NumStrategies; ++i)
404 Ensembles[i]->verify();
408 //===----------------------------------------------------------------------===//
410 //===----------------------------------------------------------------------===//
412 // Traces are built by two CFG traversals. To avoid recomputing too much, use a
413 // set abstraction that confines the search to the current loop, and doesn't
418 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
419 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
420 const MachineLoopInfo *Loops;
422 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
423 const MachineLoopInfo *loops)
424 : Blocks(blocks), Loops(loops), Downward(false) {}
428 // Specialize po_iterator_storage in order to prune the post-order traversal so
429 // it is limited to the current loop and doesn't traverse the loop back edges.
432 class po_iterator_storage<LoopBounds, true> {
435 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
436 void finishPostorder(const MachineBasicBlock*) {}
438 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
439 // Skip already visited To blocks.
440 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
441 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
443 // From is null once when To is the trace center block.
445 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
446 // Don't follow backedges, don't leave FromLoop when going upwards.
447 if ((LB.Downward ? To : From) == FromLoop->getHeader())
449 // Don't leave FromLoop.
450 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
454 // To is a new block. Mark the block as visited in case the CFG has cycles
455 // that MachineLoopInfo didn't recognize as a natural loop.
456 return LB.Visited.insert(To);
461 /// Compute the trace through MBB.
462 void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
463 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
464 << MBB->getNumber() << '\n');
465 // Set up loop bounds for the backwards post-order traversal.
466 LoopBounds Bounds(BlockInfo, MTM.Loops);
468 // Run an upwards post-order search for the trace start.
469 Bounds.Downward = false;
470 Bounds.Visited.clear();
471 typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
472 for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
474 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
475 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
476 // All the predecessors have been visited, pick the preferred one.
477 TBI.Pred = pickTracePred(*I);
480 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
484 // The trace leading to I is now known, compute the depth resources.
485 computeDepthResources(*I);
488 // Run a downwards post-order search for the trace end.
489 Bounds.Downward = true;
490 Bounds.Visited.clear();
491 typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
492 for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
494 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
495 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
496 // All the successors have been visited, pick the preferred one.
497 TBI.Succ = pickTraceSucc(*I);
500 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
504 // The trace leaving I is now known, compute the height resources.
505 computeHeightResources(*I);
509 /// Invalidate traces through BadMBB.
511 MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
512 SmallVector<const MachineBasicBlock*, 16> WorkList;
513 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
515 // Invalidate height resources of blocks above MBB.
516 if (BadTBI.hasValidHeight()) {
517 BadTBI.invalidateHeight();
518 WorkList.push_back(BadMBB);
520 const MachineBasicBlock *MBB = WorkList.pop_back_val();
521 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
523 // Find any MBB predecessors that have MBB as their preferred successor.
524 // They are the only ones that need to be invalidated.
525 for (MachineBasicBlock::const_pred_iterator
526 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
527 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
528 if (!TBI.hasValidHeight())
530 if (TBI.Succ == MBB) {
531 TBI.invalidateHeight();
532 WorkList.push_back(*I);
535 // Verify that TBI.Succ is actually a *I successor.
536 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
538 } while (!WorkList.empty());
541 // Invalidate depth resources of blocks below MBB.
542 if (BadTBI.hasValidDepth()) {
543 BadTBI.invalidateDepth();
544 WorkList.push_back(BadMBB);
546 const MachineBasicBlock *MBB = WorkList.pop_back_val();
547 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
549 // Find any MBB successors that have MBB as their preferred predecessor.
550 // They are the only ones that need to be invalidated.
551 for (MachineBasicBlock::const_succ_iterator
552 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
553 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
554 if (!TBI.hasValidDepth())
556 if (TBI.Pred == MBB) {
557 TBI.invalidateDepth();
558 WorkList.push_back(*I);
561 // Verify that TBI.Pred is actually a *I predecessor.
562 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
564 } while (!WorkList.empty());
567 // Clear any per-instruction data. We only have to do this for BadMBB itself
568 // because the instructions in that block may change. Other blocks may be
569 // invalidated, but their instructions will stay the same, so there is no
570 // need to erase the Cycle entries. They will be overwritten when we
572 for (MachineBasicBlock::const_iterator I = BadMBB->begin(), E = BadMBB->end();
577 void MachineTraceMetrics::Ensemble::verify() const {
579 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
580 "Outdated BlockInfo size");
581 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
582 const TraceBlockInfo &TBI = BlockInfo[Num];
583 if (TBI.hasValidDepth() && TBI.Pred) {
584 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
585 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
586 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
587 "Trace is broken, depth should have been invalidated.");
588 const MachineLoop *Loop = getLoopFor(MBB);
589 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
591 if (TBI.hasValidHeight() && TBI.Succ) {
592 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
593 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
594 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
595 "Trace is broken, height should have been invalidated.");
596 const MachineLoop *Loop = getLoopFor(MBB);
597 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
598 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
599 "Trace contains backedge");
605 //===----------------------------------------------------------------------===//
607 //===----------------------------------------------------------------------===//
609 // Compute the depth and height of each instruction based on data dependencies
610 // and instruction latencies. These cycle numbers assume that the CPU can issue
611 // an infinite number of instructions per cycle as long as their dependencies
614 // A data dependency is represented as a defining MI and operand numbers on the
615 // defining and using MI.
618 const MachineInstr *DefMI;
622 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
623 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
625 /// Create a DataDep from an SSA form virtual register.
626 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
628 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
629 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
630 assert(!DefI.atEnd() && "Register has no defs");
631 DefMI = DefI->getParent();
632 DefOp = DefI.getOperandNo();
633 assert((++DefI).atEnd() && "Register has multiple defs");
638 // Get the input data dependencies that must be ready before UseMI can issue.
639 // Return true if UseMI has any physreg operands.
640 static bool getDataDeps(const MachineInstr *UseMI,
641 SmallVectorImpl<DataDep> &Deps,
642 const MachineRegisterInfo *MRI) {
643 bool HasPhysRegs = false;
644 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
647 unsigned Reg = MO->getReg();
650 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
654 // Collect virtual register reads.
656 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
661 // Get the input data dependencies of a PHI instruction, using Pred as the
662 // preferred predecessor.
663 // This will add at most one dependency to Deps.
664 static void getPHIDeps(const MachineInstr *UseMI,
665 SmallVectorImpl<DataDep> &Deps,
666 const MachineBasicBlock *Pred,
667 const MachineRegisterInfo *MRI) {
668 // No predecessor at the beginning of a trace. Ignore dependencies.
671 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
672 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
673 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
674 unsigned Reg = UseMI->getOperand(i).getReg();
675 Deps.push_back(DataDep(MRI, Reg, i));
681 // Keep track of physreg data dependencies by recording each live register unit.
682 // Associate each regunit with an instruction operand. Depending on the
683 // direction instructions are scanned, it could be the operand that defined the
684 // regunit, or the highest operand to read the regunit.
689 const MachineInstr *MI;
692 unsigned getSparseSetIndex() const { return RegUnit; }
694 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {}
698 // Identify physreg dependencies for UseMI, and update the live regunit
699 // tracking set when scanning instructions downwards.
700 static void updatePhysDepsDownwards(const MachineInstr *UseMI,
701 SmallVectorImpl<DataDep> &Deps,
702 SparseSet<LiveRegUnit> &RegUnits,
703 const TargetRegisterInfo *TRI) {
704 SmallVector<unsigned, 8> Kills;
705 SmallVector<unsigned, 8> LiveDefOps;
707 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
710 unsigned Reg = MO->getReg();
711 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
713 // Track live defs and kills for updating RegUnits.
716 Kills.push_back(Reg);
718 LiveDefOps.push_back(MO.getOperandNo());
719 } else if (MO->isKill())
720 Kills.push_back(Reg);
721 // Identify dependencies.
724 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
725 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
726 if (I == RegUnits.end())
728 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
733 // Update RegUnits to reflect live registers after UseMI.
735 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
736 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
737 RegUnits.erase(*Units);
739 // Second, live defs.
740 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
741 unsigned DefOp = LiveDefOps[i];
742 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
743 Units.isValid(); ++Units) {
744 LiveRegUnit &LRU = RegUnits[*Units];
751 /// The length of the critical path through a trace is the maximum of two path
754 /// 1. The maximum height+depth over all instructions in the trace center block.
756 /// 2. The longest cross-block dependency chain. For small blocks, it is
757 /// possible that the critical path through the trace doesn't include any
758 /// instructions in the block.
760 /// This function computes the second number from the live-in list of the
762 unsigned MachineTraceMetrics::Ensemble::
763 computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
764 assert(TBI.HasValidInstrDepths && "Missing depth info");
765 assert(TBI.HasValidInstrHeights && "Missing height info");
767 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
768 const LiveInReg &LIR = TBI.LiveIns[i];
769 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
771 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
772 // Ignore dependencies outside the current trace.
773 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
774 if (!DefTBI.isUsefulDominator(TBI))
776 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
777 MaxLen = std::max(MaxLen, Len);
782 /// Compute instruction depths for all instructions above or in MBB in its
783 /// trace. This assumes that the trace through MBB has already been computed.
784 void MachineTraceMetrics::Ensemble::
785 computeInstrDepths(const MachineBasicBlock *MBB) {
786 // The top of the trace may already be computed, and HasValidInstrDepths
787 // implies Head->HasValidInstrDepths, so we only need to start from the first
788 // block in the trace that needs to be recomputed.
789 SmallVector<const MachineBasicBlock*, 8> Stack;
791 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
792 assert(TBI.hasValidDepth() && "Incomplete trace");
793 if (TBI.HasValidInstrDepths)
795 Stack.push_back(MBB);
799 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
800 // in the trace. We should track any live-out physregs that were defined in
801 // the trace. This is quite rare in SSA form, typically created by CSE
802 // hoisting a compare.
803 SparseSet<LiveRegUnit> RegUnits;
804 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
806 // Go through trace blocks in top-down order, stopping after the center block.
807 SmallVector<DataDep, 8> Deps;
808 while (!Stack.empty()) {
809 MBB = Stack.pop_back_val();
810 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
811 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
812 TBI.HasValidInstrDepths = true;
813 TBI.CriticalPath = 0;
815 // Print out resource depths here as well.
817 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
818 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
819 for (unsigned K = 0; K != PRDepths.size(); ++K)
821 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
822 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
823 << MTM.SchedModel.getProcResource(K)->Name << " ("
824 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
828 // Also compute the critical path length through MBB when possible.
829 if (TBI.HasValidInstrHeights)
830 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
832 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
834 const MachineInstr *UseMI = I;
836 // Collect all data dependencies.
839 getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
840 else if (getDataDeps(UseMI, Deps, MTM.MRI))
841 updatePhysDepsDownwards(UseMI, Deps, RegUnits, MTM.TRI);
843 // Filter and process dependencies, computing the earliest issue cycle.
845 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
846 const DataDep &Dep = Deps[i];
847 const TraceBlockInfo&DepTBI =
848 BlockInfo[Dep.DefMI->getParent()->getNumber()];
849 // Ignore dependencies from outside the current trace.
850 if (!DepTBI.isUsefulDominator(TBI))
852 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
853 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
854 // Add latency if DefMI is a real instruction. Transients get latency 0.
855 if (!Dep.DefMI->isTransient())
856 DepCycle += MTM.SchedModel
857 .computeOperandLatency(Dep.DefMI, Dep.DefOp, UseMI, Dep.UseOp);
858 Cycle = std::max(Cycle, DepCycle);
860 // Remember the instruction depth.
861 InstrCycles &MICycles = Cycles[UseMI];
862 MICycles.Depth = Cycle;
864 if (!TBI.HasValidInstrHeights) {
865 DEBUG(dbgs() << Cycle << '\t' << *UseMI);
868 // Update critical path length.
869 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
870 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *UseMI);
875 // Identify physreg dependencies for MI when scanning instructions upwards.
876 // Return the issue height of MI after considering any live regunits.
877 // Height is the issue height computed from virtual register dependencies alone.
878 static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
879 SparseSet<LiveRegUnit> &RegUnits,
880 const TargetSchedModel &SchedModel,
881 const TargetInstrInfo *TII,
882 const TargetRegisterInfo *TRI) {
883 SmallVector<unsigned, 8> ReadOps;
884 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
887 unsigned Reg = MO->getReg();
888 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
891 ReadOps.push_back(MO.getOperandNo());
894 // This is a def of Reg. Remove corresponding entries from RegUnits, and
895 // update MI Height to consider the physreg dependencies.
896 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
897 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
898 if (I == RegUnits.end())
900 unsigned DepHeight = I->Cycle;
901 if (!MI->isTransient()) {
902 // We may not know the UseMI of this dependency, if it came from the
903 // live-in list. SchedModel can handle a NULL UseMI.
904 DepHeight += SchedModel
905 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op);
907 Height = std::max(Height, DepHeight);
908 // This regunit is dead above MI.
913 // Now we know the height of MI. Update any regunits read.
914 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
915 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
916 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
917 LiveRegUnit &LRU = RegUnits[*Units];
918 // Set the height to the highest reader of the unit.
919 if (LRU.Cycle <= Height && LRU.MI != MI) {
931 typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
933 // Push the height of DefMI upwards if required to match UseMI.
934 // Return true if this is the first time DefMI was seen.
935 static bool pushDepHeight(const DataDep &Dep,
936 const MachineInstr *UseMI, unsigned UseHeight,
937 MIHeightMap &Heights,
938 const TargetSchedModel &SchedModel,
939 const TargetInstrInfo *TII) {
940 // Adjust height by Dep.DefMI latency.
941 if (!Dep.DefMI->isTransient())
942 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
945 // Update Heights[DefMI] to be the maximum height seen.
946 MIHeightMap::iterator I;
948 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
952 // DefMI has been pushed before. Give it the max height.
953 if (I->second < UseHeight)
954 I->second = UseHeight;
958 /// Assuming that the virtual register defined by DefMI:DefOp was used by
959 /// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
960 /// when reaching the block that contains DefMI.
961 void MachineTraceMetrics::Ensemble::
962 addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
963 ArrayRef<const MachineBasicBlock*> Trace) {
964 assert(!Trace.empty() && "Trace should contain at least one block");
965 unsigned Reg = DefMI->getOperand(DefOp).getReg();
966 assert(TargetRegisterInfo::isVirtualRegister(Reg));
967 const MachineBasicBlock *DefMBB = DefMI->getParent();
969 // Reg is live-in to all blocks in Trace that follow DefMBB.
970 for (unsigned i = Trace.size(); i; --i) {
971 const MachineBasicBlock *MBB = Trace[i-1];
974 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
975 // Just add the register. The height will be updated later.
976 TBI.LiveIns.push_back(Reg);
980 /// Compute instruction heights in the trace through MBB. This updates MBB and
981 /// the blocks below it in the trace. It is assumed that the trace has already
983 void MachineTraceMetrics::Ensemble::
984 computeInstrHeights(const MachineBasicBlock *MBB) {
985 // The bottom of the trace may already be computed.
986 // Find the blocks that need updating.
987 SmallVector<const MachineBasicBlock*, 8> Stack;
989 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
990 assert(TBI.hasValidHeight() && "Incomplete trace");
991 if (TBI.HasValidInstrHeights)
993 Stack.push_back(MBB);
998 // As we move upwards in the trace, keep track of instructions that are
999 // required by deeper trace instructions. Map MI -> height required so far.
1000 MIHeightMap Heights;
1002 // For physregs, the def isn't known when we see the use.
1003 // Instead, keep track of the highest use of each regunit.
1004 SparseSet<LiveRegUnit> RegUnits;
1005 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1007 // If the bottom of the trace was already precomputed, initialize heights
1008 // from its live-in list.
1009 // MBB is the highest precomputed block in the trace.
1011 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1012 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1013 LiveInReg LI = TBI.LiveIns[i];
1014 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1015 // For virtual registers, the def latency is included.
1016 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1017 if (Height < LI.Height)
1020 // For register units, the def latency is not included because we don't
1021 // know the def yet.
1022 RegUnits[LI.Reg].Cycle = LI.Height;
1027 // Go through the trace blocks in bottom-up order.
1028 SmallVector<DataDep, 8> Deps;
1029 for (;!Stack.empty(); Stack.pop_back()) {
1031 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1032 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1033 TBI.HasValidInstrHeights = true;
1034 TBI.CriticalPath = 0;
1037 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1038 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1039 for (unsigned K = 0; K != PRHeights.size(); ++K)
1041 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1042 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1043 << MTM.SchedModel.getProcResource(K)->Name << " ("
1044 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1048 // Get dependencies from PHIs in the trace successor.
1049 const MachineBasicBlock *Succ = TBI.Succ;
1050 // If MBB is the last block in the trace, and it has a back-edge to the
1051 // loop header, get loop-carried dependencies from PHIs in the header. For
1052 // that purpose, pretend that all the loop header PHIs have height 0.
1054 if (const MachineLoop *Loop = getLoopFor(MBB))
1055 if (MBB->isSuccessor(Loop->getHeader()))
1056 Succ = Loop->getHeader();
1059 for (MachineBasicBlock::const_iterator I = Succ->begin(), E = Succ->end();
1060 I != E && I->isPHI(); ++I) {
1061 const MachineInstr *PHI = I;
1063 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
1064 if (!Deps.empty()) {
1065 // Loop header PHI heights are all 0.
1066 unsigned Height = TBI.Succ ? Cycles.lookup(PHI).Height : 0;
1067 DEBUG(dbgs() << "pred\t" << Height << '\t' << *PHI);
1068 if (pushDepHeight(Deps.front(), PHI, Height,
1069 Heights, MTM.SchedModel, MTM.TII))
1070 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
1075 // Go through the block backwards.
1076 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1078 const MachineInstr *MI = --BI;
1080 // Find the MI height as determined by virtual register uses in the
1083 MIHeightMap::iterator HeightI = Heights.find(MI);
1084 if (HeightI != Heights.end()) {
1085 Cycle = HeightI->second;
1086 // We won't be seeing any more MI uses.
1087 Heights.erase(HeightI);
1090 // Don't process PHI deps. They depend on the specific predecessor, and
1091 // we'll get them when visiting the predecessor.
1093 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1095 // There may also be regunit dependencies to include in the height.
1097 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
1098 MTM.SchedModel, MTM.TII, MTM.TRI);
1100 // Update the required height of any virtual registers read by MI.
1101 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
1102 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
1103 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
1105 InstrCycles &MICycles = Cycles[MI];
1106 MICycles.Height = Cycle;
1107 if (!TBI.HasValidInstrDepths) {
1108 DEBUG(dbgs() << Cycle << '\t' << *MI);
1111 // Update critical path length.
1112 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1113 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
1116 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1117 // height because the final height isn't known until now.
1118 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
1119 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1120 LiveInReg &LIR = TBI.LiveIns[i];
1121 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1122 LIR.Height = Heights.lookup(DefMI);
1123 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1126 // Transfer the live regunits to the live-in list.
1127 for (SparseSet<LiveRegUnit>::const_iterator
1128 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1129 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1130 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1131 << '@' << RI->Cycle);
1133 DEBUG(dbgs() << '\n');
1135 if (!TBI.HasValidInstrDepths)
1137 // Add live-ins to the critical path length.
1138 TBI.CriticalPath = std::max(TBI.CriticalPath,
1139 computeCrossBlockCriticalPath(TBI));
1140 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
1144 MachineTraceMetrics::Trace
1145 MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1146 // FIXME: Check cache tags, recompute as needed.
1148 computeInstrDepths(MBB);
1149 computeInstrHeights(MBB);
1150 return Trace(*this, BlockInfo[MBB->getNumber()]);
1154 MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1155 assert(MI && "Not an instruction.");
1156 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1157 "MI must be in the trace center block");
1158 InstrCycles Cyc = getInstrCycles(MI);
1159 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1163 MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1164 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1165 SmallVector<DataDep, 1> Deps;
1166 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1167 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1168 DataDep &Dep = Deps.front();
1169 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1170 // Add latency if DefMI is a real instruction. Transients get latency 0.
1171 if (!Dep.DefMI->isTransient())
1172 DepCycle += TE.MTM.SchedModel
1173 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp);
1177 unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
1178 // Find the limiting processor resource.
1179 // Numbers have been pre-scaled to be comparable.
1181 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1183 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1184 for (unsigned K = 0; K != PRDepths.size(); ++K)
1185 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1187 for (unsigned K = 0; K != PRDepths.size(); ++K)
1188 PRMax = std::max(PRMax, PRDepths[K]);
1190 // Convert to cycle count.
1191 PRMax = TE.MTM.getCycles(PRMax);
1193 unsigned Instrs = TBI.InstrDepth;
1195 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
1196 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1198 // Assume issue width 1 without a schedule model.
1199 return std::max(Instrs, PRMax);
1203 unsigned MachineTraceMetrics::Trace::
1204 getResourceLength(ArrayRef<const MachineBasicBlock*> Extrablocks,
1205 ArrayRef<const MCSchedClassDesc*> ExtraInstrs) const {
1206 // Add up resources above and below the center block.
1207 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1208 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1210 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1211 unsigned PRCycles = PRDepths[K] + PRHeights[K];
1212 for (unsigned I = 0; I != Extrablocks.size(); ++I)
1213 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
1214 for (unsigned I = 0; I != ExtraInstrs.size(); ++I) {
1215 const MCSchedClassDesc* SC = ExtraInstrs[I];
1218 for (TargetSchedModel::ProcResIter
1219 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1220 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
1221 if (PI->ProcResourceIdx != K)
1223 PRCycles += (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(K));
1226 PRMax = std::max(PRMax, PRCycles);
1228 // Convert to cycle count.
1229 PRMax = TE.MTM.getCycles(PRMax);
1231 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1232 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1233 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
1234 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1236 // Assume issue width 1 without a schedule model.
1237 return std::max(Instrs, PRMax);
1240 void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1241 OS << getName() << " ensemble:\n";
1242 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1243 OS << " BB#" << i << '\t';
1244 BlockInfo[i].print(OS);
1249 void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1250 if (hasValidDepth()) {
1251 OS << "depth=" << InstrDepth;
1253 OS << " pred=BB#" << Pred->getNumber();
1256 OS << " head=BB#" << Head;
1257 if (HasValidInstrDepths)
1260 OS << "depth invalid";
1262 if (hasValidHeight()) {
1263 OS << "height=" << InstrHeight;
1265 OS << " succ=BB#" << Succ->getNumber();
1268 OS << " tail=BB#" << Tail;
1269 if (HasValidInstrHeights)
1272 OS << "height invalid";
1273 if (HasValidInstrDepths && HasValidInstrHeights)
1274 OS << ", crit=" << CriticalPath;
1277 void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
1278 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1280 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1281 << " --> BB#" << TBI.Tail << ':';
1282 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1283 OS << ' ' << getInstrCount() << " instrs.";
1284 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1285 OS << ' ' << TBI.CriticalPath << " cycles.";
1287 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
1288 OS << "\nBB#" << MBBNum;
1289 while (Block->hasValidDepth() && Block->Pred) {
1290 unsigned Num = Block->Pred->getNumber();
1291 OS << " <- BB#" << Num;
1292 Block = &TE.BlockInfo[Num];
1297 while (Block->hasValidHeight() && Block->Succ) {
1298 unsigned Num = Block->Succ->getNumber();
1299 OS << " -> BB#" << Num;
1300 Block = &TE.BlockInfo[Num];