xref: /llvm-project/llvm/lib/CodeGen/MachineTraceMetrics.cpp (revision 3ca14772d0c3d50e5b8b32fd405ebc0b571d1ab2)
1 //===- 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 "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"
26 
27 using namespace llvm;
28 
29 char MachineTraceMetrics::ID = 0;
30 char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
31 
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)
38 
39 MachineTraceMetrics::MachineTraceMetrics()
40   : MachineFunctionPass(ID), MF(0), TII(0), TRI(0), MRI(0), Loops(0) {
41   std::fill(Ensembles, array_endof(Ensembles), (Ensemble*)0);
42 }
43 
44 void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
45   AU.setPreservesAll();
46   AU.addRequired<MachineBranchProbabilityInfo>();
47   AU.addRequired<MachineLoopInfo>();
48   MachineFunctionPass::getAnalysisUsage(AU);
49 }
50 
51 bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
52   MF = &Func;
53   TII = MF->getTarget().getInstrInfo();
54   TRI = MF->getTarget().getRegisterInfo();
55   MRI = &MF->getRegInfo();
56   Loops = &getAnalysis<MachineLoopInfo>();
57   const TargetSubtargetInfo &ST =
58     MF->getTarget().getSubtarget<TargetSubtargetInfo>();
59   SchedModel.init(*ST.getSchedModel(), &ST, TII);
60   BlockInfo.resize(MF->getNumBlockIDs());
61   ProcResourceCycles.resize(MF->getNumBlockIDs() *
62                             SchedModel.getNumProcResourceKinds());
63   return false;
64 }
65 
66 void MachineTraceMetrics::releaseMemory() {
67   MF = 0;
68   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 
82 /// Compute the resource usage in basic block MBB.
83 const MachineTraceMetrics::FixedBlockInfo*
84 MachineTraceMetrics::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.
91   FBI->HasCalls = false;
92   unsigned InstrCount = 0;
93 
94   // Add up per-processor resource cycles as well.
95   unsigned PRKinds = SchedModel.getNumProcResourceKinds();
96   SmallVector<unsigned, 32> PRCycles(PRKinds);
97 
98   for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
99        I != E; ++I) {
100     const MachineInstr *MI = I;
101     if (MI->isTransient())
102       continue;
103     ++InstrCount;
104     if (MI->isCall())
105       FBI->HasCalls = true;
106 
107     // Count processor resources used.
108     const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(MI);
109     if (!SC->isValid())
110       continue;
111 
112     for (TargetSchedModel::ProcResIter
113          PI = SchedModel.getWriteProcResBegin(SC),
114          PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
115       assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
116       PRCycles[PI->ProcResourceIdx] += PI->Cycles;
117     }
118   }
119   FBI->InstrCount = InstrCount;
120 
121   // Scale the resource cycles so they are comparable.
122   unsigned PROffset = MBB->getNumber() * PRKinds;
123   for (unsigned K = 0; K != PRKinds; ++K)
124     ProcResourceCycles[PROffset + K] =
125       PRCycles[K] * SchedModel.getResourceFactor(K);
126 
127   return FBI;
128 }
129 
130 ArrayRef<unsigned>
131 MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
132   assert(BlockInfo[MBBNum].hasResources() &&
133          "getResources() must be called before getProcResourceCycles()");
134   unsigned PRKinds = SchedModel.getNumProcResourceKinds();
135   return ArrayRef<unsigned>(&ProcResourceCycles[MBBNum * PRKinds], PRKinds);
136 }
137 
138 
139 //===----------------------------------------------------------------------===//
140 //                         Ensemble utility functions
141 //===----------------------------------------------------------------------===//
142 
143 MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
144   : MTM(*ct) {
145   BlockInfo.resize(MTM.BlockInfo.size());
146   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
147   ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
148   ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
149 }
150 
151 // Virtual destructor serves as an anchor.
152 MachineTraceMetrics::Ensemble::~Ensemble() {}
153 
154 const MachineLoop*
155 MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
156   return MTM.Loops->getLoopFor(MBB);
157 }
158 
159 // Update resource-related information in the TraceBlockInfo for MBB.
160 // Only update resources related to the trace above MBB.
161 void MachineTraceMetrics::Ensemble::
162 computeDepthResources(const MachineBasicBlock *MBB) {
163   TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
164   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
165   unsigned PROffset = MBB->getNumber() * PRKinds;
166 
167   // Compute resources from trace above. The top block is simple.
168   if (!TBI->Pred) {
169     TBI->InstrDepth = 0;
170     TBI->Head = MBB->getNumber();
171     std::fill(ProcResourceDepths.begin() + PROffset,
172               ProcResourceDepths.begin() + PROffset + PRKinds, 0);
173     return;
174   }
175 
176   // Compute from the block above. A post-order traversal ensures the
177   // predecessor is always computed first.
178   unsigned PredNum = TBI->Pred->getNumber();
179   TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
180   assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
181   const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
182   TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
183   TBI->Head = PredTBI->Head;
184 
185   // Compute per-resource depths.
186   ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
187   ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
188   for (unsigned K = 0; K != PRKinds; ++K)
189     ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
190 }
191 
192 // Update resource-related information in the TraceBlockInfo for MBB.
193 // Only update resources related to the trace below MBB.
194 void MachineTraceMetrics::Ensemble::
195 computeHeightResources(const MachineBasicBlock *MBB) {
196   TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
197   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
198   unsigned PROffset = MBB->getNumber() * PRKinds;
199 
200   // Compute resources for the current block.
201   TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
202   ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
203 
204   // The trace tail is done.
205   if (!TBI->Succ) {
206     TBI->Tail = MBB->getNumber();
207     std::copy(PRCycles.begin(), PRCycles.end(),
208               ProcResourceHeights.begin() + PROffset);
209     return;
210   }
211 
212   // Compute from the block below. A post-order traversal ensures the
213   // predecessor is always computed first.
214   unsigned SuccNum = TBI->Succ->getNumber();
215   TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
216   assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
217   TBI->InstrHeight += SuccTBI->InstrHeight;
218   TBI->Tail = SuccTBI->Tail;
219 
220   // Compute per-resource heights.
221   ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
222   for (unsigned K = 0; K != PRKinds; ++K)
223     ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
224 }
225 
226 // Check if depth resources for MBB are valid and return the TBI.
227 // Return NULL if the resources have been invalidated.
228 const MachineTraceMetrics::TraceBlockInfo*
229 MachineTraceMetrics::Ensemble::
230 getDepthResources(const MachineBasicBlock *MBB) const {
231   const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
232   return TBI->hasValidDepth() ? TBI : 0;
233 }
234 
235 // Check if height resources for MBB are valid and return the TBI.
236 // Return NULL if the resources have been invalidated.
237 const MachineTraceMetrics::TraceBlockInfo*
238 MachineTraceMetrics::Ensemble::
239 getHeightResources(const MachineBasicBlock *MBB) const {
240   const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
241   return TBI->hasValidHeight() ? TBI : 0;
242 }
243 
244 /// Get an array of processor resource depths for MBB. Indexed by processor
245 /// resource kind, this array contains the scaled processor resources consumed
246 /// by all blocks preceding MBB in its trace. It does not include instructions
247 /// in MBB.
248 ///
249 /// Compare TraceBlockInfo::InstrDepth.
250 ArrayRef<unsigned>
251 MachineTraceMetrics::Ensemble::
252 getProcResourceDepths(unsigned MBBNum) const {
253   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
254   return ArrayRef<unsigned>(&ProcResourceDepths[MBBNum * PRKinds], PRKinds);
255 }
256 
257 /// Get an array of processor resource heights for MBB. Indexed by processor
258 /// resource kind, this array contains the scaled processor resources consumed
259 /// by this block and all blocks following it in its trace.
260 ///
261 /// Compare TraceBlockInfo::InstrHeight.
262 ArrayRef<unsigned>
263 MachineTraceMetrics::Ensemble::
264 getProcResourceHeights(unsigned MBBNum) const {
265   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
266   return ArrayRef<unsigned>(&ProcResourceHeights[MBBNum * PRKinds], PRKinds);
267 }
268 
269 //===----------------------------------------------------------------------===//
270 //                         Trace Selection Strategies
271 //===----------------------------------------------------------------------===//
272 //
273 // A trace selection strategy is implemented as a sub-class of Ensemble. The
274 // trace through a block B is computed by two DFS traversals of the CFG
275 // starting from B. One upwards, and one downwards. During the upwards DFS,
276 // pickTracePred() is called on the post-ordered blocks. During the downwards
277 // DFS, pickTraceSucc() is called in a post-order.
278 //
279 
280 // We never allow traces that leave loops, but we do allow traces to enter
281 // nested loops. We also never allow traces to contain back-edges.
282 //
283 // This means that a loop header can never appear above the center block of a
284 // trace, except as the trace head. Below the center block, loop exiting edges
285 // are banned.
286 //
287 // Return true if an edge from the From loop to the To loop is leaving a loop.
288 // Either of To and From can be null.
289 static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
290   return From && !From->contains(To);
291 }
292 
293 // MinInstrCountEnsemble - Pick the trace that executes the least number of
294 // instructions.
295 namespace {
296 class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
297   const char *getName() const { return "MinInstr"; }
298   const MachineBasicBlock *pickTracePred(const MachineBasicBlock*);
299   const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*);
300 
301 public:
302   MinInstrCountEnsemble(MachineTraceMetrics *mtm)
303     : MachineTraceMetrics::Ensemble(mtm) {}
304 };
305 }
306 
307 // Select the preferred predecessor for MBB.
308 const MachineBasicBlock*
309 MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
310   if (MBB->pred_empty())
311     return 0;
312   const MachineLoop *CurLoop = getLoopFor(MBB);
313   // Don't leave loops, and never follow back-edges.
314   if (CurLoop && MBB == CurLoop->getHeader())
315     return 0;
316   unsigned CurCount = MTM.getResources(MBB)->InstrCount;
317   const MachineBasicBlock *Best = 0;
318   unsigned BestDepth = 0;
319   for (MachineBasicBlock::const_pred_iterator
320        I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
321     const MachineBasicBlock *Pred = *I;
322     const MachineTraceMetrics::TraceBlockInfo *PredTBI =
323       getDepthResources(Pred);
324     // Ignore cycles that aren't natural loops.
325     if (!PredTBI)
326       continue;
327     // Pick the predecessor that would give this block the smallest InstrDepth.
328     unsigned Depth = PredTBI->InstrDepth + CurCount;
329     if (!Best || Depth < BestDepth)
330       Best = Pred, BestDepth = Depth;
331   }
332   return Best;
333 }
334 
335 // Select the preferred successor for MBB.
336 const MachineBasicBlock*
337 MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
338   if (MBB->pred_empty())
339     return 0;
340   const MachineLoop *CurLoop = getLoopFor(MBB);
341   const MachineBasicBlock *Best = 0;
342   unsigned BestHeight = 0;
343   for (MachineBasicBlock::const_succ_iterator
344        I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
345     const MachineBasicBlock *Succ = *I;
346     // Don't consider back-edges.
347     if (CurLoop && Succ == CurLoop->getHeader())
348       continue;
349     // Don't consider successors exiting CurLoop.
350     if (isExitingLoop(CurLoop, getLoopFor(Succ)))
351       continue;
352     const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
353       getHeightResources(Succ);
354     // Ignore cycles that aren't natural loops.
355     if (!SuccTBI)
356       continue;
357     // Pick the successor that would give this block the smallest InstrHeight.
358     unsigned Height = SuccTBI->InstrHeight;
359     if (!Best || Height < BestHeight)
360       Best = Succ, BestHeight = Height;
361   }
362   return Best;
363 }
364 
365 // Get an Ensemble sub-class for the requested trace strategy.
366 MachineTraceMetrics::Ensemble *
367 MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
368   assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
369   Ensemble *&E = Ensembles[strategy];
370   if (E)
371     return E;
372 
373   // Allocate new Ensemble on demand.
374   switch (strategy) {
375   case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
376   default: llvm_unreachable("Invalid trace strategy enum");
377   }
378 }
379 
380 void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
381   DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
382   BlockInfo[MBB->getNumber()].invalidate();
383   for (unsigned i = 0; i != TS_NumStrategies; ++i)
384     if (Ensembles[i])
385       Ensembles[i]->invalidate(MBB);
386 }
387 
388 void MachineTraceMetrics::verifyAnalysis() const {
389   if (!MF)
390     return;
391 #ifndef NDEBUG
392   assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
393   for (unsigned i = 0; i != TS_NumStrategies; ++i)
394     if (Ensembles[i])
395       Ensembles[i]->verify();
396 #endif
397 }
398 
399 //===----------------------------------------------------------------------===//
400 //                               Trace building
401 //===----------------------------------------------------------------------===//
402 //
403 // Traces are built by two CFG traversals. To avoid recomputing too much, use a
404 // set abstraction that confines the search to the current loop, and doesn't
405 // revisit blocks.
406 
407 namespace {
408 struct LoopBounds {
409   MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
410   SmallPtrSet<const MachineBasicBlock*, 8> Visited;
411   const MachineLoopInfo *Loops;
412   bool Downward;
413   LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
414              const MachineLoopInfo *loops)
415     : Blocks(blocks), Loops(loops), Downward(false) {}
416 };
417 }
418 
419 // Specialize po_iterator_storage in order to prune the post-order traversal so
420 // it is limited to the current loop and doesn't traverse the loop back edges.
421 namespace llvm {
422 template<>
423 class po_iterator_storage<LoopBounds, true> {
424   LoopBounds &LB;
425 public:
426   po_iterator_storage(LoopBounds &lb) : LB(lb) {}
427   void finishPostorder(const MachineBasicBlock*) {}
428 
429   bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
430     // Skip already visited To blocks.
431     MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
432     if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
433       return false;
434     // From is null once when To is the trace center block.
435     if (From) {
436       if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
437         // Don't follow backedges, don't leave FromLoop when going upwards.
438         if ((LB.Downward ? To : From) == FromLoop->getHeader())
439           return false;
440         // Don't leave FromLoop.
441         if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
442           return false;
443       }
444     }
445     // To is a new block. Mark the block as visited in case the CFG has cycles
446     // that MachineLoopInfo didn't recognize as a natural loop.
447     return LB.Visited.insert(To);
448   }
449 };
450 }
451 
452 /// Compute the trace through MBB.
453 void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
454   DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
455                << MBB->getNumber() << '\n');
456   // Set up loop bounds for the backwards post-order traversal.
457   LoopBounds Bounds(BlockInfo, MTM.Loops);
458 
459   // Run an upwards post-order search for the trace start.
460   Bounds.Downward = false;
461   Bounds.Visited.clear();
462   typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
463   for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
464        I != E; ++I) {
465     DEBUG(dbgs() << "  pred for BB#" << I->getNumber() << ": ");
466     TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
467     // All the predecessors have been visited, pick the preferred one.
468     TBI.Pred = pickTracePred(*I);
469     DEBUG({
470       if (TBI.Pred)
471         dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
472       else
473         dbgs() << "null\n";
474     });
475     // The trace leading to I is now known, compute the depth resources.
476     computeDepthResources(*I);
477   }
478 
479   // Run a downwards post-order search for the trace end.
480   Bounds.Downward = true;
481   Bounds.Visited.clear();
482   typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
483   for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
484        I != E; ++I) {
485     DEBUG(dbgs() << "  succ for BB#" << I->getNumber() << ": ");
486     TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
487     // All the successors have been visited, pick the preferred one.
488     TBI.Succ = pickTraceSucc(*I);
489     DEBUG({
490       if (TBI.Succ)
491         dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
492       else
493         dbgs() << "null\n";
494     });
495     // The trace leaving I is now known, compute the height resources.
496     computeHeightResources(*I);
497   }
498 }
499 
500 /// Invalidate traces through BadMBB.
501 void
502 MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
503   SmallVector<const MachineBasicBlock*, 16> WorkList;
504   TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
505 
506   // Invalidate height resources of blocks above MBB.
507   if (BadTBI.hasValidHeight()) {
508     BadTBI.invalidateHeight();
509     WorkList.push_back(BadMBB);
510     do {
511       const MachineBasicBlock *MBB = WorkList.pop_back_val();
512       DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
513             << " height.\n");
514       // Find any MBB predecessors that have MBB as their preferred successor.
515       // They are the only ones that need to be invalidated.
516       for (MachineBasicBlock::const_pred_iterator
517            I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
518         TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
519         if (!TBI.hasValidHeight())
520           continue;
521         if (TBI.Succ == MBB) {
522           TBI.invalidateHeight();
523           WorkList.push_back(*I);
524           continue;
525         }
526         // Verify that TBI.Succ is actually a *I successor.
527         assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
528       }
529     } while (!WorkList.empty());
530   }
531 
532   // Invalidate depth resources of blocks below MBB.
533   if (BadTBI.hasValidDepth()) {
534     BadTBI.invalidateDepth();
535     WorkList.push_back(BadMBB);
536     do {
537       const MachineBasicBlock *MBB = WorkList.pop_back_val();
538       DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
539             << " depth.\n");
540       // Find any MBB successors that have MBB as their preferred predecessor.
541       // They are the only ones that need to be invalidated.
542       for (MachineBasicBlock::const_succ_iterator
543            I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
544         TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
545         if (!TBI.hasValidDepth())
546           continue;
547         if (TBI.Pred == MBB) {
548           TBI.invalidateDepth();
549           WorkList.push_back(*I);
550           continue;
551         }
552         // Verify that TBI.Pred is actually a *I predecessor.
553         assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
554       }
555     } while (!WorkList.empty());
556   }
557 
558   // Clear any per-instruction data. We only have to do this for BadMBB itself
559   // because the instructions in that block may change. Other blocks may be
560   // invalidated, but their instructions will stay the same, so there is no
561   // need to erase the Cycle entries. They will be overwritten when we
562   // recompute.
563   for (MachineBasicBlock::const_iterator I = BadMBB->begin(), E = BadMBB->end();
564        I != E; ++I)
565     Cycles.erase(I);
566 }
567 
568 void MachineTraceMetrics::Ensemble::verify() const {
569 #ifndef NDEBUG
570   assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
571          "Outdated BlockInfo size");
572   for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
573     const TraceBlockInfo &TBI = BlockInfo[Num];
574     if (TBI.hasValidDepth() && TBI.Pred) {
575       const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
576       assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
577       assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
578              "Trace is broken, depth should have been invalidated.");
579       const MachineLoop *Loop = getLoopFor(MBB);
580       assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
581     }
582     if (TBI.hasValidHeight() && TBI.Succ) {
583       const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
584       assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
585       assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
586              "Trace is broken, height should have been invalidated.");
587       const MachineLoop *Loop = getLoopFor(MBB);
588       const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
589       assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
590              "Trace contains backedge");
591     }
592   }
593 #endif
594 }
595 
596 //===----------------------------------------------------------------------===//
597 //                             Data Dependencies
598 //===----------------------------------------------------------------------===//
599 //
600 // Compute the depth and height of each instruction based on data dependencies
601 // and instruction latencies. These cycle numbers assume that the CPU can issue
602 // an infinite number of instructions per cycle as long as their dependencies
603 // are ready.
604 
605 // A data dependency is represented as a defining MI and operand numbers on the
606 // defining and using MI.
607 namespace {
608 struct DataDep {
609   const MachineInstr *DefMI;
610   unsigned DefOp;
611   unsigned UseOp;
612 
613   DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
614     : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
615 
616   /// Create a DataDep from an SSA form virtual register.
617   DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
618     : UseOp(UseOp) {
619     assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
620     MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
621     assert(!DefI.atEnd() && "Register has no defs");
622     DefMI = &*DefI;
623     DefOp = DefI.getOperandNo();
624     assert((++DefI).atEnd() && "Register has multiple defs");
625   }
626 };
627 }
628 
629 // Get the input data dependencies that must be ready before UseMI can issue.
630 // Return true if UseMI has any physreg operands.
631 static bool getDataDeps(const MachineInstr *UseMI,
632                         SmallVectorImpl<DataDep> &Deps,
633                         const MachineRegisterInfo *MRI) {
634   bool HasPhysRegs = false;
635   for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
636     if (!MO->isReg())
637       continue;
638     unsigned Reg = MO->getReg();
639     if (!Reg)
640       continue;
641     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
642       HasPhysRegs = true;
643       continue;
644     }
645     // Collect virtual register reads.
646     if (MO->readsReg())
647       Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
648   }
649   return HasPhysRegs;
650 }
651 
652 // Get the input data dependencies of a PHI instruction, using Pred as the
653 // preferred predecessor.
654 // This will add at most one dependency to Deps.
655 static void getPHIDeps(const MachineInstr *UseMI,
656                        SmallVectorImpl<DataDep> &Deps,
657                        const MachineBasicBlock *Pred,
658                        const MachineRegisterInfo *MRI) {
659   // No predecessor at the beginning of a trace. Ignore dependencies.
660   if (!Pred)
661     return;
662   assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
663   for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
664     if (UseMI->getOperand(i + 1).getMBB() == Pred) {
665       unsigned Reg = UseMI->getOperand(i).getReg();
666       Deps.push_back(DataDep(MRI, Reg, i));
667       return;
668     }
669   }
670 }
671 
672 // Keep track of physreg data dependencies by recording each live register unit.
673 // Associate each regunit with an instruction operand. Depending on the
674 // direction instructions are scanned, it could be the operand that defined the
675 // regunit, or the highest operand to read the regunit.
676 namespace {
677 struct LiveRegUnit {
678   unsigned RegUnit;
679   unsigned Cycle;
680   const MachineInstr *MI;
681   unsigned Op;
682 
683   unsigned getSparseSetIndex() const { return RegUnit; }
684 
685   LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(0), Op(0) {}
686 };
687 }
688 
689 // Identify physreg dependencies for UseMI, and update the live regunit
690 // tracking set when scanning instructions downwards.
691 static void updatePhysDepsDownwards(const MachineInstr *UseMI,
692                                     SmallVectorImpl<DataDep> &Deps,
693                                     SparseSet<LiveRegUnit> &RegUnits,
694                                     const TargetRegisterInfo *TRI) {
695   SmallVector<unsigned, 8> Kills;
696   SmallVector<unsigned, 8> LiveDefOps;
697 
698   for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
699     if (!MO->isReg())
700       continue;
701     unsigned Reg = MO->getReg();
702     if (!TargetRegisterInfo::isPhysicalRegister(Reg))
703       continue;
704     // Track live defs and kills for updating RegUnits.
705     if (MO->isDef()) {
706       if (MO->isDead())
707         Kills.push_back(Reg);
708       else
709         LiveDefOps.push_back(MO.getOperandNo());
710     } else if (MO->isKill())
711       Kills.push_back(Reg);
712     // Identify dependencies.
713     if (!MO->readsReg())
714       continue;
715     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
716       SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
717       if (I == RegUnits.end())
718         continue;
719       Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
720       break;
721     }
722   }
723 
724   // Update RegUnits to reflect live registers after UseMI.
725   // First kills.
726   for (unsigned i = 0, e = Kills.size(); i != e; ++i)
727     for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
728       RegUnits.erase(*Units);
729 
730   // Second, live defs.
731   for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
732     unsigned DefOp = LiveDefOps[i];
733     for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
734          Units.isValid(); ++Units) {
735       LiveRegUnit &LRU = RegUnits[*Units];
736       LRU.MI = UseMI;
737       LRU.Op = DefOp;
738     }
739   }
740 }
741 
742 /// The length of the critical path through a trace is the maximum of two path
743 /// lengths:
744 ///
745 /// 1. The maximum height+depth over all instructions in the trace center block.
746 ///
747 /// 2. The longest cross-block dependency chain. For small blocks, it is
748 ///    possible that the critical path through the trace doesn't include any
749 ///    instructions in the block.
750 ///
751 /// This function computes the second number from the live-in list of the
752 /// center block.
753 unsigned MachineTraceMetrics::Ensemble::
754 computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
755   assert(TBI.HasValidInstrDepths && "Missing depth info");
756   assert(TBI.HasValidInstrHeights && "Missing height info");
757   unsigned MaxLen = 0;
758   for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
759     const LiveInReg &LIR = TBI.LiveIns[i];
760     if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
761       continue;
762     const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
763     // Ignore dependencies outside the current trace.
764     const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
765     if (!DefTBI.isUsefulDominator(TBI))
766       continue;
767     unsigned Len = LIR.Height + Cycles[DefMI].Depth;
768     MaxLen = std::max(MaxLen, Len);
769   }
770   return MaxLen;
771 }
772 
773 /// Compute instruction depths for all instructions above or in MBB in its
774 /// trace. This assumes that the trace through MBB has already been computed.
775 void MachineTraceMetrics::Ensemble::
776 computeInstrDepths(const MachineBasicBlock *MBB) {
777   // The top of the trace may already be computed, and HasValidInstrDepths
778   // implies Head->HasValidInstrDepths, so we only need to start from the first
779   // block in the trace that needs to be recomputed.
780   SmallVector<const MachineBasicBlock*, 8> Stack;
781   do {
782     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
783     assert(TBI.hasValidDepth() && "Incomplete trace");
784     if (TBI.HasValidInstrDepths)
785       break;
786     Stack.push_back(MBB);
787     MBB = TBI.Pred;
788   } while (MBB);
789 
790   // FIXME: If MBB is non-null at this point, it is the last pre-computed block
791   // in the trace. We should track any live-out physregs that were defined in
792   // the trace. This is quite rare in SSA form, typically created by CSE
793   // hoisting a compare.
794   SparseSet<LiveRegUnit> RegUnits;
795   RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
796 
797   // Go through trace blocks in top-down order, stopping after the center block.
798   SmallVector<DataDep, 8> Deps;
799   while (!Stack.empty()) {
800     MBB = Stack.pop_back_val();
801     DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
802     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
803     TBI.HasValidInstrDepths = true;
804     TBI.CriticalPath = 0;
805 
806     // Print out resource depths here as well.
807     DEBUG({
808       dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
809       ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
810       for (unsigned K = 0; K != PRDepths.size(); ++K)
811         if (PRDepths[K]) {
812           unsigned Factor = MTM.SchedModel.getResourceFactor(K);
813           dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
814                  << MTM.SchedModel.getProcResource(K)->Name << " ("
815                  << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
816         }
817     });
818 
819     // Also compute the critical path length through MBB when possible.
820     if (TBI.HasValidInstrHeights)
821       TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
822 
823     for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
824          I != E; ++I) {
825       const MachineInstr *UseMI = I;
826 
827       // Collect all data dependencies.
828       Deps.clear();
829       if (UseMI->isPHI())
830         getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
831       else if (getDataDeps(UseMI, Deps, MTM.MRI))
832         updatePhysDepsDownwards(UseMI, Deps, RegUnits, MTM.TRI);
833 
834       // Filter and process dependencies, computing the earliest issue cycle.
835       unsigned Cycle = 0;
836       for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
837         const DataDep &Dep = Deps[i];
838         const TraceBlockInfo&DepTBI =
839           BlockInfo[Dep.DefMI->getParent()->getNumber()];
840         // Ignore dependencies from outside the current trace.
841         if (!DepTBI.isUsefulDominator(TBI))
842           continue;
843         assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
844         unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
845         // Add latency if DefMI is a real instruction. Transients get latency 0.
846         if (!Dep.DefMI->isTransient())
847           DepCycle += MTM.SchedModel
848             .computeOperandLatency(Dep.DefMI, Dep.DefOp, UseMI, Dep.UseOp,
849                                    /* FindMin = */ false);
850         Cycle = std::max(Cycle, DepCycle);
851       }
852       // Remember the instruction depth.
853       InstrCycles &MICycles = Cycles[UseMI];
854       MICycles.Depth = Cycle;
855 
856       if (!TBI.HasValidInstrHeights) {
857         DEBUG(dbgs() << Cycle << '\t' << *UseMI);
858         continue;
859       }
860       // Update critical path length.
861       TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
862       DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *UseMI);
863     }
864   }
865 }
866 
867 // Identify physreg dependencies for MI when scanning instructions upwards.
868 // Return the issue height of MI after considering any live regunits.
869 // Height is the issue height computed from virtual register dependencies alone.
870 static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
871                                       SparseSet<LiveRegUnit> &RegUnits,
872                                       const TargetSchedModel &SchedModel,
873                                       const TargetInstrInfo *TII,
874                                       const TargetRegisterInfo *TRI) {
875   SmallVector<unsigned, 8> ReadOps;
876   for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
877     if (!MO->isReg())
878       continue;
879     unsigned Reg = MO->getReg();
880     if (!TargetRegisterInfo::isPhysicalRegister(Reg))
881       continue;
882     if (MO->readsReg())
883       ReadOps.push_back(MO.getOperandNo());
884     if (!MO->isDef())
885       continue;
886     // This is a def of Reg. Remove corresponding entries from RegUnits, and
887     // update MI Height to consider the physreg dependencies.
888     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
889       SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
890       if (I == RegUnits.end())
891         continue;
892       unsigned DepHeight = I->Cycle;
893       if (!MI->isTransient()) {
894         // We may not know the UseMI of this dependency, if it came from the
895         // live-in list. SchedModel can handle a NULL UseMI.
896         DepHeight += SchedModel
897           .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op,
898                                  /* FindMin = */ false);
899       }
900       Height = std::max(Height, DepHeight);
901       // This regunit is dead above MI.
902       RegUnits.erase(I);
903     }
904   }
905 
906   // Now we know the height of MI. Update any regunits read.
907   for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
908     unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
909     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
910       LiveRegUnit &LRU = RegUnits[*Units];
911       // Set the height to the highest reader of the unit.
912       if (LRU.Cycle <= Height && LRU.MI != MI) {
913         LRU.Cycle = Height;
914         LRU.MI = MI;
915         LRU.Op = ReadOps[i];
916       }
917     }
918   }
919 
920   return Height;
921 }
922 
923 
924 typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
925 
926 // Push the height of DefMI upwards if required to match UseMI.
927 // Return true if this is the first time DefMI was seen.
928 static bool pushDepHeight(const DataDep &Dep,
929                           const MachineInstr *UseMI, unsigned UseHeight,
930                           MIHeightMap &Heights,
931                           const TargetSchedModel &SchedModel,
932                           const TargetInstrInfo *TII) {
933   // Adjust height by Dep.DefMI latency.
934   if (!Dep.DefMI->isTransient())
935     UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
936                                                   UseMI, Dep.UseOp, false);
937 
938   // Update Heights[DefMI] to be the maximum height seen.
939   MIHeightMap::iterator I;
940   bool New;
941   tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
942   if (New)
943     return true;
944 
945   // DefMI has been pushed before. Give it the max height.
946   if (I->second < UseHeight)
947     I->second = UseHeight;
948   return false;
949 }
950 
951 /// Assuming that the virtual register defined by DefMI:DefOp was used by
952 /// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
953 /// when reaching the block that contains DefMI.
954 void MachineTraceMetrics::Ensemble::
955 addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
956            ArrayRef<const MachineBasicBlock*> Trace) {
957   assert(!Trace.empty() && "Trace should contain at least one block");
958   unsigned Reg = DefMI->getOperand(DefOp).getReg();
959   assert(TargetRegisterInfo::isVirtualRegister(Reg));
960   const MachineBasicBlock *DefMBB = DefMI->getParent();
961 
962   // Reg is live-in to all blocks in Trace that follow DefMBB.
963   for (unsigned i = Trace.size(); i; --i) {
964     const MachineBasicBlock *MBB = Trace[i-1];
965     if (MBB == DefMBB)
966       return;
967     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
968     // Just add the register. The height will be updated later.
969     TBI.LiveIns.push_back(Reg);
970   }
971 }
972 
973 /// Compute instruction heights in the trace through MBB. This updates MBB and
974 /// the blocks below it in the trace. It is assumed that the trace has already
975 /// been computed.
976 void MachineTraceMetrics::Ensemble::
977 computeInstrHeights(const MachineBasicBlock *MBB) {
978   // The bottom of the trace may already be computed.
979   // Find the blocks that need updating.
980   SmallVector<const MachineBasicBlock*, 8> Stack;
981   do {
982     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
983     assert(TBI.hasValidHeight() && "Incomplete trace");
984     if (TBI.HasValidInstrHeights)
985       break;
986     Stack.push_back(MBB);
987     TBI.LiveIns.clear();
988     MBB = TBI.Succ;
989   } while (MBB);
990 
991   // As we move upwards in the trace, keep track of instructions that are
992   // required by deeper trace instructions. Map MI -> height required so far.
993   MIHeightMap Heights;
994 
995   // For physregs, the def isn't known when we see the use.
996   // Instead, keep track of the highest use of each regunit.
997   SparseSet<LiveRegUnit> RegUnits;
998   RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
999 
1000   // If the bottom of the trace was already precomputed, initialize heights
1001   // from its live-in list.
1002   // MBB is the highest precomputed block in the trace.
1003   if (MBB) {
1004     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1005     for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1006       LiveInReg LI = TBI.LiveIns[i];
1007       if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1008         // For virtual registers, the def latency is included.
1009         unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1010         if (Height < LI.Height)
1011           Height = LI.Height;
1012       } else {
1013         // For register units, the def latency is not included because we don't
1014         // know the def yet.
1015         RegUnits[LI.Reg].Cycle = LI.Height;
1016       }
1017     }
1018   }
1019 
1020   // Go through the trace blocks in bottom-up order.
1021   SmallVector<DataDep, 8> Deps;
1022   for (;!Stack.empty(); Stack.pop_back()) {
1023     MBB = Stack.back();
1024     DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1025     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1026     TBI.HasValidInstrHeights = true;
1027     TBI.CriticalPath = 0;
1028 
1029     DEBUG({
1030       dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1031       ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1032       for (unsigned K = 0; K != PRHeights.size(); ++K)
1033         if (PRHeights[K]) {
1034           unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1035           dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1036                  << MTM.SchedModel.getProcResource(K)->Name << " ("
1037                  << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1038         }
1039     });
1040 
1041     // Get dependencies from PHIs in the trace successor.
1042     const MachineBasicBlock *Succ = TBI.Succ;
1043     // If MBB is the last block in the trace, and it has a back-edge to the
1044     // loop header, get loop-carried dependencies from PHIs in the header. For
1045     // that purpose, pretend that all the loop header PHIs have height 0.
1046     if (!Succ)
1047       if (const MachineLoop *Loop = getLoopFor(MBB))
1048         if (MBB->isSuccessor(Loop->getHeader()))
1049           Succ = Loop->getHeader();
1050 
1051     if (Succ) {
1052       for (MachineBasicBlock::const_iterator I = Succ->begin(), E = Succ->end();
1053            I != E && I->isPHI(); ++I) {
1054         const MachineInstr *PHI = I;
1055         Deps.clear();
1056         getPHIDeps(PHI, Deps, MBB, MTM.MRI);
1057         if (!Deps.empty()) {
1058           // Loop header PHI heights are all 0.
1059           unsigned Height = TBI.Succ ? Cycles.lookup(PHI).Height : 0;
1060           DEBUG(dbgs() << "pred\t" << Height << '\t' << *PHI);
1061           if (pushDepHeight(Deps.front(), PHI, Height,
1062                             Heights, MTM.SchedModel, MTM.TII))
1063             addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
1064         }
1065       }
1066     }
1067 
1068     // Go through the block backwards.
1069     for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1070          BI != BB;) {
1071       const MachineInstr *MI = --BI;
1072 
1073       // Find the MI height as determined by virtual register uses in the
1074       // trace below.
1075       unsigned Cycle = 0;
1076       MIHeightMap::iterator HeightI = Heights.find(MI);
1077       if (HeightI != Heights.end()) {
1078         Cycle = HeightI->second;
1079         // We won't be seeing any more MI uses.
1080         Heights.erase(HeightI);
1081       }
1082 
1083       // Don't process PHI deps. They depend on the specific predecessor, and
1084       // we'll get them when visiting the predecessor.
1085       Deps.clear();
1086       bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1087 
1088       // There may also be regunit dependencies to include in the height.
1089       if (HasPhysRegs)
1090         Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
1091                                       MTM.SchedModel, MTM.TII, MTM.TRI);
1092 
1093       // Update the required height of any virtual registers read by MI.
1094       for (unsigned i = 0, e = Deps.size(); i != e; ++i)
1095         if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
1096           addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
1097 
1098       InstrCycles &MICycles = Cycles[MI];
1099       MICycles.Height = Cycle;
1100       if (!TBI.HasValidInstrDepths) {
1101         DEBUG(dbgs() << Cycle << '\t' << *MI);
1102         continue;
1103       }
1104       // Update critical path length.
1105       TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1106       DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
1107     }
1108 
1109     // Update virtual live-in heights. They were added by addLiveIns() with a 0
1110     // height because the final height isn't known until now.
1111     DEBUG(dbgs() << "BB#" << MBB->getNumber() <<  " Live-ins:");
1112     for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1113       LiveInReg &LIR = TBI.LiveIns[i];
1114       const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1115       LIR.Height = Heights.lookup(DefMI);
1116       DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1117     }
1118 
1119     // Transfer the live regunits to the live-in list.
1120     for (SparseSet<LiveRegUnit>::const_iterator
1121          RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1122       TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1123       DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1124                    << '@' << RI->Cycle);
1125     }
1126     DEBUG(dbgs() << '\n');
1127 
1128     if (!TBI.HasValidInstrDepths)
1129       continue;
1130     // Add live-ins to the critical path length.
1131     TBI.CriticalPath = std::max(TBI.CriticalPath,
1132                                 computeCrossBlockCriticalPath(TBI));
1133     DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
1134   }
1135 }
1136 
1137 MachineTraceMetrics::Trace
1138 MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1139   // FIXME: Check cache tags, recompute as needed.
1140   computeTrace(MBB);
1141   computeInstrDepths(MBB);
1142   computeInstrHeights(MBB);
1143   return Trace(*this, BlockInfo[MBB->getNumber()]);
1144 }
1145 
1146 unsigned
1147 MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1148   assert(MI && "Not an instruction.");
1149   assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1150          "MI must be in the trace center block");
1151   InstrCycles Cyc = getInstrCycles(MI);
1152   return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1153 }
1154 
1155 unsigned
1156 MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1157   const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1158   SmallVector<DataDep, 1> Deps;
1159   getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1160   assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1161   DataDep &Dep = Deps.front();
1162   unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1163   // Add latency if DefMI is a real instruction. Transients get latency 0.
1164   if (!Dep.DefMI->isTransient())
1165     DepCycle += TE.MTM.SchedModel
1166       .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp, false);
1167   return DepCycle;
1168 }
1169 
1170 unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
1171   // Find the limiting processor resource.
1172   // Numbers have been pre-scaled to be comparable.
1173   unsigned PRMax = 0;
1174   ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1175   if (Bottom) {
1176     ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1177     for (unsigned K = 0; K != PRDepths.size(); ++K)
1178       PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1179   } else {
1180     for (unsigned K = 0; K != PRDepths.size(); ++K)
1181       PRMax = std::max(PRMax, PRDepths[K]);
1182   }
1183   // Convert to cycle count.
1184   PRMax = TE.MTM.getCycles(PRMax);
1185 
1186   unsigned Instrs = TBI.InstrDepth;
1187   if (Bottom)
1188     Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
1189   if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1190     Instrs /= IW;
1191   // Assume issue width 1 without a schedule model.
1192   return std::max(Instrs, PRMax);
1193 }
1194 
1195 unsigned MachineTraceMetrics::Trace::
1196 getResourceLength(ArrayRef<const MachineBasicBlock*> Extrablocks) const {
1197   // Add up resources above and below the center block.
1198   ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1199   ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1200   unsigned PRMax = 0;
1201   for (unsigned K = 0; K != PRDepths.size(); ++K) {
1202     unsigned PRCycles = PRDepths[K] + PRHeights[K];
1203     for (unsigned I = 0; I != Extrablocks.size(); ++I)
1204       PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
1205     PRMax = std::max(PRMax, PRCycles);
1206   }
1207   // Convert to cycle count.
1208   PRMax = TE.MTM.getCycles(PRMax);
1209 
1210   unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1211   for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1212     Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
1213   if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1214     Instrs /= IW;
1215   // Assume issue width 1 without a schedule model.
1216   return std::max(Instrs, PRMax);
1217 }
1218 
1219 void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1220   OS << getName() << " ensemble:\n";
1221   for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1222     OS << "  BB#" << i << '\t';
1223     BlockInfo[i].print(OS);
1224     OS << '\n';
1225   }
1226 }
1227 
1228 void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1229   if (hasValidDepth()) {
1230     OS << "depth=" << InstrDepth;
1231     if (Pred)
1232       OS << " pred=BB#" << Pred->getNumber();
1233     else
1234       OS << " pred=null";
1235     OS << " head=BB#" << Head;
1236     if (HasValidInstrDepths)
1237       OS << " +instrs";
1238   } else
1239     OS << "depth invalid";
1240   OS << ", ";
1241   if (hasValidHeight()) {
1242     OS << "height=" << InstrHeight;
1243     if (Succ)
1244       OS << " succ=BB#" << Succ->getNumber();
1245     else
1246       OS << " succ=null";
1247     OS << " tail=BB#" << Tail;
1248     if (HasValidInstrHeights)
1249       OS << " +instrs";
1250   } else
1251     OS << "height invalid";
1252   if (HasValidInstrDepths && HasValidInstrHeights)
1253     OS << ", crit=" << CriticalPath;
1254 }
1255 
1256 void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
1257   unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1258 
1259   OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1260      << " --> BB#" << TBI.Tail << ':';
1261   if (TBI.hasValidHeight() && TBI.hasValidDepth())
1262     OS << ' ' << getInstrCount() << " instrs.";
1263   if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1264     OS << ' ' << TBI.CriticalPath << " cycles.";
1265 
1266   const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
1267   OS << "\nBB#" << MBBNum;
1268   while (Block->hasValidDepth() && Block->Pred) {
1269     unsigned Num = Block->Pred->getNumber();
1270     OS << " <- BB#" << Num;
1271     Block = &TE.BlockInfo[Num];
1272   }
1273 
1274   Block = &TBI;
1275   OS << "\n    ";
1276   while (Block->hasValidHeight() && Block->Succ) {
1277     unsigned Num = Block->Succ->getNumber();
1278     OS << " -> BB#" << Num;
1279     Block = &TE.BlockInfo[Num];
1280   }
1281   OS << '\n';
1282 }
1283