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