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