blob: 998a9645e68bfa2761ee180bbad983a3881bbf39 [file] [log] [blame]
Eugene Zelenko49e2fc42017-02-21 22:07:52 +00001//===- lib/CodeGen/MachineTraceMetrics.cpp --------------------------------===//
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00002//
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
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000010#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/DenseMap.h"
12#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000013#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000014#include "llvm/ADT/SmallPtrSet.h"
15#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000017#include "llvm/CodeGen/MachineBasicBlock.h"
18#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000019#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000021#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000022#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000024#include "llvm/CodeGen/MachineTraceMetrics.h"
25#include "llvm/MC/MCRegisterInfo.h"
26#include "llvm/Pass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Support/Debug.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000028#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +000029#include "llvm/Support/Format.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetRegisterInfo.h"
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +000033#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000034#include <algorithm>
35#include <cassert>
36#include <iterator>
37#include <tuple>
38#include <utility>
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000039
40using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "machine-trace-metrics"
43
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000044char MachineTraceMetrics::ID = 0;
45char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
46
47INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
48 "machine-trace-metrics", "Machine Trace Metrics", false, true)
49INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
50INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
51INITIALIZE_PASS_END(MachineTraceMetrics,
52 "machine-trace-metrics", "Machine Trace Metrics", false, true)
53
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000054MachineTraceMetrics::MachineTraceMetrics() : MachineFunctionPass(ID) {
Benjamin Kramer502b9e12014-04-12 16:15:53 +000055 std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000056}
57
58void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.setPreservesAll();
60 AU.addRequired<MachineBranchProbabilityInfo>();
61 AU.addRequired<MachineLoopInfo>();
62 MachineFunctionPass::getAnalysisUsage(AU);
63}
64
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +000065bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
66 MF = &Func;
Eric Christopher3d4276f2015-01-27 07:31:29 +000067 const TargetSubtargetInfo &ST = MF->getSubtarget();
68 TII = ST.getInstrInfo();
69 TRI = ST.getRegisterInfo();
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +000070 MRI = &MF->getRegInfo();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000071 Loops = &getAnalysis<MachineLoopInfo>();
Pete Cooper11759452014-09-02 17:43:54 +000072 SchedModel.init(ST.getSchedModel(), &ST, TII);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +000073 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +000074 ProcResourceCycles.resize(MF->getNumBlockIDs() *
75 SchedModel.getNumProcResourceKinds());
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000076 return false;
77}
78
79void MachineTraceMetrics::releaseMemory() {
Craig Topperc0196b12014-04-14 00:51:57 +000080 MF = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000081 BlockInfo.clear();
82 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
83 delete Ensembles[i];
Craig Topperc0196b12014-04-14 00:51:57 +000084 Ensembles[i] = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000085 }
86}
87
88//===----------------------------------------------------------------------===//
89// Fixed block information
90//===----------------------------------------------------------------------===//
91//
92// The number of instructions in a basic block and the CPU resources used by
93// those instructions don't depend on any given trace strategy.
94
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000095/// Compute the resource usage in basic block MBB.
96const MachineTraceMetrics::FixedBlockInfo*
97MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
98 assert(MBB && "No basic block");
99 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
100 if (FBI->hasResources())
101 return FBI;
102
103 // Compute resource usage in the block.
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000104 FBI->HasCalls = false;
105 unsigned InstrCount = 0;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000106
107 // Add up per-processor resource cycles as well.
108 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
109 SmallVector<unsigned, 32> PRCycles(PRKinds);
110
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000111 for (const auto &MI : *MBB) {
112 if (MI.isTransient())
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000113 continue;
114 ++InstrCount;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000115 if (MI.isCall())
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000116 FBI->HasCalls = true;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000117
118 // Count processor resources used.
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000119 if (!SchedModel.hasInstrSchedModel())
120 continue;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000121 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000122 if (!SC->isValid())
123 continue;
124
125 for (TargetSchedModel::ProcResIter
126 PI = SchedModel.getWriteProcResBegin(SC),
127 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
128 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
129 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
130 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000131 }
132 FBI->InstrCount = InstrCount;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000133
134 // Scale the resource cycles so they are comparable.
135 unsigned PROffset = MBB->getNumber() * PRKinds;
136 for (unsigned K = 0; K != PRKinds; ++K)
137 ProcResourceCycles[PROffset + K] =
138 PRCycles[K] * SchedModel.getResourceFactor(K);
139
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000140 return FBI;
141}
142
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000143ArrayRef<unsigned>
144MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
145 assert(BlockInfo[MBBNum].hasResources() &&
146 "getResources() must be called before getProcResourceCycles()");
147 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000148 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
Craig Toppere1d12942014-08-27 05:25:25 +0000149 return makeArrayRef(ProcResourceCycles.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000150}
151
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000152//===----------------------------------------------------------------------===//
153// Ensemble utility functions
154//===----------------------------------------------------------------------===//
155
156MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000157 : MTM(*ct) {
158 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000159 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
160 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
161 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000162}
163
164// Virtual destructor serves as an anchor.
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000165MachineTraceMetrics::Ensemble::~Ensemble() = default;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000166
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000167const MachineLoop*
168MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000169 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000170}
171
172// Update resource-related information in the TraceBlockInfo for MBB.
173// Only update resources related to the trace above MBB.
174void MachineTraceMetrics::Ensemble::
175computeDepthResources(const MachineBasicBlock *MBB) {
176 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000177 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
178 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000179
180 // Compute resources from trace above. The top block is simple.
181 if (!TBI->Pred) {
182 TBI->InstrDepth = 0;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000183 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000184 std::fill(ProcResourceDepths.begin() + PROffset,
185 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000186 return;
187 }
188
189 // Compute from the block above. A post-order traversal ensures the
190 // predecessor is always computed first.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000191 unsigned PredNum = TBI->Pred->getNumber();
192 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000193 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000194 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000195 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000196 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000197
198 // Compute per-resource depths.
199 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
200 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
201 for (unsigned K = 0; K != PRKinds; ++K)
202 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000203}
204
205// Update resource-related information in the TraceBlockInfo for MBB.
206// Only update resources related to the trace below MBB.
207void MachineTraceMetrics::Ensemble::
208computeHeightResources(const MachineBasicBlock *MBB) {
209 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000210 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
211 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000212
213 // Compute resources for the current block.
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000214 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000215 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000216
217 // The trace tail is done.
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000218 if (!TBI->Succ) {
219 TBI->Tail = MBB->getNumber();
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000220 std::copy(PRCycles.begin(), PRCycles.end(),
221 ProcResourceHeights.begin() + PROffset);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000222 return;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000223 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000224
225 // Compute from the block below. A post-order traversal ensures the
226 // predecessor is always computed first.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000227 unsigned SuccNum = TBI->Succ->getNumber();
228 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000229 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
230 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000231 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000232
233 // Compute per-resource heights.
234 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
235 for (unsigned K = 0; K != PRKinds; ++K)
236 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000237}
238
239// Check if depth resources for MBB are valid and return the TBI.
240// Return NULL if the resources have been invalidated.
241const MachineTraceMetrics::TraceBlockInfo*
242MachineTraceMetrics::Ensemble::
243getDepthResources(const MachineBasicBlock *MBB) const {
244 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Craig Topperc0196b12014-04-14 00:51:57 +0000245 return TBI->hasValidDepth() ? TBI : nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000246}
247
248// Check if height resources for MBB are valid and return the TBI.
249// Return NULL if the resources have been invalidated.
250const MachineTraceMetrics::TraceBlockInfo*
251MachineTraceMetrics::Ensemble::
252getHeightResources(const MachineBasicBlock *MBB) const {
253 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Craig Topperc0196b12014-04-14 00:51:57 +0000254 return TBI->hasValidHeight() ? TBI : nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000255}
256
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000257/// Get an array of processor resource depths for MBB. Indexed by processor
258/// resource kind, this array contains the scaled processor resources consumed
259/// by all blocks preceding MBB in its trace. It does not include instructions
260/// in MBB.
261///
262/// Compare TraceBlockInfo::InstrDepth.
263ArrayRef<unsigned>
264MachineTraceMetrics::Ensemble::
265getProcResourceDepths(unsigned MBBNum) const {
266 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000267 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
Craig Toppere1d12942014-08-27 05:25:25 +0000268 return makeArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000269}
270
271/// Get an array of processor resource heights for MBB. Indexed by processor
272/// resource kind, this array contains the scaled processor resources consumed
273/// by this block and all blocks following it in its trace.
274///
275/// Compare TraceBlockInfo::InstrHeight.
276ArrayRef<unsigned>
277MachineTraceMetrics::Ensemble::
278getProcResourceHeights(unsigned MBBNum) const {
279 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000280 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
Craig Toppere1d12942014-08-27 05:25:25 +0000281 return makeArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000282}
283
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000284//===----------------------------------------------------------------------===//
285// Trace Selection Strategies
286//===----------------------------------------------------------------------===//
287//
288// A trace selection strategy is implemented as a sub-class of Ensemble. The
289// trace through a block B is computed by two DFS traversals of the CFG
290// starting from B. One upwards, and one downwards. During the upwards DFS,
291// pickTracePred() is called on the post-ordered blocks. During the downwards
292// DFS, pickTraceSucc() is called in a post-order.
293//
294
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000295// We never allow traces that leave loops, but we do allow traces to enter
296// nested loops. We also never allow traces to contain back-edges.
297//
298// This means that a loop header can never appear above the center block of a
299// trace, except as the trace head. Below the center block, loop exiting edges
300// are banned.
301//
302// Return true if an edge from the From loop to the To loop is leaving a loop.
303// Either of To and From can be null.
304static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
305 return From && !From->contains(To);
306}
307
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000308// MinInstrCountEnsemble - Pick the trace that executes the least number of
309// instructions.
310namespace {
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000311
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000312class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Craig Topper4584cd52014-03-07 09:26:03 +0000313 const char *getName() const override { return "MinInstr"; }
314 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
315 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000316
317public:
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000318 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
319 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000320};
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000321
322} // end anonymous namespace
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000323
324// Select the preferred predecessor for MBB.
325const MachineBasicBlock*
326MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
327 if (MBB->pred_empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000328 return nullptr;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000329 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000330 // Don't leave loops, and never follow back-edges.
331 if (CurLoop && MBB == CurLoop->getHeader())
Craig Topperc0196b12014-04-14 00:51:57 +0000332 return nullptr;
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000333 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Craig Topperc0196b12014-04-14 00:51:57 +0000334 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000335 unsigned BestDepth = 0;
Sanjay Patel99b3aa32015-05-21 17:22:45 +0000336 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
Jakob Stoklund Olesenf308c122012-07-30 21:10:27 +0000337 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
338 getDepthResources(Pred);
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000339 // Ignore cycles that aren't natural loops.
340 if (!PredTBI)
341 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000342 // Pick the predecessor that would give this block the smallest InstrDepth.
343 unsigned Depth = PredTBI->InstrDepth + CurCount;
Richard Trieu7a083812016-02-18 22:09:30 +0000344 if (!Best || Depth < BestDepth) {
345 Best = Pred;
346 BestDepth = Depth;
347 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000348 }
349 return Best;
350}
351
352// Select the preferred successor for MBB.
353const MachineBasicBlock*
354MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
355 if (MBB->pred_empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000356 return nullptr;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000357 const MachineLoop *CurLoop = getLoopFor(MBB);
Craig Topperc0196b12014-04-14 00:51:57 +0000358 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000359 unsigned BestHeight = 0;
Sanjay Patel99b3aa32015-05-21 17:22:45 +0000360 for (const MachineBasicBlock *Succ : MBB->successors()) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000361 // Don't consider back-edges.
362 if (CurLoop && Succ == CurLoop->getHeader())
363 continue;
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000364 // Don't consider successors exiting CurLoop.
365 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000366 continue;
Jakob Stoklund Olesenf308c122012-07-30 21:10:27 +0000367 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
368 getHeightResources(Succ);
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000369 // Ignore cycles that aren't natural loops.
370 if (!SuccTBI)
371 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000372 // Pick the successor that would give this block the smallest InstrHeight.
373 unsigned Height = SuccTBI->InstrHeight;
Richard Trieu7a083812016-02-18 22:09:30 +0000374 if (!Best || Height < BestHeight) {
375 Best = Succ;
376 BestHeight = Height;
377 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000378 }
379 return Best;
380}
381
382// Get an Ensemble sub-class for the requested trace strategy.
383MachineTraceMetrics::Ensemble *
384MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
385 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
386 Ensemble *&E = Ensembles[strategy];
387 if (E)
388 return E;
389
390 // Allocate new Ensemble on demand.
391 switch (strategy) {
392 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
393 default: llvm_unreachable("Invalid trace strategy enum");
394 }
395}
396
397void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
398 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
399 BlockInfo[MBB->getNumber()].invalidate();
400 for (unsigned i = 0; i != TS_NumStrategies; ++i)
401 if (Ensembles[i])
402 Ensembles[i]->invalidate(MBB);
403}
404
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000405void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen68c2cd02012-07-30 23:15:12 +0000406 if (!MF)
407 return;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000408#ifndef NDEBUG
409 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
410 for (unsigned i = 0; i != TS_NumStrategies; ++i)
411 if (Ensembles[i])
412 Ensembles[i]->verify();
413#endif
414}
415
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000416//===----------------------------------------------------------------------===//
417// Trace building
418//===----------------------------------------------------------------------===//
419//
420// Traces are built by two CFG traversals. To avoid recomputing too much, use a
421// set abstraction that confines the search to the current loop, and doesn't
422// revisit blocks.
423
424namespace {
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000425
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000426struct LoopBounds {
427 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000428 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000429 const MachineLoopInfo *Loops;
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000430 bool Downward = false;
431
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000432 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000433 const MachineLoopInfo *loops) : Blocks(blocks), Loops(loops) {}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000434};
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000435
436} // end anonymous namespace
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000437
438// Specialize po_iterator_storage in order to prune the post-order traversal so
439// it is limited to the current loop and doesn't traverse the loop back edges.
440namespace llvm {
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000441
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000442template<>
443class po_iterator_storage<LoopBounds, true> {
444 LoopBounds &LB;
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000445
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000446public:
447 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000448
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000449 void finishPostorder(const MachineBasicBlock*) {}
450
Tim Shene0793db2016-08-15 21:52:54 +0000451 bool insertEdge(Optional<const MachineBasicBlock *> From,
452 const MachineBasicBlock *To) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000453 // Skip already visited To blocks.
454 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
455 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
456 return false;
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000457 // From is null once when To is the trace center block.
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000458 if (From) {
Tim Shene0793db2016-08-15 21:52:54 +0000459 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(*From)) {
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000460 // Don't follow backedges, don't leave FromLoop when going upwards.
Tim Shene0793db2016-08-15 21:52:54 +0000461 if ((LB.Downward ? To : *From) == FromLoop->getHeader())
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000462 return false;
463 // Don't leave FromLoop.
464 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
465 return false;
466 }
467 }
468 // To is a new block. Mark the block as visited in case the CFG has cycles
469 // that MachineLoopInfo didn't recognize as a natural loop.
David Blaikie70573dc2014-11-19 07:49:26 +0000470 return LB.Visited.insert(To).second;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000471 }
472};
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000473
474} // end namespace llvm
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000475
476/// Compute the trace through MBB.
477void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
478 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
479 << MBB->getNumber() << '\n');
480 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000481 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000482
483 // Run an upwards post-order search for the trace start.
484 Bounds.Downward = false;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000485 Bounds.Visited.clear();
Daniel Berlin25db4f42015-04-15 17:41:42 +0000486 for (auto I : inverse_post_order_ext(MBB, Bounds)) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000487 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
488 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
489 // All the predecessors have been visited, pick the preferred one.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000490 TBI.Pred = pickTracePred(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000491 DEBUG({
492 if (TBI.Pred)
493 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
494 else
495 dbgs() << "null\n";
496 });
497 // The trace leading to I is now known, compute the depth resources.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000498 computeDepthResources(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000499 }
500
501 // Run a downwards post-order search for the trace end.
502 Bounds.Downward = true;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000503 Bounds.Visited.clear();
Daniel Berlin25db4f42015-04-15 17:41:42 +0000504 for (auto I : post_order_ext(MBB, Bounds)) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000505 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
506 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
507 // All the successors have been visited, pick the preferred one.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000508 TBI.Succ = pickTraceSucc(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000509 DEBUG({
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000510 if (TBI.Succ)
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000511 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
512 else
513 dbgs() << "null\n";
514 });
515 // The trace leaving I is now known, compute the height resources.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000516 computeHeightResources(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000517 }
518}
519
520/// Invalidate traces through BadMBB.
521void
522MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
523 SmallVector<const MachineBasicBlock*, 16> WorkList;
524 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
525
526 // Invalidate height resources of blocks above MBB.
527 if (BadTBI.hasValidHeight()) {
528 BadTBI.invalidateHeight();
529 WorkList.push_back(BadMBB);
530 do {
531 const MachineBasicBlock *MBB = WorkList.pop_back_val();
532 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
533 << " height.\n");
534 // Find any MBB predecessors that have MBB as their preferred successor.
535 // They are the only ones that need to be invalidated.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000536 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
537 TraceBlockInfo &TBI = BlockInfo[Pred->getNumber()];
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000538 if (!TBI.hasValidHeight())
539 continue;
540 if (TBI.Succ == MBB) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000541 TBI.invalidateHeight();
Sanjay Pateld2b71442015-07-06 16:27:35 +0000542 WorkList.push_back(Pred);
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000543 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000544 }
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000545 // Verify that TBI.Succ is actually a *I successor.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000546 assert((!TBI.Succ || Pred->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000547 }
548 } while (!WorkList.empty());
549 }
550
551 // Invalidate depth resources of blocks below MBB.
552 if (BadTBI.hasValidDepth()) {
553 BadTBI.invalidateDepth();
554 WorkList.push_back(BadMBB);
555 do {
556 const MachineBasicBlock *MBB = WorkList.pop_back_val();
557 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
558 << " depth.\n");
559 // Find any MBB successors that have MBB as their preferred predecessor.
560 // They are the only ones that need to be invalidated.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000561 for (const MachineBasicBlock *Succ : MBB->successors()) {
562 TraceBlockInfo &TBI = BlockInfo[Succ->getNumber()];
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000563 if (!TBI.hasValidDepth())
564 continue;
565 if (TBI.Pred == MBB) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000566 TBI.invalidateDepth();
Sanjay Pateld2b71442015-07-06 16:27:35 +0000567 WorkList.push_back(Succ);
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000568 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000569 }
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000570 // Verify that TBI.Pred is actually a *I predecessor.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000571 assert((!TBI.Pred || Succ->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000572 }
573 } while (!WorkList.empty());
574 }
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000575
576 // Clear any per-instruction data. We only have to do this for BadMBB itself
577 // because the instructions in that block may change. Other blocks may be
578 // invalidated, but their instructions will stay the same, so there is no
579 // need to erase the Cycle entries. They will be overwritten when we
580 // recompute.
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000581 for (const auto &I : *BadMBB)
582 Cycles.erase(&I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000583}
584
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000585void MachineTraceMetrics::Ensemble::verify() const {
586#ifndef NDEBUG
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000587 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000588 "Outdated BlockInfo size");
589 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
590 const TraceBlockInfo &TBI = BlockInfo[Num];
591 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000592 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000593 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
594 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
595 "Trace is broken, depth should have been invalidated.");
596 const MachineLoop *Loop = getLoopFor(MBB);
597 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
598 }
599 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000600 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000601 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
602 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
603 "Trace is broken, height should have been invalidated.");
604 const MachineLoop *Loop = getLoopFor(MBB);
605 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
606 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
607 "Trace contains backedge");
608 }
609 }
610#endif
611}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000612
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000613//===----------------------------------------------------------------------===//
614// Data Dependencies
615//===----------------------------------------------------------------------===//
616//
617// Compute the depth and height of each instruction based on data dependencies
618// and instruction latencies. These cycle numbers assume that the CPU can issue
619// an infinite number of instructions per cycle as long as their dependencies
620// are ready.
621
622// A data dependency is represented as a defining MI and operand numbers on the
623// defining and using MI.
624namespace {
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000625
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000626struct DataDep {
627 const MachineInstr *DefMI;
628 unsigned DefOp;
629 unsigned UseOp;
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000630
631 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
632 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
633
634 /// Create a DataDep from an SSA form virtual register.
635 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
636 : UseOp(UseOp) {
637 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
638 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
639 assert(!DefI.atEnd() && "Register has no defs");
Owen Anderson16c6bf42014-03-13 23:12:04 +0000640 DefMI = DefI->getParent();
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000641 DefOp = DefI.getOperandNo();
642 assert((++DefI).atEnd() && "Register has multiple defs");
643 }
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000644};
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000645
646} // end anonymous namespace
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000647
648// Get the input data dependencies that must be ready before UseMI can issue.
649// Return true if UseMI has any physreg operands.
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000650static bool getDataDeps(const MachineInstr &UseMI,
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000651 SmallVectorImpl<DataDep> &Deps,
652 const MachineRegisterInfo *MRI) {
Sanjay Patelf2fa58e2015-07-23 22:56:53 +0000653 // Debug values should not be included in any calculations.
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000654 if (UseMI.isDebugValue())
Sanjay Patelf2fa58e2015-07-23 22:56:53 +0000655 return false;
656
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000657 bool HasPhysRegs = false;
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000658 for (MachineInstr::const_mop_iterator I = UseMI.operands_begin(),
659 E = UseMI.operands_end(); I != E; ++I) {
Matthias Braune41e1462015-05-29 02:56:46 +0000660 const MachineOperand &MO = *I;
661 if (!MO.isReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000662 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000663 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000664 if (!Reg)
665 continue;
666 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
667 HasPhysRegs = true;
668 continue;
669 }
670 // Collect virtual register reads.
Matthias Braune41e1462015-05-29 02:56:46 +0000671 if (MO.readsReg())
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000672 Deps.push_back(DataDep(MRI, Reg, UseMI.getOperandNo(I)));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000673 }
674 return HasPhysRegs;
675}
676
677// Get the input data dependencies of a PHI instruction, using Pred as the
678// preferred predecessor.
679// This will add at most one dependency to Deps.
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000680static void getPHIDeps(const MachineInstr &UseMI,
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000681 SmallVectorImpl<DataDep> &Deps,
682 const MachineBasicBlock *Pred,
683 const MachineRegisterInfo *MRI) {
684 // No predecessor at the beginning of a trace. Ignore dependencies.
685 if (!Pred)
686 return;
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000687 assert(UseMI.isPHI() && UseMI.getNumOperands() % 2 && "Bad PHI");
688 for (unsigned i = 1; i != UseMI.getNumOperands(); i += 2) {
689 if (UseMI.getOperand(i + 1).getMBB() == Pred) {
690 unsigned Reg = UseMI.getOperand(i).getReg();
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000691 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000692 return;
693 }
694 }
695}
696
697// Keep track of physreg data dependencies by recording each live register unit.
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000698// Associate each regunit with an instruction operand. Depending on the
699// direction instructions are scanned, it could be the operand that defined the
700// regunit, or the highest operand to read the regunit.
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000701namespace {
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000702
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000703struct LiveRegUnit {
704 unsigned RegUnit;
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000705 unsigned Cycle = 0;
706 const MachineInstr *MI = nullptr;
707 unsigned Op = 0;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000708
709 unsigned getSparseSetIndex() const { return RegUnit; }
710
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000711 LiveRegUnit(unsigned RU) : RegUnit(RU) {}
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000712};
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000713
714} // end anonymous namespace
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000715
716// Identify physreg dependencies for UseMI, and update the live regunit
717// tracking set when scanning instructions downwards.
718static void updatePhysDepsDownwards(const MachineInstr *UseMI,
719 SmallVectorImpl<DataDep> &Deps,
720 SparseSet<LiveRegUnit> &RegUnits,
721 const TargetRegisterInfo *TRI) {
722 SmallVector<unsigned, 8> Kills;
723 SmallVector<unsigned, 8> LiveDefOps;
724
Matthias Braune41e1462015-05-29 02:56:46 +0000725 for (MachineInstr::const_mop_iterator MI = UseMI->operands_begin(),
726 ME = UseMI->operands_end(); MI != ME; ++MI) {
727 const MachineOperand &MO = *MI;
728 if (!MO.isReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000729 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000730 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000731 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
732 continue;
733 // Track live defs and kills for updating RegUnits.
Matthias Braune41e1462015-05-29 02:56:46 +0000734 if (MO.isDef()) {
735 if (MO.isDead())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000736 Kills.push_back(Reg);
737 else
Matthias Braune41e1462015-05-29 02:56:46 +0000738 LiveDefOps.push_back(UseMI->getOperandNo(MI));
739 } else if (MO.isKill())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000740 Kills.push_back(Reg);
741 // Identify dependencies.
Matthias Braune41e1462015-05-29 02:56:46 +0000742 if (!MO.readsReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000743 continue;
744 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
745 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
746 if (I == RegUnits.end())
747 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000748 Deps.push_back(DataDep(I->MI, I->Op, UseMI->getOperandNo(MI)));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000749 break;
750 }
751 }
752
753 // Update RegUnits to reflect live registers after UseMI.
754 // First kills.
Sanjay Patel87d2ae22015-12-09 22:45:45 +0000755 for (unsigned Kill : Kills)
756 for (MCRegUnitIterator Units(Kill, TRI); Units.isValid(); ++Units)
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000757 RegUnits.erase(*Units);
758
759 // Second, live defs.
Sanjay Patel87d2ae22015-12-09 22:45:45 +0000760 for (unsigned DefOp : LiveDefOps) {
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000761 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
762 Units.isValid(); ++Units) {
763 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000764 LRU.MI = UseMI;
765 LRU.Op = DefOp;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000766 }
767 }
768}
769
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000770/// The length of the critical path through a trace is the maximum of two path
771/// lengths:
772///
773/// 1. The maximum height+depth over all instructions in the trace center block.
774///
775/// 2. The longest cross-block dependency chain. For small blocks, it is
776/// possible that the critical path through the trace doesn't include any
777/// instructions in the block.
778///
779/// This function computes the second number from the live-in list of the
780/// center block.
781unsigned MachineTraceMetrics::Ensemble::
782computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
783 assert(TBI.HasValidInstrDepths && "Missing depth info");
784 assert(TBI.HasValidInstrHeights && "Missing height info");
785 unsigned MaxLen = 0;
Sanjay Patel87d2ae22015-12-09 22:45:45 +0000786 for (const LiveInReg &LIR : TBI.LiveIns) {
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000787 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
788 continue;
789 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
790 // Ignore dependencies outside the current trace.
791 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
Jakob Stoklund Olesen299cedc2013-03-07 23:55:49 +0000792 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000793 continue;
794 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
795 MaxLen = std::max(MaxLen, Len);
796 }
797 return MaxLen;
798}
799
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000800/// Compute instruction depths for all instructions above or in MBB in its
801/// trace. This assumes that the trace through MBB has already been computed.
802void MachineTraceMetrics::Ensemble::
803computeInstrDepths(const MachineBasicBlock *MBB) {
804 // The top of the trace may already be computed, and HasValidInstrDepths
805 // implies Head->HasValidInstrDepths, so we only need to start from the first
806 // block in the trace that needs to be recomputed.
807 SmallVector<const MachineBasicBlock*, 8> Stack;
808 do {
809 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
810 assert(TBI.hasValidDepth() && "Incomplete trace");
811 if (TBI.HasValidInstrDepths)
812 break;
813 Stack.push_back(MBB);
814 MBB = TBI.Pred;
815 } while (MBB);
816
817 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
818 // in the trace. We should track any live-out physregs that were defined in
819 // the trace. This is quite rare in SSA form, typically created by CSE
820 // hoisting a compare.
821 SparseSet<LiveRegUnit> RegUnits;
822 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
823
824 // Go through trace blocks in top-down order, stopping after the center block.
825 SmallVector<DataDep, 8> Deps;
826 while (!Stack.empty()) {
827 MBB = Stack.pop_back_val();
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000828 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000829 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
830 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000831 TBI.CriticalPath = 0;
832
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000833 // Print out resource depths here as well.
834 DEBUG({
835 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
836 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
837 for (unsigned K = 0; K != PRDepths.size(); ++K)
838 if (PRDepths[K]) {
839 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
840 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
841 << MTM.SchedModel.getProcResource(K)->Name << " ("
842 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
843 }
844 });
845
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000846 // Also compute the critical path length through MBB when possible.
847 if (TBI.HasValidInstrHeights)
848 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
849
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000850 for (const auto &UseMI : *MBB) {
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000851 // Collect all data dependencies.
852 Deps.clear();
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000853 if (UseMI.isPHI())
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000854 getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000855 else if (getDataDeps(UseMI, Deps, MTM.MRI))
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000856 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000857
858 // Filter and process dependencies, computing the earliest issue cycle.
859 unsigned Cycle = 0;
Sanjay Patel0ca438c2015-06-30 16:30:22 +0000860 for (const DataDep &Dep : Deps) {
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000861 const TraceBlockInfo&DepTBI =
862 BlockInfo[Dep.DefMI->getParent()->getNumber()];
863 // Ignore dependencies from outside the current trace.
Jakob Stoklund Olesen299cedc2013-03-07 23:55:49 +0000864 if (!DepTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000865 continue;
866 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
867 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
868 // Add latency if DefMI is a real instruction. Transients get latency 0.
869 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000870 DepCycle += MTM.SchedModel
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000871 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000872 Cycle = std::max(Cycle, DepCycle);
873 }
874 // Remember the instruction depth.
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000875 InstrCycles &MICycles = Cycles[&UseMI];
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000876 MICycles.Depth = Cycle;
877
878 if (!TBI.HasValidInstrHeights) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000879 DEBUG(dbgs() << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000880 continue;
881 }
882 // Update critical path length.
883 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000884 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000885 }
886 }
887}
888
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000889// Identify physreg dependencies for MI when scanning instructions upwards.
890// Return the issue height of MI after considering any live regunits.
891// Height is the issue height computed from virtual register dependencies alone.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000892static unsigned updatePhysDepsUpwards(const MachineInstr &MI, unsigned Height,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000893 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000894 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000895 const TargetInstrInfo *TII,
896 const TargetRegisterInfo *TRI) {
897 SmallVector<unsigned, 8> ReadOps;
Matthias Braune41e1462015-05-29 02:56:46 +0000898
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000899 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
900 MOE = MI.operands_end();
901 MOI != MOE; ++MOI) {
Matthias Braune41e1462015-05-29 02:56:46 +0000902 const MachineOperand &MO = *MOI;
903 if (!MO.isReg())
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000904 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000905 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000906 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
907 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000908 if (MO.readsReg())
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000909 ReadOps.push_back(MI.getOperandNo(MOI));
Matthias Braune41e1462015-05-29 02:56:46 +0000910 if (!MO.isDef())
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000911 continue;
912 // This is a def of Reg. Remove corresponding entries from RegUnits, and
913 // update MI Height to consider the physreg dependencies.
914 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
915 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
916 if (I == RegUnits.end())
917 continue;
918 unsigned DepHeight = I->Cycle;
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000919 if (!MI.isTransient()) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000920 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000921 // live-in list. SchedModel can handle a NULL UseMI.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000922 DepHeight += SchedModel.computeOperandLatency(&MI, MI.getOperandNo(MOI),
923 I->MI, I->Op);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000924 }
925 Height = std::max(Height, DepHeight);
926 // This regunit is dead above MI.
927 RegUnits.erase(I);
928 }
929 }
930
931 // Now we know the height of MI. Update any regunits read.
932 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000933 unsigned Reg = MI.getOperand(ReadOps[i]).getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000934 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
935 LiveRegUnit &LRU = RegUnits[*Units];
936 // Set the height to the highest reader of the unit.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000937 if (LRU.Cycle <= Height && LRU.MI != &MI) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000938 LRU.Cycle = Height;
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000939 LRU.MI = &MI;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000940 LRU.Op = ReadOps[i];
941 }
942 }
943 }
944
945 return Height;
946}
947
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000948typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
949
950// Push the height of DefMI upwards if required to match UseMI.
951// Return true if this is the first time DefMI was seen.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000952static bool pushDepHeight(const DataDep &Dep, const MachineInstr &UseMI,
953 unsigned UseHeight, MIHeightMap &Heights,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000954 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000955 const TargetInstrInfo *TII) {
956 // Adjust height by Dep.DefMI latency.
957 if (!Dep.DefMI->isTransient())
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000958 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI,
959 Dep.UseOp);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000960
961 // Update Heights[DefMI] to be the maximum height seen.
962 MIHeightMap::iterator I;
963 bool New;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000964 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000965 if (New)
966 return true;
967
968 // DefMI has been pushed before. Give it the max height.
969 if (I->second < UseHeight)
970 I->second = UseHeight;
971 return false;
972}
973
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000974/// Assuming that the virtual register defined by DefMI:DefOp was used by
975/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
976/// when reaching the block that contains DefMI.
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000977void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000978addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000979 ArrayRef<const MachineBasicBlock*> Trace) {
980 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000981 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000982 assert(TargetRegisterInfo::isVirtualRegister(Reg));
983 const MachineBasicBlock *DefMBB = DefMI->getParent();
984
985 // Reg is live-in to all blocks in Trace that follow DefMBB.
986 for (unsigned i = Trace.size(); i; --i) {
987 const MachineBasicBlock *MBB = Trace[i-1];
988 if (MBB == DefMBB)
989 return;
990 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
991 // Just add the register. The height will be updated later.
992 TBI.LiveIns.push_back(Reg);
993 }
994}
995
996/// Compute instruction heights in the trace through MBB. This updates MBB and
997/// the blocks below it in the trace. It is assumed that the trace has already
998/// been computed.
999void MachineTraceMetrics::Ensemble::
1000computeInstrHeights(const MachineBasicBlock *MBB) {
1001 // The bottom of the trace may already be computed.
1002 // Find the blocks that need updating.
1003 SmallVector<const MachineBasicBlock*, 8> Stack;
1004 do {
1005 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1006 assert(TBI.hasValidHeight() && "Incomplete trace");
1007 if (TBI.HasValidInstrHeights)
1008 break;
1009 Stack.push_back(MBB);
1010 TBI.LiveIns.clear();
1011 MBB = TBI.Succ;
1012 } while (MBB);
1013
1014 // As we move upwards in the trace, keep track of instructions that are
1015 // required by deeper trace instructions. Map MI -> height required so far.
1016 MIHeightMap Heights;
1017
1018 // For physregs, the def isn't known when we see the use.
1019 // Instead, keep track of the highest use of each regunit.
1020 SparseSet<LiveRegUnit> RegUnits;
1021 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1022
1023 // If the bottom of the trace was already precomputed, initialize heights
1024 // from its live-in list.
1025 // MBB is the highest precomputed block in the trace.
1026 if (MBB) {
1027 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001028 for (LiveInReg &LI : TBI.LiveIns) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001029 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1030 // For virtual registers, the def latency is included.
1031 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1032 if (Height < LI.Height)
1033 Height = LI.Height;
1034 } else {
1035 // For register units, the def latency is not included because we don't
1036 // know the def yet.
1037 RegUnits[LI.Reg].Cycle = LI.Height;
1038 }
1039 }
1040 }
1041
1042 // Go through the trace blocks in bottom-up order.
1043 SmallVector<DataDep, 8> Deps;
1044 for (;!Stack.empty(); Stack.pop_back()) {
1045 MBB = Stack.back();
1046 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1047 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1048 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001049 TBI.CriticalPath = 0;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001050
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001051 DEBUG({
1052 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1053 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1054 for (unsigned K = 0; K != PRHeights.size(); ++K)
1055 if (PRHeights[K]) {
1056 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1057 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1058 << MTM.SchedModel.getProcResource(K)->Name << " ("
1059 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1060 }
1061 });
1062
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001063 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001064 const MachineBasicBlock *Succ = TBI.Succ;
1065 // If MBB is the last block in the trace, and it has a back-edge to the
1066 // loop header, get loop-carried dependencies from PHIs in the header. For
1067 // that purpose, pretend that all the loop header PHIs have height 0.
1068 if (!Succ)
1069 if (const MachineLoop *Loop = getLoopFor(MBB))
1070 if (MBB->isSuccessor(Loop->getHeader()))
1071 Succ = Loop->getHeader();
1072
1073 if (Succ) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001074 for (const auto &PHI : *Succ) {
1075 if (!PHI.isPHI())
1076 break;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001077 Deps.clear();
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001078 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001079 if (!Deps.empty()) {
1080 // Loop header PHI heights are all 0.
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001081 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1082 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +00001083 if (pushDepHeight(Deps.front(), PHI, Height, Heights, MTM.SchedModel,
1084 MTM.TII))
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +00001085 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001086 }
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001087 }
1088 }
1089
1090 // Go through the block backwards.
1091 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1092 BI != BB;) {
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001093 const MachineInstr &MI = *--BI;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001094
1095 // Find the MI height as determined by virtual register uses in the
1096 // trace below.
1097 unsigned Cycle = 0;
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001098 MIHeightMap::iterator HeightI = Heights.find(&MI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001099 if (HeightI != Heights.end()) {
1100 Cycle = HeightI->second;
1101 // We won't be seeing any more MI uses.
1102 Heights.erase(HeightI);
1103 }
1104
1105 // Don't process PHI deps. They depend on the specific predecessor, and
1106 // we'll get them when visiting the predecessor.
1107 Deps.clear();
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001108 bool HasPhysRegs = !MI.isPHI() && getDataDeps(MI, Deps, MTM.MRI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001109
1110 // There may also be regunit dependencies to include in the height.
1111 if (HasPhysRegs)
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +00001112 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits, MTM.SchedModel,
1113 MTM.TII, MTM.TRI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001114
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001115 // Update the required height of any virtual registers read by MI.
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001116 for (const DataDep &Dep : Deps)
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +00001117 if (pushDepHeight(Dep, MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001118 addLiveIns(Dep.DefMI, Dep.DefOp, Stack);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001119
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001120 InstrCycles &MICycles = Cycles[&MI];
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001121 MICycles.Height = Cycle;
1122 if (!TBI.HasValidInstrDepths) {
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001123 DEBUG(dbgs() << Cycle << '\t' << MI);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001124 continue;
1125 }
1126 // Update critical path length.
1127 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001128 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << MI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001129 }
1130
1131 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1132 // height because the final height isn't known until now.
1133 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001134 for (LiveInReg &LIR : TBI.LiveIns) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001135 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1136 LIR.Height = Heights.lookup(DefMI);
1137 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1138 }
1139
1140 // Transfer the live regunits to the live-in list.
1141 for (SparseSet<LiveRegUnit>::const_iterator
1142 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1143 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1144 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1145 << '@' << RI->Cycle);
1146 }
1147 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001148
1149 if (!TBI.HasValidInstrDepths)
1150 continue;
1151 // Add live-ins to the critical path length.
1152 TBI.CriticalPath = std::max(TBI.CriticalPath,
1153 computeCrossBlockCriticalPath(TBI));
1154 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001155 }
1156}
1157
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001158MachineTraceMetrics::Trace
1159MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
Sanjay Patel82db3b72015-07-04 15:00:28 +00001160 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1161
1162 if (!TBI.hasValidDepth() || !TBI.hasValidHeight())
1163 computeTrace(MBB);
1164 if (!TBI.HasValidInstrDepths)
1165 computeInstrDepths(MBB);
1166 if (!TBI.HasValidInstrHeights)
1167 computeInstrHeights(MBB);
1168
1169 return Trace(*this, TBI);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001170}
1171
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001172unsigned
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001173MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr &MI) const {
1174 assert(getBlockNum() == unsigned(MI.getParent()->getNumber()) &&
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001175 "MI must be in the trace center block");
1176 InstrCycles Cyc = getInstrCycles(MI);
1177 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1178}
1179
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001180unsigned
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001181MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr &PHI) const {
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001182 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1183 SmallVector<DataDep, 1> Deps;
1184 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1185 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1186 DataDep &Dep = Deps.front();
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001187 unsigned DepCycle = getInstrCycles(*Dep.DefMI).Depth;
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001188 // Add latency if DefMI is a real instruction. Transients get latency 0.
1189 if (!Dep.DefMI->isTransient())
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001190 DepCycle += TE.MTM.SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
1191 &PHI, Dep.UseOp);
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001192 return DepCycle;
1193}
1194
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001195/// When bottom is set include instructions in current block in estimate.
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001196unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001197 // Find the limiting processor resource.
1198 // Numbers have been pre-scaled to be comparable.
1199 unsigned PRMax = 0;
1200 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1201 if (Bottom) {
1202 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1203 for (unsigned K = 0; K != PRDepths.size(); ++K)
1204 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1205 } else {
1206 for (unsigned K = 0; K != PRDepths.size(); ++K)
1207 PRMax = std::max(PRMax, PRDepths[K]);
1208 }
1209 // Convert to cycle count.
1210 PRMax = TE.MTM.getCycles(PRMax);
1211
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001212 /// All instructions before current block
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001213 unsigned Instrs = TBI.InstrDepth;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001214 // plus instructions in current block
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001215 if (Bottom)
1216 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001217 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1218 Instrs /= IW;
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001219 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001220 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001221}
1222
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001223unsigned MachineTraceMetrics::Trace::getResourceLength(
1224 ArrayRef<const MachineBasicBlock *> Extrablocks,
1225 ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1226 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001227 // Add up resources above and below the center block.
1228 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1229 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1230 unsigned PRMax = 0;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001231
1232 // Capture computing cycles from extra instructions
1233 auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
1234 unsigned ResourceIdx)
1235 ->unsigned {
1236 unsigned Cycles = 0;
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001237 for (const MCSchedClassDesc *SC : Instrs) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001238 if (!SC->isValid())
1239 continue;
1240 for (TargetSchedModel::ProcResIter
1241 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1242 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
1243 PI != PE; ++PI) {
1244 if (PI->ProcResourceIdx != ResourceIdx)
1245 continue;
1246 Cycles +=
1247 (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
1248 }
1249 }
1250 return Cycles;
1251 };
1252
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001253 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1254 unsigned PRCycles = PRDepths[K] + PRHeights[K];
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001255 for (const MachineBasicBlock *MBB : Extrablocks)
1256 PRCycles += TE.MTM.getProcResourceCycles(MBB->getNumber())[K];
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001257 PRCycles += extraCycles(ExtraInstrs, K);
1258 PRCycles -= extraCycles(RemoveInstrs, K);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001259 PRMax = std::max(PRMax, PRCycles);
1260 }
1261 // Convert to cycle count.
1262 PRMax = TE.MTM.getCycles(PRMax);
1263
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001264 // Instrs: #instructions in current trace outside current block.
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001265 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001266 // Add instruction count from the extra blocks.
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001267 for (const MachineBasicBlock *MBB : Extrablocks)
1268 Instrs += TE.MTM.getResources(MBB)->InstrCount;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001269 Instrs += ExtraInstrs.size();
1270 Instrs -= RemoveInstrs.size();
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001271 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1272 Instrs /= IW;
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001273 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001274 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001275}
1276
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001277bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr &DefMI,
1278 const MachineInstr &UseMI) const {
1279 if (DefMI.getParent() == UseMI.getParent())
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001280 return true;
1281
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001282 const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI.getParent()->getNumber()];
1283 const TraceBlockInfo &TBI = TE.BlockInfo[UseMI.getParent()->getNumber()];
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001284
1285 return DepTBI.isUsefulDominator(TBI);
1286}
1287
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001288void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1289 OS << getName() << " ensemble:\n";
1290 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1291 OS << " BB#" << i << '\t';
1292 BlockInfo[i].print(OS);
1293 OS << '\n';
1294 }
1295}
1296
1297void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1298 if (hasValidDepth()) {
1299 OS << "depth=" << InstrDepth;
1300 if (Pred)
1301 OS << " pred=BB#" << Pred->getNumber();
1302 else
1303 OS << " pred=null";
1304 OS << " head=BB#" << Head;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +00001305 if (HasValidInstrDepths)
1306 OS << " +instrs";
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001307 } else
1308 OS << "depth invalid";
1309 OS << ", ";
1310 if (hasValidHeight()) {
1311 OS << "height=" << InstrHeight;
1312 if (Succ)
1313 OS << " succ=BB#" << Succ->getNumber();
1314 else
1315 OS << " succ=null";
1316 OS << " tail=BB#" << Tail;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +00001317 if (HasValidInstrHeights)
1318 OS << " +instrs";
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001319 } else
1320 OS << "height invalid";
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001321 if (HasValidInstrDepths && HasValidInstrHeights)
1322 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001323}
1324
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001325void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001326 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1327
1328 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1329 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001330 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1331 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001332 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1333 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001334
1335 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001336 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001337 while (Block->hasValidDepth() && Block->Pred) {
1338 unsigned Num = Block->Pred->getNumber();
1339 OS << " <- BB#" << Num;
1340 Block = &TE.BlockInfo[Num];
1341 }
1342
1343 Block = &TBI;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001344 OS << "\n ";
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001345 while (Block->hasValidHeight() && Block->Succ) {
1346 unsigned Num = Block->Succ->getNumber();
1347 OS << " -> BB#" << Num;
1348 Block = &TE.BlockInfo[Num];
1349 }
1350 OS << '\n';
1351}