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