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