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