xref: /src/contrib/llvm-project/llvm/lib/CodeGen/MachineTraceMetrics.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
171d5a254SDimitry Andric //===- lib/CodeGen/MachineTraceMetrics.cpp --------------------------------===//
258b69754SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
658b69754SDimitry Andric //
758b69754SDimitry Andric //===----------------------------------------------------------------------===//
858b69754SDimitry Andric 
97ab83427SDimitry Andric #include "llvm/CodeGen/MachineTraceMetrics.h"
1071d5a254SDimitry Andric #include "llvm/ADT/ArrayRef.h"
1171d5a254SDimitry Andric #include "llvm/ADT/DenseMap.h"
124a16efa3SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
1371d5a254SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
1471d5a254SDimitry Andric #include "llvm/ADT/SmallVector.h"
154a16efa3SDimitry Andric #include "llvm/ADT/SparseSet.h"
1658b69754SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
1758b69754SDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
1871d5a254SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
1971d5a254SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
2058b69754SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
2171d5a254SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
2258b69754SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
23044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
24044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
25044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
26706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
2771d5a254SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
2871d5a254SDimitry Andric #include "llvm/Pass.h"
294a16efa3SDimitry Andric #include "llvm/Support/Debug.h"
3071d5a254SDimitry Andric #include "llvm/Support/ErrorHandling.h"
314a16efa3SDimitry Andric #include "llvm/Support/Format.h"
324a16efa3SDimitry Andric #include "llvm/Support/raw_ostream.h"
3371d5a254SDimitry Andric #include <algorithm>
3471d5a254SDimitry Andric #include <cassert>
3571d5a254SDimitry Andric #include <iterator>
3671d5a254SDimitry Andric #include <tuple>
3771d5a254SDimitry Andric #include <utility>
3858b69754SDimitry Andric 
3958b69754SDimitry Andric using namespace llvm;
4058b69754SDimitry Andric 
415ca98fd9SDimitry Andric #define DEBUG_TYPE "machine-trace-metrics"
425ca98fd9SDimitry Andric 
4358b69754SDimitry Andric char MachineTraceMetrics::ID = 0;
44044eb2f6SDimitry Andric 
4558b69754SDimitry Andric char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
4658b69754SDimitry Andric 
47ab44ce3dSDimitry Andric INITIALIZE_PASS_BEGIN(MachineTraceMetrics, DEBUG_TYPE,
48ab44ce3dSDimitry Andric                       "Machine Trace Metrics", false, true)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)49ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)
50ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
51ab44ce3dSDimitry Andric INITIALIZE_PASS_END(MachineTraceMetrics, DEBUG_TYPE,
52ab44ce3dSDimitry Andric                     "Machine Trace Metrics", false, true)
5358b69754SDimitry Andric 
5471d5a254SDimitry Andric MachineTraceMetrics::MachineTraceMetrics() : MachineFunctionPass(ID) {
555ca98fd9SDimitry Andric   std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
5658b69754SDimitry Andric }
5758b69754SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const5858b69754SDimitry Andric void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
5958b69754SDimitry Andric   AU.setPreservesAll();
60ac9a064cSDimitry Andric   AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
61ac9a064cSDimitry Andric   AU.addRequired<MachineLoopInfoWrapperPass>();
6258b69754SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
6358b69754SDimitry Andric }
6458b69754SDimitry Andric 
runOnMachineFunction(MachineFunction & Func)6558b69754SDimitry Andric bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
6658b69754SDimitry Andric   MF = &Func;
675a5ac124SDimitry Andric   const TargetSubtargetInfo &ST = MF->getSubtarget();
685a5ac124SDimitry Andric   TII = ST.getInstrInfo();
695a5ac124SDimitry Andric   TRI = ST.getRegisterInfo();
7058b69754SDimitry Andric   MRI = &MF->getRegInfo();
71ac9a064cSDimitry Andric   Loops = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
72eb11fae6SDimitry Andric   SchedModel.init(&ST);
7358b69754SDimitry Andric   BlockInfo.resize(MF->getNumBlockIDs());
74b1c73532SDimitry Andric   ProcReleaseAtCycles.resize(MF->getNumBlockIDs() *
754a16efa3SDimitry Andric                             SchedModel.getNumProcResourceKinds());
7658b69754SDimitry Andric   return false;
7758b69754SDimitry Andric }
7858b69754SDimitry Andric 
releaseMemory()7958b69754SDimitry Andric void MachineTraceMetrics::releaseMemory() {
805ca98fd9SDimitry Andric   MF = nullptr;
8158b69754SDimitry Andric   BlockInfo.clear();
8277fc4c14SDimitry Andric   for (Ensemble *&E : Ensembles) {
8377fc4c14SDimitry Andric     delete E;
8477fc4c14SDimitry Andric     E = nullptr;
8558b69754SDimitry Andric   }
8658b69754SDimitry Andric }
8758b69754SDimitry Andric 
8858b69754SDimitry Andric //===----------------------------------------------------------------------===//
8958b69754SDimitry Andric //                          Fixed block information
9058b69754SDimitry Andric //===----------------------------------------------------------------------===//
9158b69754SDimitry Andric //
9258b69754SDimitry Andric // The number of instructions in a basic block and the CPU resources used by
9358b69754SDimitry Andric // those instructions don't depend on any given trace strategy.
9458b69754SDimitry Andric 
9558b69754SDimitry Andric /// Compute the resource usage in basic block MBB.
9658b69754SDimitry Andric const MachineTraceMetrics::FixedBlockInfo*
getResources(const MachineBasicBlock * MBB)9758b69754SDimitry Andric MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
9858b69754SDimitry Andric   assert(MBB && "No basic block");
9958b69754SDimitry Andric   FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
10058b69754SDimitry Andric   if (FBI->hasResources())
10158b69754SDimitry Andric     return FBI;
10258b69754SDimitry Andric 
10358b69754SDimitry Andric   // Compute resource usage in the block.
10458b69754SDimitry Andric   FBI->HasCalls = false;
10558b69754SDimitry Andric   unsigned InstrCount = 0;
1064a16efa3SDimitry Andric 
1074a16efa3SDimitry Andric   // Add up per-processor resource cycles as well.
1084a16efa3SDimitry Andric   unsigned PRKinds = SchedModel.getNumProcResourceKinds();
1094a16efa3SDimitry Andric   SmallVector<unsigned, 32> PRCycles(PRKinds);
1104a16efa3SDimitry Andric 
1115ca98fd9SDimitry Andric   for (const auto &MI : *MBB) {
1125ca98fd9SDimitry Andric     if (MI.isTransient())
11358b69754SDimitry Andric       continue;
11458b69754SDimitry Andric     ++InstrCount;
1155ca98fd9SDimitry Andric     if (MI.isCall())
11658b69754SDimitry Andric       FBI->HasCalls = true;
1174a16efa3SDimitry Andric 
1184a16efa3SDimitry Andric     // Count processor resources used.
1194a16efa3SDimitry Andric     if (!SchedModel.hasInstrSchedModel())
1204a16efa3SDimitry Andric       continue;
1215ca98fd9SDimitry Andric     const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
1224a16efa3SDimitry Andric     if (!SC->isValid())
1234a16efa3SDimitry Andric       continue;
1244a16efa3SDimitry Andric 
1254a16efa3SDimitry Andric     for (TargetSchedModel::ProcResIter
1264a16efa3SDimitry Andric          PI = SchedModel.getWriteProcResBegin(SC),
1274a16efa3SDimitry Andric          PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
1284a16efa3SDimitry Andric       assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
129b1c73532SDimitry Andric       PRCycles[PI->ProcResourceIdx] += PI->ReleaseAtCycle;
1304a16efa3SDimitry Andric     }
13158b69754SDimitry Andric   }
13258b69754SDimitry Andric   FBI->InstrCount = InstrCount;
1334a16efa3SDimitry Andric 
1344a16efa3SDimitry Andric   // Scale the resource cycles so they are comparable.
1354a16efa3SDimitry Andric   unsigned PROffset = MBB->getNumber() * PRKinds;
1364a16efa3SDimitry Andric   for (unsigned K = 0; K != PRKinds; ++K)
137b1c73532SDimitry Andric     ProcReleaseAtCycles[PROffset + K] =
1384a16efa3SDimitry Andric       PRCycles[K] * SchedModel.getResourceFactor(K);
1394a16efa3SDimitry Andric 
14058b69754SDimitry Andric   return FBI;
14158b69754SDimitry Andric }
14258b69754SDimitry Andric 
1434a16efa3SDimitry Andric ArrayRef<unsigned>
getProcReleaseAtCycles(unsigned MBBNum) const144b1c73532SDimitry Andric MachineTraceMetrics::getProcReleaseAtCycles(unsigned MBBNum) const {
1454a16efa3SDimitry Andric   assert(BlockInfo[MBBNum].hasResources() &&
146b1c73532SDimitry Andric          "getResources() must be called before getProcReleaseAtCycles()");
1474a16efa3SDimitry Andric   unsigned PRKinds = SchedModel.getNumProcResourceKinds();
148b1c73532SDimitry Andric   assert((MBBNum+1) * PRKinds <= ProcReleaseAtCycles.size());
149b1c73532SDimitry Andric   return ArrayRef(ProcReleaseAtCycles.data() + MBBNum * PRKinds, PRKinds);
1504a16efa3SDimitry Andric }
1514a16efa3SDimitry Andric 
15258b69754SDimitry Andric //===----------------------------------------------------------------------===//
15358b69754SDimitry Andric //                         Ensemble utility functions
15458b69754SDimitry Andric //===----------------------------------------------------------------------===//
15558b69754SDimitry Andric 
Ensemble(MachineTraceMetrics * ct)15658b69754SDimitry Andric MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
15758b69754SDimitry Andric   : MTM(*ct) {
15858b69754SDimitry Andric   BlockInfo.resize(MTM.BlockInfo.size());
1594a16efa3SDimitry Andric   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
1604a16efa3SDimitry Andric   ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
1614a16efa3SDimitry Andric   ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
16258b69754SDimitry Andric }
16358b69754SDimitry Andric 
16458b69754SDimitry Andric // Virtual destructor serves as an anchor.
16571d5a254SDimitry Andric MachineTraceMetrics::Ensemble::~Ensemble() = default;
16658b69754SDimitry Andric 
16758b69754SDimitry Andric const MachineLoop*
getLoopFor(const MachineBasicBlock * MBB) const16858b69754SDimitry Andric MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
16958b69754SDimitry Andric   return MTM.Loops->getLoopFor(MBB);
17058b69754SDimitry Andric }
17158b69754SDimitry Andric 
17258b69754SDimitry Andric // Update resource-related information in the TraceBlockInfo for MBB.
17358b69754SDimitry Andric // Only update resources related to the trace above MBB.
17458b69754SDimitry Andric void MachineTraceMetrics::Ensemble::
computeDepthResources(const MachineBasicBlock * MBB)17558b69754SDimitry Andric computeDepthResources(const MachineBasicBlock *MBB) {
17658b69754SDimitry Andric   TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
1774a16efa3SDimitry Andric   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
1784a16efa3SDimitry Andric   unsigned PROffset = MBB->getNumber() * PRKinds;
17958b69754SDimitry Andric 
18058b69754SDimitry Andric   // Compute resources from trace above. The top block is simple.
18158b69754SDimitry Andric   if (!TBI->Pred) {
18258b69754SDimitry Andric     TBI->InstrDepth = 0;
18358b69754SDimitry Andric     TBI->Head = MBB->getNumber();
1844a16efa3SDimitry Andric     std::fill(ProcResourceDepths.begin() + PROffset,
1854a16efa3SDimitry Andric               ProcResourceDepths.begin() + PROffset + PRKinds, 0);
18658b69754SDimitry Andric     return;
18758b69754SDimitry Andric   }
18858b69754SDimitry Andric 
18958b69754SDimitry Andric   // Compute from the block above. A post-order traversal ensures the
19058b69754SDimitry Andric   // predecessor is always computed first.
1914a16efa3SDimitry Andric   unsigned PredNum = TBI->Pred->getNumber();
1924a16efa3SDimitry Andric   TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
19358b69754SDimitry Andric   assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
19458b69754SDimitry Andric   const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
19558b69754SDimitry Andric   TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
19658b69754SDimitry Andric   TBI->Head = PredTBI->Head;
1974a16efa3SDimitry Andric 
1984a16efa3SDimitry Andric   // Compute per-resource depths.
1994a16efa3SDimitry Andric   ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
200b1c73532SDimitry Andric   ArrayRef<unsigned> PredPRCycles = MTM.getProcReleaseAtCycles(PredNum);
2014a16efa3SDimitry Andric   for (unsigned K = 0; K != PRKinds; ++K)
2024a16efa3SDimitry Andric     ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
20358b69754SDimitry Andric }
20458b69754SDimitry Andric 
20558b69754SDimitry Andric // Update resource-related information in the TraceBlockInfo for MBB.
20658b69754SDimitry Andric // Only update resources related to the trace below MBB.
20758b69754SDimitry Andric void MachineTraceMetrics::Ensemble::
computeHeightResources(const MachineBasicBlock * MBB)20858b69754SDimitry Andric computeHeightResources(const MachineBasicBlock *MBB) {
20958b69754SDimitry Andric   TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
2104a16efa3SDimitry Andric   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
2114a16efa3SDimitry Andric   unsigned PROffset = MBB->getNumber() * PRKinds;
21258b69754SDimitry Andric 
21358b69754SDimitry Andric   // Compute resources for the current block.
21458b69754SDimitry Andric   TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
215b1c73532SDimitry Andric   ArrayRef<unsigned> PRCycles = MTM.getProcReleaseAtCycles(MBB->getNumber());
21658b69754SDimitry Andric 
21758b69754SDimitry Andric   // The trace tail is done.
21858b69754SDimitry Andric   if (!TBI->Succ) {
21958b69754SDimitry Andric     TBI->Tail = MBB->getNumber();
220d8e91e46SDimitry Andric     llvm::copy(PRCycles, ProcResourceHeights.begin() + PROffset);
22158b69754SDimitry Andric     return;
22258b69754SDimitry Andric   }
22358b69754SDimitry Andric 
22458b69754SDimitry Andric   // Compute from the block below. A post-order traversal ensures the
22558b69754SDimitry Andric   // predecessor is always computed first.
2264a16efa3SDimitry Andric   unsigned SuccNum = TBI->Succ->getNumber();
2274a16efa3SDimitry Andric   TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
22858b69754SDimitry Andric   assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
22958b69754SDimitry Andric   TBI->InstrHeight += SuccTBI->InstrHeight;
23058b69754SDimitry Andric   TBI->Tail = SuccTBI->Tail;
2314a16efa3SDimitry Andric 
2324a16efa3SDimitry Andric   // Compute per-resource heights.
2334a16efa3SDimitry Andric   ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
2344a16efa3SDimitry Andric   for (unsigned K = 0; K != PRKinds; ++K)
2354a16efa3SDimitry Andric     ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
23658b69754SDimitry Andric }
23758b69754SDimitry Andric 
23858b69754SDimitry Andric // Check if depth resources for MBB are valid and return the TBI.
23958b69754SDimitry Andric // Return NULL if the resources have been invalidated.
24058b69754SDimitry Andric const MachineTraceMetrics::TraceBlockInfo*
24158b69754SDimitry Andric MachineTraceMetrics::Ensemble::
getDepthResources(const MachineBasicBlock * MBB) const24258b69754SDimitry Andric getDepthResources(const MachineBasicBlock *MBB) const {
24358b69754SDimitry Andric   const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
2445ca98fd9SDimitry Andric   return TBI->hasValidDepth() ? TBI : nullptr;
24558b69754SDimitry Andric }
24658b69754SDimitry Andric 
24758b69754SDimitry Andric // Check if height resources for MBB are valid and return the TBI.
24858b69754SDimitry Andric // Return NULL if the resources have been invalidated.
24958b69754SDimitry Andric const MachineTraceMetrics::TraceBlockInfo*
25058b69754SDimitry Andric MachineTraceMetrics::Ensemble::
getHeightResources(const MachineBasicBlock * MBB) const25158b69754SDimitry Andric getHeightResources(const MachineBasicBlock *MBB) const {
25258b69754SDimitry Andric   const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
2535ca98fd9SDimitry Andric   return TBI->hasValidHeight() ? TBI : nullptr;
25458b69754SDimitry Andric }
25558b69754SDimitry Andric 
2564a16efa3SDimitry Andric /// Get an array of processor resource depths for MBB. Indexed by processor
2574a16efa3SDimitry Andric /// resource kind, this array contains the scaled processor resources consumed
2584a16efa3SDimitry Andric /// by all blocks preceding MBB in its trace. It does not include instructions
2594a16efa3SDimitry Andric /// in MBB.
2604a16efa3SDimitry Andric ///
2614a16efa3SDimitry Andric /// Compare TraceBlockInfo::InstrDepth.
2624a16efa3SDimitry Andric ArrayRef<unsigned>
2634a16efa3SDimitry Andric MachineTraceMetrics::Ensemble::
getProcResourceDepths(unsigned MBBNum) const2644a16efa3SDimitry Andric getProcResourceDepths(unsigned MBBNum) const {
2654a16efa3SDimitry Andric   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
2664a16efa3SDimitry Andric   assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
267e3b55780SDimitry Andric   return ArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds);
2684a16efa3SDimitry Andric }
2694a16efa3SDimitry Andric 
2704a16efa3SDimitry Andric /// Get an array of processor resource heights for MBB. Indexed by processor
2714a16efa3SDimitry Andric /// resource kind, this array contains the scaled processor resources consumed
2724a16efa3SDimitry Andric /// by this block and all blocks following it in its trace.
2734a16efa3SDimitry Andric ///
2744a16efa3SDimitry Andric /// Compare TraceBlockInfo::InstrHeight.
2754a16efa3SDimitry Andric ArrayRef<unsigned>
2764a16efa3SDimitry Andric MachineTraceMetrics::Ensemble::
getProcResourceHeights(unsigned MBBNum) const2774a16efa3SDimitry Andric getProcResourceHeights(unsigned MBBNum) const {
2784a16efa3SDimitry Andric   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
2794a16efa3SDimitry Andric   assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
280e3b55780SDimitry Andric   return ArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds);
2814a16efa3SDimitry Andric }
2824a16efa3SDimitry Andric 
28358b69754SDimitry Andric //===----------------------------------------------------------------------===//
28458b69754SDimitry Andric //                         Trace Selection Strategies
28558b69754SDimitry Andric //===----------------------------------------------------------------------===//
28658b69754SDimitry Andric //
28758b69754SDimitry Andric // A trace selection strategy is implemented as a sub-class of Ensemble. The
28858b69754SDimitry Andric // trace through a block B is computed by two DFS traversals of the CFG
28958b69754SDimitry Andric // starting from B. One upwards, and one downwards. During the upwards DFS,
29058b69754SDimitry Andric // pickTracePred() is called on the post-ordered blocks. During the downwards
29158b69754SDimitry Andric // DFS, pickTraceSucc() is called in a post-order.
29258b69754SDimitry Andric //
29358b69754SDimitry Andric 
29458b69754SDimitry Andric // We never allow traces that leave loops, but we do allow traces to enter
29558b69754SDimitry Andric // nested loops. We also never allow traces to contain back-edges.
29658b69754SDimitry Andric //
29758b69754SDimitry Andric // This means that a loop header can never appear above the center block of a
29858b69754SDimitry Andric // trace, except as the trace head. Below the center block, loop exiting edges
29958b69754SDimitry Andric // are banned.
30058b69754SDimitry Andric //
30158b69754SDimitry Andric // Return true if an edge from the From loop to the To loop is leaving a loop.
30258b69754SDimitry Andric // Either of To and From can be null.
isExitingLoop(const MachineLoop * From,const MachineLoop * To)30358b69754SDimitry Andric static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
30458b69754SDimitry Andric   return From && !From->contains(To);
30558b69754SDimitry Andric }
30658b69754SDimitry Andric 
30758b69754SDimitry Andric // MinInstrCountEnsemble - Pick the trace that executes the least number of
30858b69754SDimitry Andric // instructions.
30958b69754SDimitry Andric namespace {
31071d5a254SDimitry Andric 
31158b69754SDimitry Andric class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
getName() const3125ca98fd9SDimitry Andric   const char *getName() const override { return "MinInstr"; }
3135ca98fd9SDimitry Andric   const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
3145ca98fd9SDimitry Andric   const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
31558b69754SDimitry Andric 
31658b69754SDimitry Andric public:
MinInstrCountEnsemble(MachineTraceMetrics * mtm)31758b69754SDimitry Andric   MinInstrCountEnsemble(MachineTraceMetrics *mtm)
31858b69754SDimitry Andric     : MachineTraceMetrics::Ensemble(mtm) {}
31958b69754SDimitry Andric };
32071d5a254SDimitry Andric 
3217fa27ce4SDimitry Andric /// Pick only the current basic block for the trace and do not choose any
3227fa27ce4SDimitry Andric /// predecessors/successors.
3237fa27ce4SDimitry Andric class LocalEnsemble : public MachineTraceMetrics::Ensemble {
getName() const3247fa27ce4SDimitry Andric   const char *getName() const override { return "Local"; }
pickTracePred(const MachineBasicBlock *)3257fa27ce4SDimitry Andric   const MachineBasicBlock *pickTracePred(const MachineBasicBlock *) override {
3267fa27ce4SDimitry Andric     return nullptr;
3277fa27ce4SDimitry Andric   };
pickTraceSucc(const MachineBasicBlock *)3287fa27ce4SDimitry Andric   const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock *) override {
3297fa27ce4SDimitry Andric     return nullptr;
3307fa27ce4SDimitry Andric   };
3317fa27ce4SDimitry Andric 
3327fa27ce4SDimitry Andric public:
LocalEnsemble(MachineTraceMetrics * MTM)3337fa27ce4SDimitry Andric   LocalEnsemble(MachineTraceMetrics *MTM)
3347fa27ce4SDimitry Andric       : MachineTraceMetrics::Ensemble(MTM) {}
3357fa27ce4SDimitry Andric };
33671d5a254SDimitry Andric } // end anonymous namespace
33758b69754SDimitry Andric 
33858b69754SDimitry Andric // Select the preferred predecessor for MBB.
33958b69754SDimitry Andric const MachineBasicBlock*
pickTracePred(const MachineBasicBlock * MBB)34058b69754SDimitry Andric MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
34158b69754SDimitry Andric   if (MBB->pred_empty())
3425ca98fd9SDimitry Andric     return nullptr;
34358b69754SDimitry Andric   const MachineLoop *CurLoop = getLoopFor(MBB);
34458b69754SDimitry Andric   // Don't leave loops, and never follow back-edges.
34558b69754SDimitry Andric   if (CurLoop && MBB == CurLoop->getHeader())
3465ca98fd9SDimitry Andric     return nullptr;
34758b69754SDimitry Andric   unsigned CurCount = MTM.getResources(MBB)->InstrCount;
3485ca98fd9SDimitry Andric   const MachineBasicBlock *Best = nullptr;
34958b69754SDimitry Andric   unsigned BestDepth = 0;
3505a5ac124SDimitry Andric   for (const MachineBasicBlock *Pred : MBB->predecessors()) {
35158b69754SDimitry Andric     const MachineTraceMetrics::TraceBlockInfo *PredTBI =
35258b69754SDimitry Andric       getDepthResources(Pred);
35358b69754SDimitry Andric     // Ignore cycles that aren't natural loops.
35458b69754SDimitry Andric     if (!PredTBI)
35558b69754SDimitry Andric       continue;
35658b69754SDimitry Andric     // Pick the predecessor that would give this block the smallest InstrDepth.
35758b69754SDimitry Andric     unsigned Depth = PredTBI->InstrDepth + CurCount;
35801095a5dSDimitry Andric     if (!Best || Depth < BestDepth) {
35901095a5dSDimitry Andric       Best = Pred;
36001095a5dSDimitry Andric       BestDepth = Depth;
36101095a5dSDimitry Andric     }
36258b69754SDimitry Andric   }
36358b69754SDimitry Andric   return Best;
36458b69754SDimitry Andric }
36558b69754SDimitry Andric 
36658b69754SDimitry Andric // Select the preferred successor for MBB.
36758b69754SDimitry Andric const MachineBasicBlock*
pickTraceSucc(const MachineBasicBlock * MBB)36858b69754SDimitry Andric MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
369e3b55780SDimitry Andric   if (MBB->succ_empty())
3705ca98fd9SDimitry Andric     return nullptr;
37158b69754SDimitry Andric   const MachineLoop *CurLoop = getLoopFor(MBB);
3725ca98fd9SDimitry Andric   const MachineBasicBlock *Best = nullptr;
37358b69754SDimitry Andric   unsigned BestHeight = 0;
3745a5ac124SDimitry Andric   for (const MachineBasicBlock *Succ : MBB->successors()) {
37558b69754SDimitry Andric     // Don't consider back-edges.
37658b69754SDimitry Andric     if (CurLoop && Succ == CurLoop->getHeader())
37758b69754SDimitry Andric       continue;
37858b69754SDimitry Andric     // Don't consider successors exiting CurLoop.
37958b69754SDimitry Andric     if (isExitingLoop(CurLoop, getLoopFor(Succ)))
38058b69754SDimitry Andric       continue;
38158b69754SDimitry Andric     const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
38258b69754SDimitry Andric       getHeightResources(Succ);
38358b69754SDimitry Andric     // Ignore cycles that aren't natural loops.
38458b69754SDimitry Andric     if (!SuccTBI)
38558b69754SDimitry Andric       continue;
38658b69754SDimitry Andric     // Pick the successor that would give this block the smallest InstrHeight.
38758b69754SDimitry Andric     unsigned Height = SuccTBI->InstrHeight;
38801095a5dSDimitry Andric     if (!Best || Height < BestHeight) {
38901095a5dSDimitry Andric       Best = Succ;
39001095a5dSDimitry Andric       BestHeight = Height;
39101095a5dSDimitry Andric     }
39258b69754SDimitry Andric   }
39358b69754SDimitry Andric   return Best;
39458b69754SDimitry Andric }
39558b69754SDimitry Andric 
39658b69754SDimitry Andric // Get an Ensemble sub-class for the requested trace strategy.
39758b69754SDimitry Andric MachineTraceMetrics::Ensemble *
getEnsemble(MachineTraceStrategy strategy)3987fa27ce4SDimitry Andric MachineTraceMetrics::getEnsemble(MachineTraceStrategy strategy) {
3997fa27ce4SDimitry Andric   assert(strategy < MachineTraceStrategy::TS_NumStrategies &&
4007fa27ce4SDimitry Andric          "Invalid trace strategy enum");
4017fa27ce4SDimitry Andric   Ensemble *&E = Ensembles[static_cast<size_t>(strategy)];
40258b69754SDimitry Andric   if (E)
40358b69754SDimitry Andric     return E;
40458b69754SDimitry Andric 
40558b69754SDimitry Andric   // Allocate new Ensemble on demand.
40658b69754SDimitry Andric   switch (strategy) {
4077fa27ce4SDimitry Andric   case MachineTraceStrategy::TS_MinInstrCount:
4087fa27ce4SDimitry Andric     return (E = new MinInstrCountEnsemble(this));
4097fa27ce4SDimitry Andric   case MachineTraceStrategy::TS_Local:
4107fa27ce4SDimitry Andric     return (E = new LocalEnsemble(this));
41158b69754SDimitry Andric   default: llvm_unreachable("Invalid trace strategy enum");
41258b69754SDimitry Andric   }
41358b69754SDimitry Andric }
41458b69754SDimitry Andric 
invalidate(const MachineBasicBlock * MBB)41558b69754SDimitry Andric void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
416eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Invalidate traces through " << printMBBReference(*MBB)
417044eb2f6SDimitry Andric                     << '\n');
41858b69754SDimitry Andric   BlockInfo[MBB->getNumber()].invalidate();
41977fc4c14SDimitry Andric   for (Ensemble *E : Ensembles)
42077fc4c14SDimitry Andric     if (E)
42177fc4c14SDimitry Andric       E->invalidate(MBB);
42258b69754SDimitry Andric }
42358b69754SDimitry Andric 
verifyAnalysis() const42458b69754SDimitry Andric void MachineTraceMetrics::verifyAnalysis() const {
42558b69754SDimitry Andric   if (!MF)
42658b69754SDimitry Andric     return;
42758b69754SDimitry Andric #ifndef NDEBUG
42858b69754SDimitry Andric   assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
42977fc4c14SDimitry Andric   for (Ensemble *E : Ensembles)
43077fc4c14SDimitry Andric     if (E)
43177fc4c14SDimitry Andric       E->verify();
43258b69754SDimitry Andric #endif
43358b69754SDimitry Andric }
43458b69754SDimitry Andric 
43558b69754SDimitry Andric //===----------------------------------------------------------------------===//
43658b69754SDimitry Andric //                               Trace building
43758b69754SDimitry Andric //===----------------------------------------------------------------------===//
43858b69754SDimitry Andric //
43958b69754SDimitry Andric // Traces are built by two CFG traversals. To avoid recomputing too much, use a
44058b69754SDimitry Andric // set abstraction that confines the search to the current loop, and doesn't
44158b69754SDimitry Andric // revisit blocks.
44258b69754SDimitry Andric 
44358b69754SDimitry Andric namespace {
44471d5a254SDimitry Andric 
44558b69754SDimitry Andric struct LoopBounds {
44658b69754SDimitry Andric   MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
44758b69754SDimitry Andric   SmallPtrSet<const MachineBasicBlock*, 8> Visited;
44858b69754SDimitry Andric   const MachineLoopInfo *Loops;
44971d5a254SDimitry Andric   bool Downward = false;
45071d5a254SDimitry Andric 
LoopBounds__anon90c290e40211::LoopBounds45158b69754SDimitry Andric   LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
45271d5a254SDimitry Andric              const MachineLoopInfo *loops) : Blocks(blocks), Loops(loops) {}
45358b69754SDimitry Andric };
45471d5a254SDimitry Andric 
45571d5a254SDimitry Andric } // end anonymous namespace
45658b69754SDimitry Andric 
45758b69754SDimitry Andric // Specialize po_iterator_storage in order to prune the post-order traversal so
45858b69754SDimitry Andric // it is limited to the current loop and doesn't traverse the loop back edges.
45958b69754SDimitry Andric namespace llvm {
46071d5a254SDimitry Andric 
46158b69754SDimitry Andric template<>
46258b69754SDimitry Andric class po_iterator_storage<LoopBounds, true> {
46358b69754SDimitry Andric   LoopBounds &LB;
46471d5a254SDimitry Andric 
46558b69754SDimitry Andric public:
po_iterator_storage(LoopBounds & lb)46658b69754SDimitry Andric   po_iterator_storage(LoopBounds &lb) : LB(lb) {}
46771d5a254SDimitry Andric 
finishPostorder(const MachineBasicBlock *)46858b69754SDimitry Andric   void finishPostorder(const MachineBasicBlock*) {}
46958b69754SDimitry Andric 
insertEdge(std::optional<const MachineBasicBlock * > From,const MachineBasicBlock * To)470e3b55780SDimitry Andric   bool insertEdge(std::optional<const MachineBasicBlock *> From,
471b915e9e0SDimitry Andric                   const MachineBasicBlock *To) {
47258b69754SDimitry Andric     // Skip already visited To blocks.
47358b69754SDimitry Andric     MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
47458b69754SDimitry Andric     if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
47558b69754SDimitry Andric       return false;
47658b69754SDimitry Andric     // From is null once when To is the trace center block.
47758b69754SDimitry Andric     if (From) {
478b915e9e0SDimitry Andric       if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(*From)) {
47958b69754SDimitry Andric         // Don't follow backedges, don't leave FromLoop when going upwards.
480b915e9e0SDimitry Andric         if ((LB.Downward ? To : *From) == FromLoop->getHeader())
48158b69754SDimitry Andric           return false;
48258b69754SDimitry Andric         // Don't leave FromLoop.
48358b69754SDimitry Andric         if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
48458b69754SDimitry Andric           return false;
48558b69754SDimitry Andric       }
48658b69754SDimitry Andric     }
48758b69754SDimitry Andric     // To is a new block. Mark the block as visited in case the CFG has cycles
48858b69754SDimitry Andric     // that MachineLoopInfo didn't recognize as a natural loop.
48967c32a98SDimitry Andric     return LB.Visited.insert(To).second;
49058b69754SDimitry Andric   }
49158b69754SDimitry Andric };
49271d5a254SDimitry Andric 
49371d5a254SDimitry Andric } // end namespace llvm
49458b69754SDimitry Andric 
49558b69754SDimitry Andric /// Compute the trace through MBB.
computeTrace(const MachineBasicBlock * MBB)49658b69754SDimitry Andric void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
497eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Computing " << getName() << " trace through "
498044eb2f6SDimitry Andric                     << printMBBReference(*MBB) << '\n');
49958b69754SDimitry Andric   // Set up loop bounds for the backwards post-order traversal.
50058b69754SDimitry Andric   LoopBounds Bounds(BlockInfo, MTM.Loops);
50158b69754SDimitry Andric 
50258b69754SDimitry Andric   // Run an upwards post-order search for the trace start.
50358b69754SDimitry Andric   Bounds.Downward = false;
50458b69754SDimitry Andric   Bounds.Visited.clear();
5054b4fe385SDimitry Andric   for (const auto *I : inverse_post_order_ext(MBB, Bounds)) {
506eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "  pred for " << printMBBReference(*I) << ": ");
50758b69754SDimitry Andric     TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
50858b69754SDimitry Andric     // All the predecessors have been visited, pick the preferred one.
5095a5ac124SDimitry Andric     TBI.Pred = pickTracePred(I);
510eb11fae6SDimitry Andric     LLVM_DEBUG({
51158b69754SDimitry Andric       if (TBI.Pred)
512044eb2f6SDimitry Andric         dbgs() << printMBBReference(*TBI.Pred) << '\n';
51358b69754SDimitry Andric       else
51458b69754SDimitry Andric         dbgs() << "null\n";
51558b69754SDimitry Andric     });
51658b69754SDimitry Andric     // The trace leading to I is now known, compute the depth resources.
5175a5ac124SDimitry Andric     computeDepthResources(I);
51858b69754SDimitry Andric   }
51958b69754SDimitry Andric 
52058b69754SDimitry Andric   // Run a downwards post-order search for the trace end.
52158b69754SDimitry Andric   Bounds.Downward = true;
52258b69754SDimitry Andric   Bounds.Visited.clear();
5234b4fe385SDimitry Andric   for (const auto *I : post_order_ext(MBB, Bounds)) {
524eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "  succ for " << printMBBReference(*I) << ": ");
52558b69754SDimitry Andric     TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
52658b69754SDimitry Andric     // All the successors have been visited, pick the preferred one.
5275a5ac124SDimitry Andric     TBI.Succ = pickTraceSucc(I);
528eb11fae6SDimitry Andric     LLVM_DEBUG({
52958b69754SDimitry Andric       if (TBI.Succ)
530044eb2f6SDimitry Andric         dbgs() << printMBBReference(*TBI.Succ) << '\n';
53158b69754SDimitry Andric       else
53258b69754SDimitry Andric         dbgs() << "null\n";
53358b69754SDimitry Andric     });
53458b69754SDimitry Andric     // The trace leaving I is now known, compute the height resources.
5355a5ac124SDimitry Andric     computeHeightResources(I);
53658b69754SDimitry Andric   }
53758b69754SDimitry Andric }
53858b69754SDimitry Andric 
53958b69754SDimitry Andric /// Invalidate traces through BadMBB.
54058b69754SDimitry Andric void
invalidate(const MachineBasicBlock * BadMBB)54158b69754SDimitry Andric MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
54258b69754SDimitry Andric   SmallVector<const MachineBasicBlock*, 16> WorkList;
54358b69754SDimitry Andric   TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
54458b69754SDimitry Andric 
54558b69754SDimitry Andric   // Invalidate height resources of blocks above MBB.
54658b69754SDimitry Andric   if (BadTBI.hasValidHeight()) {
54758b69754SDimitry Andric     BadTBI.invalidateHeight();
54858b69754SDimitry Andric     WorkList.push_back(BadMBB);
54958b69754SDimitry Andric     do {
55058b69754SDimitry Andric       const MachineBasicBlock *MBB = WorkList.pop_back_val();
551eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "Invalidate " << printMBBReference(*MBB) << ' '
552044eb2f6SDimitry Andric                         << getName() << " height.\n");
55358b69754SDimitry Andric       // Find any MBB predecessors that have MBB as their preferred successor.
55458b69754SDimitry Andric       // They are the only ones that need to be invalidated.
555ee8648bdSDimitry Andric       for (const MachineBasicBlock *Pred : MBB->predecessors()) {
556ee8648bdSDimitry Andric         TraceBlockInfo &TBI = BlockInfo[Pred->getNumber()];
55758b69754SDimitry Andric         if (!TBI.hasValidHeight())
55858b69754SDimitry Andric           continue;
55958b69754SDimitry Andric         if (TBI.Succ == MBB) {
56058b69754SDimitry Andric           TBI.invalidateHeight();
561ee8648bdSDimitry Andric           WorkList.push_back(Pred);
56258b69754SDimitry Andric           continue;
56358b69754SDimitry Andric         }
56458b69754SDimitry Andric         // Verify that TBI.Succ is actually a *I successor.
565ee8648bdSDimitry Andric         assert((!TBI.Succ || Pred->isSuccessor(TBI.Succ)) && "CFG changed");
56658b69754SDimitry Andric       }
56758b69754SDimitry Andric     } while (!WorkList.empty());
56858b69754SDimitry Andric   }
56958b69754SDimitry Andric 
57058b69754SDimitry Andric   // Invalidate depth resources of blocks below MBB.
57158b69754SDimitry Andric   if (BadTBI.hasValidDepth()) {
57258b69754SDimitry Andric     BadTBI.invalidateDepth();
57358b69754SDimitry Andric     WorkList.push_back(BadMBB);
57458b69754SDimitry Andric     do {
57558b69754SDimitry Andric       const MachineBasicBlock *MBB = WorkList.pop_back_val();
576eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "Invalidate " << printMBBReference(*MBB) << ' '
577044eb2f6SDimitry Andric                         << getName() << " depth.\n");
57858b69754SDimitry Andric       // Find any MBB successors that have MBB as their preferred predecessor.
57958b69754SDimitry Andric       // They are the only ones that need to be invalidated.
580ee8648bdSDimitry Andric       for (const MachineBasicBlock *Succ : MBB->successors()) {
581ee8648bdSDimitry Andric         TraceBlockInfo &TBI = BlockInfo[Succ->getNumber()];
58258b69754SDimitry Andric         if (!TBI.hasValidDepth())
58358b69754SDimitry Andric           continue;
58458b69754SDimitry Andric         if (TBI.Pred == MBB) {
58558b69754SDimitry Andric           TBI.invalidateDepth();
586ee8648bdSDimitry Andric           WorkList.push_back(Succ);
58758b69754SDimitry Andric           continue;
58858b69754SDimitry Andric         }
58958b69754SDimitry Andric         // Verify that TBI.Pred is actually a *I predecessor.
590ee8648bdSDimitry Andric         assert((!TBI.Pred || Succ->isPredecessor(TBI.Pred)) && "CFG changed");
59158b69754SDimitry Andric       }
59258b69754SDimitry Andric     } while (!WorkList.empty());
59358b69754SDimitry Andric   }
59458b69754SDimitry Andric 
59558b69754SDimitry Andric   // Clear any per-instruction data. We only have to do this for BadMBB itself
59658b69754SDimitry Andric   // because the instructions in that block may change. Other blocks may be
59758b69754SDimitry Andric   // invalidated, but their instructions will stay the same, so there is no
59858b69754SDimitry Andric   // need to erase the Cycle entries. They will be overwritten when we
59958b69754SDimitry Andric   // recompute.
6005ca98fd9SDimitry Andric   for (const auto &I : *BadMBB)
6015ca98fd9SDimitry Andric     Cycles.erase(&I);
60258b69754SDimitry Andric }
60358b69754SDimitry Andric 
verify() const60458b69754SDimitry Andric void MachineTraceMetrics::Ensemble::verify() const {
60558b69754SDimitry Andric #ifndef NDEBUG
60658b69754SDimitry Andric   assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
60758b69754SDimitry Andric          "Outdated BlockInfo size");
60858b69754SDimitry Andric   for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
60958b69754SDimitry Andric     const TraceBlockInfo &TBI = BlockInfo[Num];
61058b69754SDimitry Andric     if (TBI.hasValidDepth() && TBI.Pred) {
61158b69754SDimitry Andric       const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
61258b69754SDimitry Andric       assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
61358b69754SDimitry Andric       assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
61458b69754SDimitry Andric              "Trace is broken, depth should have been invalidated.");
61558b69754SDimitry Andric       const MachineLoop *Loop = getLoopFor(MBB);
61658b69754SDimitry Andric       assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
61758b69754SDimitry Andric     }
61858b69754SDimitry Andric     if (TBI.hasValidHeight() && TBI.Succ) {
61958b69754SDimitry Andric       const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
62058b69754SDimitry Andric       assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
62158b69754SDimitry Andric       assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
62258b69754SDimitry Andric              "Trace is broken, height should have been invalidated.");
62358b69754SDimitry Andric       const MachineLoop *Loop = getLoopFor(MBB);
62458b69754SDimitry Andric       const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
62558b69754SDimitry Andric       assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
62658b69754SDimitry Andric              "Trace contains backedge");
62758b69754SDimitry Andric     }
62858b69754SDimitry Andric   }
62958b69754SDimitry Andric #endif
63058b69754SDimitry Andric }
63158b69754SDimitry Andric 
63258b69754SDimitry Andric //===----------------------------------------------------------------------===//
63358b69754SDimitry Andric //                             Data Dependencies
63458b69754SDimitry Andric //===----------------------------------------------------------------------===//
63558b69754SDimitry Andric //
63658b69754SDimitry Andric // Compute the depth and height of each instruction based on data dependencies
63758b69754SDimitry Andric // and instruction latencies. These cycle numbers assume that the CPU can issue
63858b69754SDimitry Andric // an infinite number of instructions per cycle as long as their dependencies
63958b69754SDimitry Andric // are ready.
64058b69754SDimitry Andric 
64158b69754SDimitry Andric // A data dependency is represented as a defining MI and operand numbers on the
64258b69754SDimitry Andric // defining and using MI.
64358b69754SDimitry Andric namespace {
64471d5a254SDimitry Andric 
64558b69754SDimitry Andric struct DataDep {
64658b69754SDimitry Andric   const MachineInstr *DefMI;
64758b69754SDimitry Andric   unsigned DefOp;
64858b69754SDimitry Andric   unsigned UseOp;
64958b69754SDimitry Andric 
DataDep__anon90c290e40311::DataDep65058b69754SDimitry Andric   DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
65158b69754SDimitry Andric     : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
65258b69754SDimitry Andric 
65358b69754SDimitry Andric   /// Create a DataDep from an SSA form virtual register.
DataDep__anon90c290e40311::DataDep65458b69754SDimitry Andric   DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
65558b69754SDimitry Andric     : UseOp(UseOp) {
6561d5ae102SDimitry Andric     assert(Register::isVirtualRegister(VirtReg));
65758b69754SDimitry Andric     MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
65858b69754SDimitry Andric     assert(!DefI.atEnd() && "Register has no defs");
6595ca98fd9SDimitry Andric     DefMI = DefI->getParent();
66058b69754SDimitry Andric     DefOp = DefI.getOperandNo();
66158b69754SDimitry Andric     assert((++DefI).atEnd() && "Register has multiple defs");
66258b69754SDimitry Andric   }
66358b69754SDimitry Andric };
66471d5a254SDimitry Andric 
66571d5a254SDimitry Andric } // end anonymous namespace
66658b69754SDimitry Andric 
66758b69754SDimitry Andric // Get the input data dependencies that must be ready before UseMI can issue.
66858b69754SDimitry Andric // Return true if UseMI has any physreg operands.
getDataDeps(const MachineInstr & UseMI,SmallVectorImpl<DataDep> & Deps,const MachineRegisterInfo * MRI)66901095a5dSDimitry Andric static bool getDataDeps(const MachineInstr &UseMI,
67058b69754SDimitry Andric                         SmallVectorImpl<DataDep> &Deps,
67158b69754SDimitry Andric                         const MachineRegisterInfo *MRI) {
67269156b4cSDimitry Andric   // Debug values should not be included in any calculations.
673eb11fae6SDimitry Andric   if (UseMI.isDebugInstr())
67469156b4cSDimitry Andric     return false;
67569156b4cSDimitry Andric 
67658b69754SDimitry Andric   bool HasPhysRegs = false;
6777fa27ce4SDimitry Andric   for (const MachineOperand &MO : UseMI.operands()) {
67885d8b2bbSDimitry Andric     if (!MO.isReg())
67958b69754SDimitry Andric       continue;
6801d5ae102SDimitry Andric     Register Reg = MO.getReg();
68158b69754SDimitry Andric     if (!Reg)
68258b69754SDimitry Andric       continue;
683e3b55780SDimitry Andric     if (Reg.isPhysical()) {
68458b69754SDimitry Andric       HasPhysRegs = true;
68558b69754SDimitry Andric       continue;
68658b69754SDimitry Andric     }
68758b69754SDimitry Andric     // Collect virtual register reads.
68885d8b2bbSDimitry Andric     if (MO.readsReg())
6897fa27ce4SDimitry Andric       Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
69058b69754SDimitry Andric   }
69158b69754SDimitry Andric   return HasPhysRegs;
69258b69754SDimitry Andric }
69358b69754SDimitry Andric 
69458b69754SDimitry Andric // Get the input data dependencies of a PHI instruction, using Pred as the
69558b69754SDimitry Andric // preferred predecessor.
69658b69754SDimitry Andric // This will add at most one dependency to Deps.
getPHIDeps(const MachineInstr & UseMI,SmallVectorImpl<DataDep> & Deps,const MachineBasicBlock * Pred,const MachineRegisterInfo * MRI)69701095a5dSDimitry Andric static void getPHIDeps(const MachineInstr &UseMI,
69858b69754SDimitry Andric                        SmallVectorImpl<DataDep> &Deps,
69958b69754SDimitry Andric                        const MachineBasicBlock *Pred,
70058b69754SDimitry Andric                        const MachineRegisterInfo *MRI) {
70158b69754SDimitry Andric   // No predecessor at the beginning of a trace. Ignore dependencies.
70258b69754SDimitry Andric   if (!Pred)
70358b69754SDimitry Andric     return;
70401095a5dSDimitry Andric   assert(UseMI.isPHI() && UseMI.getNumOperands() % 2 && "Bad PHI");
70501095a5dSDimitry Andric   for (unsigned i = 1; i != UseMI.getNumOperands(); i += 2) {
70601095a5dSDimitry Andric     if (UseMI.getOperand(i + 1).getMBB() == Pred) {
7071d5ae102SDimitry Andric       Register Reg = UseMI.getOperand(i).getReg();
70858b69754SDimitry Andric       Deps.push_back(DataDep(MRI, Reg, i));
70958b69754SDimitry Andric       return;
71058b69754SDimitry Andric     }
71158b69754SDimitry Andric   }
71258b69754SDimitry Andric }
71358b69754SDimitry Andric 
71458b69754SDimitry Andric // Identify physreg dependencies for UseMI, and update the live regunit
71558b69754SDimitry Andric // tracking set when scanning instructions downwards.
updatePhysDepsDownwards(const MachineInstr * UseMI,SmallVectorImpl<DataDep> & Deps,SparseSet<LiveRegUnit> & RegUnits,const TargetRegisterInfo * TRI)71658b69754SDimitry Andric static void updatePhysDepsDownwards(const MachineInstr *UseMI,
71758b69754SDimitry Andric                                     SmallVectorImpl<DataDep> &Deps,
71858b69754SDimitry Andric                                     SparseSet<LiveRegUnit> &RegUnits,
71958b69754SDimitry Andric                                     const TargetRegisterInfo *TRI) {
720b60736ecSDimitry Andric   SmallVector<MCRegister, 8> Kills;
72158b69754SDimitry Andric   SmallVector<unsigned, 8> LiveDefOps;
72258b69754SDimitry Andric 
7237fa27ce4SDimitry Andric   for (const MachineOperand &MO : UseMI->operands()) {
724b60736ecSDimitry Andric     if (!MO.isReg() || !MO.getReg().isPhysical())
72558b69754SDimitry Andric       continue;
726b60736ecSDimitry Andric     MCRegister Reg = MO.getReg().asMCReg();
72758b69754SDimitry Andric     // Track live defs and kills for updating RegUnits.
72885d8b2bbSDimitry Andric     if (MO.isDef()) {
72985d8b2bbSDimitry Andric       if (MO.isDead())
73058b69754SDimitry Andric         Kills.push_back(Reg);
73158b69754SDimitry Andric       else
7327fa27ce4SDimitry Andric         LiveDefOps.push_back(MO.getOperandNo());
73385d8b2bbSDimitry Andric     } else if (MO.isKill())
73458b69754SDimitry Andric       Kills.push_back(Reg);
73558b69754SDimitry Andric     // Identify dependencies.
73685d8b2bbSDimitry Andric     if (!MO.readsReg())
73758b69754SDimitry Andric       continue;
7387fa27ce4SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(Reg)) {
7397fa27ce4SDimitry Andric       SparseSet<LiveRegUnit>::iterator I = RegUnits.find(Unit);
74058b69754SDimitry Andric       if (I == RegUnits.end())
74158b69754SDimitry Andric         continue;
7427fa27ce4SDimitry Andric       Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
74358b69754SDimitry Andric       break;
74458b69754SDimitry Andric     }
74558b69754SDimitry Andric   }
74658b69754SDimitry Andric 
74758b69754SDimitry Andric   // Update RegUnits to reflect live registers after UseMI.
74858b69754SDimitry Andric   // First kills.
749b60736ecSDimitry Andric   for (MCRegister Kill : Kills)
7507fa27ce4SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(Kill))
7517fa27ce4SDimitry Andric       RegUnits.erase(Unit);
75258b69754SDimitry Andric 
75358b69754SDimitry Andric   // Second, live defs.
754dd58ef01SDimitry Andric   for (unsigned DefOp : LiveDefOps) {
7557fa27ce4SDimitry Andric     for (MCRegUnit Unit :
7567fa27ce4SDimitry Andric          TRI->regunits(UseMI->getOperand(DefOp).getReg().asMCReg())) {
7577fa27ce4SDimitry Andric       LiveRegUnit &LRU = RegUnits[Unit];
75858b69754SDimitry Andric       LRU.MI = UseMI;
75958b69754SDimitry Andric       LRU.Op = DefOp;
76058b69754SDimitry Andric     }
76158b69754SDimitry Andric   }
76258b69754SDimitry Andric }
76358b69754SDimitry Andric 
76458b69754SDimitry Andric /// The length of the critical path through a trace is the maximum of two path
76558b69754SDimitry Andric /// lengths:
76658b69754SDimitry Andric ///
76758b69754SDimitry Andric /// 1. The maximum height+depth over all instructions in the trace center block.
76858b69754SDimitry Andric ///
76958b69754SDimitry Andric /// 2. The longest cross-block dependency chain. For small blocks, it is
77058b69754SDimitry Andric ///    possible that the critical path through the trace doesn't include any
77158b69754SDimitry Andric ///    instructions in the block.
77258b69754SDimitry Andric ///
77358b69754SDimitry Andric /// This function computes the second number from the live-in list of the
77458b69754SDimitry Andric /// center block.
77558b69754SDimitry Andric unsigned MachineTraceMetrics::Ensemble::
computeCrossBlockCriticalPath(const TraceBlockInfo & TBI)77658b69754SDimitry Andric computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
77758b69754SDimitry Andric   assert(TBI.HasValidInstrDepths && "Missing depth info");
77858b69754SDimitry Andric   assert(TBI.HasValidInstrHeights && "Missing height info");
77958b69754SDimitry Andric   unsigned MaxLen = 0;
780dd58ef01SDimitry Andric   for (const LiveInReg &LIR : TBI.LiveIns) {
781b60736ecSDimitry Andric     if (!LIR.Reg.isVirtual())
78258b69754SDimitry Andric       continue;
78358b69754SDimitry Andric     const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
78458b69754SDimitry Andric     // Ignore dependencies outside the current trace.
78558b69754SDimitry Andric     const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
7864a16efa3SDimitry Andric     if (!DefTBI.isUsefulDominator(TBI))
78758b69754SDimitry Andric       continue;
78858b69754SDimitry Andric     unsigned Len = LIR.Height + Cycles[DefMI].Depth;
78958b69754SDimitry Andric     MaxLen = std::max(MaxLen, Len);
79058b69754SDimitry Andric   }
79158b69754SDimitry Andric   return MaxLen;
79258b69754SDimitry Andric }
79358b69754SDimitry Andric 
79458b69754SDimitry Andric void MachineTraceMetrics::Ensemble::
updateDepth(MachineTraceMetrics::TraceBlockInfo & TBI,const MachineInstr & UseMI,SparseSet<LiveRegUnit> & RegUnits)795044eb2f6SDimitry Andric updateDepth(MachineTraceMetrics::TraceBlockInfo &TBI, const MachineInstr &UseMI,
796044eb2f6SDimitry Andric             SparseSet<LiveRegUnit> &RegUnits) {
79758b69754SDimitry Andric   SmallVector<DataDep, 8> Deps;
79858b69754SDimitry Andric   // Collect all data dependencies.
7995ca98fd9SDimitry Andric   if (UseMI.isPHI())
80001095a5dSDimitry Andric     getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
80101095a5dSDimitry Andric   else if (getDataDeps(UseMI, Deps, MTM.MRI))
8025ca98fd9SDimitry Andric     updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
80358b69754SDimitry Andric 
80458b69754SDimitry Andric   // Filter and process dependencies, computing the earliest issue cycle.
80558b69754SDimitry Andric   unsigned Cycle = 0;
8061a82d4c0SDimitry Andric   for (const DataDep &Dep : Deps) {
80758b69754SDimitry Andric     const TraceBlockInfo&DepTBI =
80858b69754SDimitry Andric       BlockInfo[Dep.DefMI->getParent()->getNumber()];
80958b69754SDimitry Andric     // Ignore dependencies from outside the current trace.
8104a16efa3SDimitry Andric     if (!DepTBI.isUsefulDominator(TBI))
81158b69754SDimitry Andric       continue;
81258b69754SDimitry Andric     assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
81358b69754SDimitry Andric     unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
81458b69754SDimitry Andric     // Add latency if DefMI is a real instruction. Transients get latency 0.
81558b69754SDimitry Andric     if (!Dep.DefMI->isTransient())
816522600a2SDimitry Andric       DepCycle += MTM.SchedModel
8175ca98fd9SDimitry Andric         .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
81858b69754SDimitry Andric     Cycle = std::max(Cycle, DepCycle);
81958b69754SDimitry Andric   }
82058b69754SDimitry Andric   // Remember the instruction depth.
8215ca98fd9SDimitry Andric   InstrCycles &MICycles = Cycles[&UseMI];
82258b69754SDimitry Andric   MICycles.Depth = Cycle;
82358b69754SDimitry Andric 
824044eb2f6SDimitry Andric   if (TBI.HasValidInstrHeights) {
82558b69754SDimitry Andric     // Update critical path length.
82658b69754SDimitry Andric     TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
827eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
828044eb2f6SDimitry Andric   } else {
829eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << Cycle << '\t' << UseMI);
830044eb2f6SDimitry Andric   }
831044eb2f6SDimitry Andric }
832044eb2f6SDimitry Andric 
833044eb2f6SDimitry Andric void MachineTraceMetrics::Ensemble::
updateDepth(const MachineBasicBlock * MBB,const MachineInstr & UseMI,SparseSet<LiveRegUnit> & RegUnits)834044eb2f6SDimitry Andric updateDepth(const MachineBasicBlock *MBB, const MachineInstr &UseMI,
835044eb2f6SDimitry Andric             SparseSet<LiveRegUnit> &RegUnits) {
836044eb2f6SDimitry Andric   updateDepth(BlockInfo[MBB->getNumber()], UseMI, RegUnits);
837044eb2f6SDimitry Andric }
838044eb2f6SDimitry Andric 
839044eb2f6SDimitry Andric void MachineTraceMetrics::Ensemble::
updateDepths(MachineBasicBlock::iterator Start,MachineBasicBlock::iterator End,SparseSet<LiveRegUnit> & RegUnits)840044eb2f6SDimitry Andric updateDepths(MachineBasicBlock::iterator Start,
841044eb2f6SDimitry Andric              MachineBasicBlock::iterator End,
842044eb2f6SDimitry Andric              SparseSet<LiveRegUnit> &RegUnits) {
843044eb2f6SDimitry Andric     for (; Start != End; Start++)
844044eb2f6SDimitry Andric       updateDepth(Start->getParent(), *Start, RegUnits);
845044eb2f6SDimitry Andric }
846044eb2f6SDimitry Andric 
847044eb2f6SDimitry Andric /// Compute instruction depths for all instructions above or in MBB in its
848044eb2f6SDimitry Andric /// trace. This assumes that the trace through MBB has already been computed.
849044eb2f6SDimitry Andric void MachineTraceMetrics::Ensemble::
computeInstrDepths(const MachineBasicBlock * MBB)850044eb2f6SDimitry Andric computeInstrDepths(const MachineBasicBlock *MBB) {
851044eb2f6SDimitry Andric   // The top of the trace may already be computed, and HasValidInstrDepths
852044eb2f6SDimitry Andric   // implies Head->HasValidInstrDepths, so we only need to start from the first
853044eb2f6SDimitry Andric   // block in the trace that needs to be recomputed.
854044eb2f6SDimitry Andric   SmallVector<const MachineBasicBlock*, 8> Stack;
855044eb2f6SDimitry Andric   do {
856044eb2f6SDimitry Andric     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
857044eb2f6SDimitry Andric     assert(TBI.hasValidDepth() && "Incomplete trace");
858044eb2f6SDimitry Andric     if (TBI.HasValidInstrDepths)
859044eb2f6SDimitry Andric       break;
860044eb2f6SDimitry Andric     Stack.push_back(MBB);
861044eb2f6SDimitry Andric     MBB = TBI.Pred;
862044eb2f6SDimitry Andric   } while (MBB);
863044eb2f6SDimitry Andric 
864044eb2f6SDimitry Andric   // FIXME: If MBB is non-null at this point, it is the last pre-computed block
865044eb2f6SDimitry Andric   // in the trace. We should track any live-out physregs that were defined in
866044eb2f6SDimitry Andric   // the trace. This is quite rare in SSA form, typically created by CSE
867044eb2f6SDimitry Andric   // hoisting a compare.
868044eb2f6SDimitry Andric   SparseSet<LiveRegUnit> RegUnits;
869044eb2f6SDimitry Andric   RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
870044eb2f6SDimitry Andric 
871044eb2f6SDimitry Andric   // Go through trace blocks in top-down order, stopping after the center block.
872044eb2f6SDimitry Andric   while (!Stack.empty()) {
873044eb2f6SDimitry Andric     MBB = Stack.pop_back_val();
874eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "\nDepths for " << printMBBReference(*MBB) << ":\n");
875044eb2f6SDimitry Andric     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
876044eb2f6SDimitry Andric     TBI.HasValidInstrDepths = true;
877044eb2f6SDimitry Andric     TBI.CriticalPath = 0;
878044eb2f6SDimitry Andric 
879044eb2f6SDimitry Andric     // Print out resource depths here as well.
880eb11fae6SDimitry Andric     LLVM_DEBUG({
881044eb2f6SDimitry Andric       dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
882044eb2f6SDimitry Andric       ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
883044eb2f6SDimitry Andric       for (unsigned K = 0; K != PRDepths.size(); ++K)
884044eb2f6SDimitry Andric         if (PRDepths[K]) {
885044eb2f6SDimitry Andric           unsigned Factor = MTM.SchedModel.getResourceFactor(K);
886044eb2f6SDimitry Andric           dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
887044eb2f6SDimitry Andric                  << MTM.SchedModel.getProcResource(K)->Name << " ("
888044eb2f6SDimitry Andric                  << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
889044eb2f6SDimitry Andric         }
890044eb2f6SDimitry Andric     });
891044eb2f6SDimitry Andric 
892044eb2f6SDimitry Andric     // Also compute the critical path length through MBB when possible.
893044eb2f6SDimitry Andric     if (TBI.HasValidInstrHeights)
894044eb2f6SDimitry Andric       TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
895044eb2f6SDimitry Andric 
896044eb2f6SDimitry Andric     for (const auto &UseMI : *MBB) {
897044eb2f6SDimitry Andric       updateDepth(TBI, UseMI, RegUnits);
89858b69754SDimitry Andric     }
89958b69754SDimitry Andric   }
90058b69754SDimitry Andric }
90158b69754SDimitry Andric 
90258b69754SDimitry Andric // Identify physreg dependencies for MI when scanning instructions upwards.
90358b69754SDimitry Andric // Return the issue height of MI after considering any live regunits.
90458b69754SDimitry Andric // Height is the issue height computed from virtual register dependencies alone.
updatePhysDepsUpwards(const MachineInstr & MI,unsigned Height,SparseSet<LiveRegUnit> & RegUnits,const TargetSchedModel & SchedModel,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI)90501095a5dSDimitry Andric static unsigned updatePhysDepsUpwards(const MachineInstr &MI, unsigned Height,
90658b69754SDimitry Andric                                       SparseSet<LiveRegUnit> &RegUnits,
907522600a2SDimitry Andric                                       const TargetSchedModel &SchedModel,
90858b69754SDimitry Andric                                       const TargetInstrInfo *TII,
90958b69754SDimitry Andric                                       const TargetRegisterInfo *TRI) {
91058b69754SDimitry Andric   SmallVector<unsigned, 8> ReadOps;
91185d8b2bbSDimitry Andric 
9127fa27ce4SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
91385d8b2bbSDimitry Andric     if (!MO.isReg())
91458b69754SDimitry Andric       continue;
9151d5ae102SDimitry Andric     Register Reg = MO.getReg();
916e3b55780SDimitry Andric     if (!Reg.isPhysical())
91758b69754SDimitry Andric       continue;
91885d8b2bbSDimitry Andric     if (MO.readsReg())
9197fa27ce4SDimitry Andric       ReadOps.push_back(MO.getOperandNo());
92085d8b2bbSDimitry Andric     if (!MO.isDef())
92158b69754SDimitry Andric       continue;
92258b69754SDimitry Andric     // This is a def of Reg. Remove corresponding entries from RegUnits, and
92358b69754SDimitry Andric     // update MI Height to consider the physreg dependencies.
9247fa27ce4SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg())) {
9257fa27ce4SDimitry Andric       SparseSet<LiveRegUnit>::iterator I = RegUnits.find(Unit);
92658b69754SDimitry Andric       if (I == RegUnits.end())
92758b69754SDimitry Andric         continue;
92858b69754SDimitry Andric       unsigned DepHeight = I->Cycle;
92901095a5dSDimitry Andric       if (!MI.isTransient()) {
93058b69754SDimitry Andric         // We may not know the UseMI of this dependency, if it came from the
931522600a2SDimitry Andric         // live-in list. SchedModel can handle a NULL UseMI.
9327fa27ce4SDimitry Andric         DepHeight += SchedModel.computeOperandLatency(&MI, MO.getOperandNo(),
93301095a5dSDimitry Andric                                                       I->MI, I->Op);
93458b69754SDimitry Andric       }
93558b69754SDimitry Andric       Height = std::max(Height, DepHeight);
93658b69754SDimitry Andric       // This regunit is dead above MI.
93758b69754SDimitry Andric       RegUnits.erase(I);
93858b69754SDimitry Andric     }
93958b69754SDimitry Andric   }
94058b69754SDimitry Andric 
94158b69754SDimitry Andric   // Now we know the height of MI. Update any regunits read.
942ac9a064cSDimitry Andric   for (unsigned Op : ReadOps) {
943ac9a064cSDimitry Andric     MCRegister Reg = MI.getOperand(Op).getReg().asMCReg();
9447fa27ce4SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(Reg)) {
9457fa27ce4SDimitry Andric       LiveRegUnit &LRU = RegUnits[Unit];
94658b69754SDimitry Andric       // Set the height to the highest reader of the unit.
94701095a5dSDimitry Andric       if (LRU.Cycle <= Height && LRU.MI != &MI) {
94858b69754SDimitry Andric         LRU.Cycle = Height;
94901095a5dSDimitry Andric         LRU.MI = &MI;
950ac9a064cSDimitry Andric         LRU.Op = Op;
95158b69754SDimitry Andric       }
95258b69754SDimitry Andric     }
95358b69754SDimitry Andric   }
95458b69754SDimitry Andric 
95558b69754SDimitry Andric   return Height;
95658b69754SDimitry Andric }
95758b69754SDimitry Andric 
958044eb2f6SDimitry Andric using MIHeightMap = DenseMap<const MachineInstr *, unsigned>;
95958b69754SDimitry Andric 
96058b69754SDimitry Andric // Push the height of DefMI upwards if required to match UseMI.
96158b69754SDimitry Andric // Return true if this is the first time DefMI was seen.
pushDepHeight(const DataDep & Dep,const MachineInstr & UseMI,unsigned UseHeight,MIHeightMap & Heights,const TargetSchedModel & SchedModel,const TargetInstrInfo * TII)96201095a5dSDimitry Andric static bool pushDepHeight(const DataDep &Dep, const MachineInstr &UseMI,
96301095a5dSDimitry Andric                           unsigned UseHeight, MIHeightMap &Heights,
964522600a2SDimitry Andric                           const TargetSchedModel &SchedModel,
96558b69754SDimitry Andric                           const TargetInstrInfo *TII) {
96658b69754SDimitry Andric   // Adjust height by Dep.DefMI latency.
96758b69754SDimitry Andric   if (!Dep.DefMI->isTransient())
96801095a5dSDimitry Andric     UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI,
96901095a5dSDimitry Andric                                                   Dep.UseOp);
97058b69754SDimitry Andric 
97158b69754SDimitry Andric   // Update Heights[DefMI] to be the maximum height seen.
97258b69754SDimitry Andric   MIHeightMap::iterator I;
97358b69754SDimitry Andric   bool New;
9745ca98fd9SDimitry Andric   std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
97558b69754SDimitry Andric   if (New)
97658b69754SDimitry Andric     return true;
97758b69754SDimitry Andric 
97858b69754SDimitry Andric   // DefMI has been pushed before. Give it the max height.
97958b69754SDimitry Andric   if (I->second < UseHeight)
98058b69754SDimitry Andric     I->second = UseHeight;
98158b69754SDimitry Andric   return false;
98258b69754SDimitry Andric }
98358b69754SDimitry Andric 
984522600a2SDimitry Andric /// Assuming that the virtual register defined by DefMI:DefOp was used by
985522600a2SDimitry Andric /// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
986522600a2SDimitry Andric /// when reaching the block that contains DefMI.
98758b69754SDimitry Andric void MachineTraceMetrics::Ensemble::
addLiveIns(const MachineInstr * DefMI,unsigned DefOp,ArrayRef<const MachineBasicBlock * > Trace)988522600a2SDimitry Andric addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
98958b69754SDimitry Andric            ArrayRef<const MachineBasicBlock*> Trace) {
99058b69754SDimitry Andric   assert(!Trace.empty() && "Trace should contain at least one block");
991b60736ecSDimitry Andric   Register Reg = DefMI->getOperand(DefOp).getReg();
992e3b55780SDimitry Andric   assert(Reg.isVirtual());
99358b69754SDimitry Andric   const MachineBasicBlock *DefMBB = DefMI->getParent();
99458b69754SDimitry Andric 
99558b69754SDimitry Andric   // Reg is live-in to all blocks in Trace that follow DefMBB.
99677fc4c14SDimitry Andric   for (const MachineBasicBlock *MBB : llvm::reverse(Trace)) {
99758b69754SDimitry Andric     if (MBB == DefMBB)
99858b69754SDimitry Andric       return;
99958b69754SDimitry Andric     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
100058b69754SDimitry Andric     // Just add the register. The height will be updated later.
100158b69754SDimitry Andric     TBI.LiveIns.push_back(Reg);
100258b69754SDimitry Andric   }
100358b69754SDimitry Andric }
100458b69754SDimitry Andric 
100558b69754SDimitry Andric /// Compute instruction heights in the trace through MBB. This updates MBB and
100658b69754SDimitry Andric /// the blocks below it in the trace. It is assumed that the trace has already
100758b69754SDimitry Andric /// been computed.
100858b69754SDimitry Andric void MachineTraceMetrics::Ensemble::
computeInstrHeights(const MachineBasicBlock * MBB)100958b69754SDimitry Andric computeInstrHeights(const MachineBasicBlock *MBB) {
101058b69754SDimitry Andric   // The bottom of the trace may already be computed.
101158b69754SDimitry Andric   // Find the blocks that need updating.
101258b69754SDimitry Andric   SmallVector<const MachineBasicBlock*, 8> Stack;
101358b69754SDimitry Andric   do {
101458b69754SDimitry Andric     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
101558b69754SDimitry Andric     assert(TBI.hasValidHeight() && "Incomplete trace");
101658b69754SDimitry Andric     if (TBI.HasValidInstrHeights)
101758b69754SDimitry Andric       break;
101858b69754SDimitry Andric     Stack.push_back(MBB);
101958b69754SDimitry Andric     TBI.LiveIns.clear();
102058b69754SDimitry Andric     MBB = TBI.Succ;
102158b69754SDimitry Andric   } while (MBB);
102258b69754SDimitry Andric 
102358b69754SDimitry Andric   // As we move upwards in the trace, keep track of instructions that are
102458b69754SDimitry Andric   // required by deeper trace instructions. Map MI -> height required so far.
102558b69754SDimitry Andric   MIHeightMap Heights;
102658b69754SDimitry Andric 
102758b69754SDimitry Andric   // For physregs, the def isn't known when we see the use.
102858b69754SDimitry Andric   // Instead, keep track of the highest use of each regunit.
102958b69754SDimitry Andric   SparseSet<LiveRegUnit> RegUnits;
103058b69754SDimitry Andric   RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
103158b69754SDimitry Andric 
103258b69754SDimitry Andric   // If the bottom of the trace was already precomputed, initialize heights
103358b69754SDimitry Andric   // from its live-in list.
103458b69754SDimitry Andric   // MBB is the highest precomputed block in the trace.
103558b69754SDimitry Andric   if (MBB) {
103658b69754SDimitry Andric     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1037ee8648bdSDimitry Andric     for (LiveInReg &LI : TBI.LiveIns) {
1038b60736ecSDimitry Andric       if (LI.Reg.isVirtual()) {
103958b69754SDimitry Andric         // For virtual registers, the def latency is included.
104058b69754SDimitry Andric         unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
104158b69754SDimitry Andric         if (Height < LI.Height)
104258b69754SDimitry Andric           Height = LI.Height;
104358b69754SDimitry Andric       } else {
104458b69754SDimitry Andric         // For register units, the def latency is not included because we don't
104558b69754SDimitry Andric         // know the def yet.
104658b69754SDimitry Andric         RegUnits[LI.Reg].Cycle = LI.Height;
104758b69754SDimitry Andric       }
104858b69754SDimitry Andric     }
104958b69754SDimitry Andric   }
105058b69754SDimitry Andric 
105158b69754SDimitry Andric   // Go through the trace blocks in bottom-up order.
105258b69754SDimitry Andric   SmallVector<DataDep, 8> Deps;
105358b69754SDimitry Andric   for (;!Stack.empty(); Stack.pop_back()) {
105458b69754SDimitry Andric     MBB = Stack.back();
1055eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Heights for " << printMBBReference(*MBB) << ":\n");
105658b69754SDimitry Andric     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
105758b69754SDimitry Andric     TBI.HasValidInstrHeights = true;
105858b69754SDimitry Andric     TBI.CriticalPath = 0;
105958b69754SDimitry Andric 
1060eb11fae6SDimitry Andric     LLVM_DEBUG({
10614a16efa3SDimitry Andric       dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
10624a16efa3SDimitry Andric       ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
10634a16efa3SDimitry Andric       for (unsigned K = 0; K != PRHeights.size(); ++K)
10644a16efa3SDimitry Andric         if (PRHeights[K]) {
10654a16efa3SDimitry Andric           unsigned Factor = MTM.SchedModel.getResourceFactor(K);
10664a16efa3SDimitry Andric           dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
10674a16efa3SDimitry Andric                  << MTM.SchedModel.getProcResource(K)->Name << " ("
10684a16efa3SDimitry Andric                  << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
10694a16efa3SDimitry Andric         }
10704a16efa3SDimitry Andric     });
10714a16efa3SDimitry Andric 
107258b69754SDimitry Andric     // Get dependencies from PHIs in the trace successor.
107358b69754SDimitry Andric     const MachineBasicBlock *Succ = TBI.Succ;
107458b69754SDimitry Andric     // If MBB is the last block in the trace, and it has a back-edge to the
107558b69754SDimitry Andric     // loop header, get loop-carried dependencies from PHIs in the header. For
107658b69754SDimitry Andric     // that purpose, pretend that all the loop header PHIs have height 0.
107758b69754SDimitry Andric     if (!Succ)
107858b69754SDimitry Andric       if (const MachineLoop *Loop = getLoopFor(MBB))
107958b69754SDimitry Andric         if (MBB->isSuccessor(Loop->getHeader()))
108058b69754SDimitry Andric           Succ = Loop->getHeader();
108158b69754SDimitry Andric 
108258b69754SDimitry Andric     if (Succ) {
10835ca98fd9SDimitry Andric       for (const auto &PHI : *Succ) {
10845ca98fd9SDimitry Andric         if (!PHI.isPHI())
10855ca98fd9SDimitry Andric           break;
108658b69754SDimitry Andric         Deps.clear();
108701095a5dSDimitry Andric         getPHIDeps(PHI, Deps, MBB, MTM.MRI);
108858b69754SDimitry Andric         if (!Deps.empty()) {
108958b69754SDimitry Andric           // Loop header PHI heights are all 0.
10905ca98fd9SDimitry Andric           unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1091eb11fae6SDimitry Andric           LLVM_DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
109201095a5dSDimitry Andric           if (pushDepHeight(Deps.front(), PHI, Height, Heights, MTM.SchedModel,
109301095a5dSDimitry Andric                             MTM.TII))
1094522600a2SDimitry Andric             addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
109558b69754SDimitry Andric         }
109658b69754SDimitry Andric       }
109758b69754SDimitry Andric     }
109858b69754SDimitry Andric 
109958b69754SDimitry Andric     // Go through the block backwards.
11007fa27ce4SDimitry Andric     for (const MachineInstr &MI : reverse(*MBB)) {
110158b69754SDimitry Andric       // Find the MI height as determined by virtual register uses in the
110258b69754SDimitry Andric       // trace below.
110358b69754SDimitry Andric       unsigned Cycle = 0;
110401095a5dSDimitry Andric       MIHeightMap::iterator HeightI = Heights.find(&MI);
110558b69754SDimitry Andric       if (HeightI != Heights.end()) {
110658b69754SDimitry Andric         Cycle = HeightI->second;
110758b69754SDimitry Andric         // We won't be seeing any more MI uses.
110858b69754SDimitry Andric         Heights.erase(HeightI);
110958b69754SDimitry Andric       }
111058b69754SDimitry Andric 
111158b69754SDimitry Andric       // Don't process PHI deps. They depend on the specific predecessor, and
111258b69754SDimitry Andric       // we'll get them when visiting the predecessor.
111358b69754SDimitry Andric       Deps.clear();
111401095a5dSDimitry Andric       bool HasPhysRegs = !MI.isPHI() && getDataDeps(MI, Deps, MTM.MRI);
111558b69754SDimitry Andric 
111658b69754SDimitry Andric       // There may also be regunit dependencies to include in the height.
111758b69754SDimitry Andric       if (HasPhysRegs)
111801095a5dSDimitry Andric         Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits, MTM.SchedModel,
111901095a5dSDimitry Andric                                       MTM.TII, MTM.TRI);
112058b69754SDimitry Andric 
112158b69754SDimitry Andric       // Update the required height of any virtual registers read by MI.
11221a82d4c0SDimitry Andric       for (const DataDep &Dep : Deps)
11231a82d4c0SDimitry Andric         if (pushDepHeight(Dep, MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
11241a82d4c0SDimitry Andric           addLiveIns(Dep.DefMI, Dep.DefOp, Stack);
112558b69754SDimitry Andric 
112601095a5dSDimitry Andric       InstrCycles &MICycles = Cycles[&MI];
112758b69754SDimitry Andric       MICycles.Height = Cycle;
112858b69754SDimitry Andric       if (!TBI.HasValidInstrDepths) {
1129eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << Cycle << '\t' << MI);
113058b69754SDimitry Andric         continue;
113158b69754SDimitry Andric       }
113258b69754SDimitry Andric       // Update critical path length.
113358b69754SDimitry Andric       TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1134eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << MI);
113558b69754SDimitry Andric     }
113658b69754SDimitry Andric 
113758b69754SDimitry Andric     // Update virtual live-in heights. They were added by addLiveIns() with a 0
113858b69754SDimitry Andric     // height because the final height isn't known until now.
1139eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " Live-ins:");
11401a82d4c0SDimitry Andric     for (LiveInReg &LIR : TBI.LiveIns) {
114158b69754SDimitry Andric       const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
114258b69754SDimitry Andric       LIR.Height = Heights.lookup(DefMI);
1143eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << ' ' << printReg(LIR.Reg) << '@' << LIR.Height);
114458b69754SDimitry Andric     }
114558b69754SDimitry Andric 
114658b69754SDimitry Andric     // Transfer the live regunits to the live-in list.
11477fa27ce4SDimitry Andric     for (const LiveRegUnit &RU : RegUnits) {
11487fa27ce4SDimitry Andric       TBI.LiveIns.push_back(LiveInReg(RU.RegUnit, RU.Cycle));
11497fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << ' ' << printRegUnit(RU.RegUnit, MTM.TRI) << '@'
11507fa27ce4SDimitry Andric                         << RU.Cycle);
115158b69754SDimitry Andric     }
1152eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
115358b69754SDimitry Andric 
115458b69754SDimitry Andric     if (!TBI.HasValidInstrDepths)
115558b69754SDimitry Andric       continue;
115658b69754SDimitry Andric     // Add live-ins to the critical path length.
115758b69754SDimitry Andric     TBI.CriticalPath = std::max(TBI.CriticalPath,
115858b69754SDimitry Andric                                 computeCrossBlockCriticalPath(TBI));
1159eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
116058b69754SDimitry Andric   }
116158b69754SDimitry Andric }
116258b69754SDimitry Andric 
116358b69754SDimitry Andric MachineTraceMetrics::Trace
getTrace(const MachineBasicBlock * MBB)116458b69754SDimitry Andric MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1165ee8648bdSDimitry Andric   TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1166ee8648bdSDimitry Andric 
1167ee8648bdSDimitry Andric   if (!TBI.hasValidDepth() || !TBI.hasValidHeight())
116858b69754SDimitry Andric     computeTrace(MBB);
1169ee8648bdSDimitry Andric   if (!TBI.HasValidInstrDepths)
117058b69754SDimitry Andric     computeInstrDepths(MBB);
1171ee8648bdSDimitry Andric   if (!TBI.HasValidInstrHeights)
117258b69754SDimitry Andric     computeInstrHeights(MBB);
1173ee8648bdSDimitry Andric 
1174ee8648bdSDimitry Andric   return Trace(*this, TBI);
117558b69754SDimitry Andric }
117658b69754SDimitry Andric 
117758b69754SDimitry Andric unsigned
getInstrSlack(const MachineInstr & MI) const117801095a5dSDimitry Andric MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr &MI) const {
117901095a5dSDimitry Andric   assert(getBlockNum() == unsigned(MI.getParent()->getNumber()) &&
118058b69754SDimitry Andric          "MI must be in the trace center block");
118158b69754SDimitry Andric   InstrCycles Cyc = getInstrCycles(MI);
118258b69754SDimitry Andric   return getCriticalPath() - (Cyc.Depth + Cyc.Height);
118358b69754SDimitry Andric }
118458b69754SDimitry Andric 
118558b69754SDimitry Andric unsigned
getPHIDepth(const MachineInstr & PHI) const118601095a5dSDimitry Andric MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr &PHI) const {
118758b69754SDimitry Andric   const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
118858b69754SDimitry Andric   SmallVector<DataDep, 1> Deps;
118958b69754SDimitry Andric   getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
119058b69754SDimitry Andric   assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
119158b69754SDimitry Andric   DataDep &Dep = Deps.front();
119201095a5dSDimitry Andric   unsigned DepCycle = getInstrCycles(*Dep.DefMI).Depth;
119358b69754SDimitry Andric   // Add latency if DefMI is a real instruction. Transients get latency 0.
119458b69754SDimitry Andric   if (!Dep.DefMI->isTransient())
119501095a5dSDimitry Andric     DepCycle += TE.MTM.SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
119601095a5dSDimitry Andric                                                         &PHI, Dep.UseOp);
119758b69754SDimitry Andric   return DepCycle;
119858b69754SDimitry Andric }
119958b69754SDimitry Andric 
120067c32a98SDimitry Andric /// When bottom is set include instructions in current block in estimate.
getResourceDepth(bool Bottom) const120158b69754SDimitry Andric unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
12024a16efa3SDimitry Andric   // Find the limiting processor resource.
12034a16efa3SDimitry Andric   // Numbers have been pre-scaled to be comparable.
12044a16efa3SDimitry Andric   unsigned PRMax = 0;
12054a16efa3SDimitry Andric   ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
12064a16efa3SDimitry Andric   if (Bottom) {
1207b1c73532SDimitry Andric     ArrayRef<unsigned> PRCycles = TE.MTM.getProcReleaseAtCycles(getBlockNum());
12084a16efa3SDimitry Andric     for (unsigned K = 0; K != PRDepths.size(); ++K)
12094a16efa3SDimitry Andric       PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
12104a16efa3SDimitry Andric   } else {
121177fc4c14SDimitry Andric     for (unsigned PRD : PRDepths)
121277fc4c14SDimitry Andric       PRMax = std::max(PRMax, PRD);
12134a16efa3SDimitry Andric   }
12144a16efa3SDimitry Andric   // Convert to cycle count.
12154a16efa3SDimitry Andric   PRMax = TE.MTM.getCycles(PRMax);
12164a16efa3SDimitry Andric 
121767c32a98SDimitry Andric   /// All instructions before current block
121858b69754SDimitry Andric   unsigned Instrs = TBI.InstrDepth;
121967c32a98SDimitry Andric   // plus instructions in current block
122058b69754SDimitry Andric   if (Bottom)
122158b69754SDimitry Andric     Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
1222522600a2SDimitry Andric   if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1223522600a2SDimitry Andric     Instrs /= IW;
122458b69754SDimitry Andric   // Assume issue width 1 without a schedule model.
12254a16efa3SDimitry Andric   return std::max(Instrs, PRMax);
122658b69754SDimitry Andric }
122758b69754SDimitry Andric 
getResourceLength(ArrayRef<const MachineBasicBlock * > Extrablocks,ArrayRef<const MCSchedClassDesc * > ExtraInstrs,ArrayRef<const MCSchedClassDesc * > RemoveInstrs) const122867c32a98SDimitry Andric unsigned MachineTraceMetrics::Trace::getResourceLength(
122967c32a98SDimitry Andric     ArrayRef<const MachineBasicBlock *> Extrablocks,
123067c32a98SDimitry Andric     ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
123167c32a98SDimitry Andric     ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
12324a16efa3SDimitry Andric   // Add up resources above and below the center block.
12334a16efa3SDimitry Andric   ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
12344a16efa3SDimitry Andric   ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
12354a16efa3SDimitry Andric   unsigned PRMax = 0;
123667c32a98SDimitry Andric 
123767c32a98SDimitry Andric   // Capture computing cycles from extra instructions
123867c32a98SDimitry Andric   auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
123967c32a98SDimitry Andric                             unsigned ResourceIdx)
124067c32a98SDimitry Andric                          ->unsigned {
124167c32a98SDimitry Andric     unsigned Cycles = 0;
1242ee8648bdSDimitry Andric     for (const MCSchedClassDesc *SC : Instrs) {
124359d6cff9SDimitry Andric       if (!SC->isValid())
124459d6cff9SDimitry Andric         continue;
124559d6cff9SDimitry Andric       for (TargetSchedModel::ProcResIter
124659d6cff9SDimitry Andric                PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
124767c32a98SDimitry Andric                PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
124867c32a98SDimitry Andric            PI != PE; ++PI) {
124967c32a98SDimitry Andric         if (PI->ProcResourceIdx != ResourceIdx)
125059d6cff9SDimitry Andric           continue;
1251b1c73532SDimitry Andric         Cycles += (PI->ReleaseAtCycle *
1252b1c73532SDimitry Andric                    TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
125359d6cff9SDimitry Andric       }
125459d6cff9SDimitry Andric     }
125567c32a98SDimitry Andric     return Cycles;
125667c32a98SDimitry Andric   };
125767c32a98SDimitry Andric 
125867c32a98SDimitry Andric   for (unsigned K = 0; K != PRDepths.size(); ++K) {
125967c32a98SDimitry Andric     unsigned PRCycles = PRDepths[K] + PRHeights[K];
1260ee8648bdSDimitry Andric     for (const MachineBasicBlock *MBB : Extrablocks)
1261b1c73532SDimitry Andric       PRCycles += TE.MTM.getProcReleaseAtCycles(MBB->getNumber())[K];
126267c32a98SDimitry Andric     PRCycles += extraCycles(ExtraInstrs, K);
126367c32a98SDimitry Andric     PRCycles -= extraCycles(RemoveInstrs, K);
12644a16efa3SDimitry Andric     PRMax = std::max(PRMax, PRCycles);
12654a16efa3SDimitry Andric   }
12664a16efa3SDimitry Andric   // Convert to cycle count.
12674a16efa3SDimitry Andric   PRMax = TE.MTM.getCycles(PRMax);
12684a16efa3SDimitry Andric 
126967c32a98SDimitry Andric   // Instrs: #instructions in current trace outside current block.
127058b69754SDimitry Andric   unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
127167c32a98SDimitry Andric   // Add instruction count from the extra blocks.
1272ee8648bdSDimitry Andric   for (const MachineBasicBlock *MBB : Extrablocks)
1273ee8648bdSDimitry Andric     Instrs += TE.MTM.getResources(MBB)->InstrCount;
127467c32a98SDimitry Andric   Instrs += ExtraInstrs.size();
127567c32a98SDimitry Andric   Instrs -= RemoveInstrs.size();
1276522600a2SDimitry Andric   if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1277522600a2SDimitry Andric     Instrs /= IW;
127858b69754SDimitry Andric   // Assume issue width 1 without a schedule model.
12794a16efa3SDimitry Andric   return std::max(Instrs, PRMax);
128058b69754SDimitry Andric }
128158b69754SDimitry Andric 
isDepInTrace(const MachineInstr & DefMI,const MachineInstr & UseMI) const128201095a5dSDimitry Andric bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr &DefMI,
128301095a5dSDimitry Andric                                               const MachineInstr &UseMI) const {
128401095a5dSDimitry Andric   if (DefMI.getParent() == UseMI.getParent())
128567c32a98SDimitry Andric     return true;
128667c32a98SDimitry Andric 
128701095a5dSDimitry Andric   const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI.getParent()->getNumber()];
128801095a5dSDimitry Andric   const TraceBlockInfo &TBI = TE.BlockInfo[UseMI.getParent()->getNumber()];
128967c32a98SDimitry Andric 
129067c32a98SDimitry Andric   return DepTBI.isUsefulDominator(TBI);
129167c32a98SDimitry Andric }
129267c32a98SDimitry Andric 
print(raw_ostream & OS) const129358b69754SDimitry Andric void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
129458b69754SDimitry Andric   OS << getName() << " ensemble:\n";
129558b69754SDimitry Andric   for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1296044eb2f6SDimitry Andric     OS << "  %bb." << i << '\t';
129758b69754SDimitry Andric     BlockInfo[i].print(OS);
129858b69754SDimitry Andric     OS << '\n';
129958b69754SDimitry Andric   }
130058b69754SDimitry Andric }
130158b69754SDimitry Andric 
print(raw_ostream & OS) const130258b69754SDimitry Andric void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
130358b69754SDimitry Andric   if (hasValidDepth()) {
130458b69754SDimitry Andric     OS << "depth=" << InstrDepth;
130558b69754SDimitry Andric     if (Pred)
1306044eb2f6SDimitry Andric       OS << " pred=" << printMBBReference(*Pred);
130758b69754SDimitry Andric     else
130858b69754SDimitry Andric       OS << " pred=null";
1309044eb2f6SDimitry Andric     OS << " head=%bb." << Head;
131058b69754SDimitry Andric     if (HasValidInstrDepths)
131158b69754SDimitry Andric       OS << " +instrs";
131258b69754SDimitry Andric   } else
131358b69754SDimitry Andric     OS << "depth invalid";
131458b69754SDimitry Andric   OS << ", ";
131558b69754SDimitry Andric   if (hasValidHeight()) {
131658b69754SDimitry Andric     OS << "height=" << InstrHeight;
131758b69754SDimitry Andric     if (Succ)
1318044eb2f6SDimitry Andric       OS << " succ=" << printMBBReference(*Succ);
131958b69754SDimitry Andric     else
132058b69754SDimitry Andric       OS << " succ=null";
1321044eb2f6SDimitry Andric     OS << " tail=%bb." << Tail;
132258b69754SDimitry Andric     if (HasValidInstrHeights)
132358b69754SDimitry Andric       OS << " +instrs";
132458b69754SDimitry Andric   } else
132558b69754SDimitry Andric     OS << "height invalid";
132658b69754SDimitry Andric   if (HasValidInstrDepths && HasValidInstrHeights)
132758b69754SDimitry Andric     OS << ", crit=" << CriticalPath;
132858b69754SDimitry Andric }
132958b69754SDimitry Andric 
print(raw_ostream & OS) const133058b69754SDimitry Andric void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
133158b69754SDimitry Andric   unsigned MBBNum = &TBI - &TE.BlockInfo[0];
133258b69754SDimitry Andric 
1333044eb2f6SDimitry Andric   OS << TE.getName() << " trace %bb." << TBI.Head << " --> %bb." << MBBNum
1334044eb2f6SDimitry Andric      << " --> %bb." << TBI.Tail << ':';
133558b69754SDimitry Andric   if (TBI.hasValidHeight() && TBI.hasValidDepth())
133658b69754SDimitry Andric     OS << ' ' << getInstrCount() << " instrs.";
133758b69754SDimitry Andric   if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
133858b69754SDimitry Andric     OS << ' ' << TBI.CriticalPath << " cycles.";
133958b69754SDimitry Andric 
134058b69754SDimitry Andric   const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
1341044eb2f6SDimitry Andric   OS << "\n%bb." << MBBNum;
134258b69754SDimitry Andric   while (Block->hasValidDepth() && Block->Pred) {
134358b69754SDimitry Andric     unsigned Num = Block->Pred->getNumber();
1344044eb2f6SDimitry Andric     OS << " <- " << printMBBReference(*Block->Pred);
134558b69754SDimitry Andric     Block = &TE.BlockInfo[Num];
134658b69754SDimitry Andric   }
134758b69754SDimitry Andric 
134858b69754SDimitry Andric   Block = &TBI;
134958b69754SDimitry Andric   OS << "\n    ";
135058b69754SDimitry Andric   while (Block->hasValidHeight() && Block->Succ) {
135158b69754SDimitry Andric     unsigned Num = Block->Succ->getNumber();
1352044eb2f6SDimitry Andric     OS << " -> " << printMBBReference(*Block->Succ);
135358b69754SDimitry Andric     Block = &TE.BlockInfo[Num];
135458b69754SDimitry Andric   }
135558b69754SDimitry Andric   OS << '\n';
135658b69754SDimitry Andric }
1357