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