00f702c846c5d931ed68dada29ed46df2c8c985a
[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 #define DEBUG_TYPE "machine-trace-metrics"
11 #include "llvm/CodeGen/MachineTraceMetrics.h"
12 #include "llvm/ADT/PostOrderIterator.h"
13 #include "llvm/ADT/SparseSet.h"
14 #include "llvm/CodeGen/MachineBasicBlock.h"
15 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
16 #include "llvm/CodeGen/MachineLoopInfo.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/MC/MCSubtargetInfo.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetSubtargetInfo.h"
26
27 using namespace llvm;
28
29 char MachineTraceMetrics::ID = 0;
30 char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
31
32 INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
33                   "machine-trace-metrics", "Machine Trace Metrics", false, true)
34 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
35 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
36 INITIALIZE_PASS_END(MachineTraceMetrics,
37                   "machine-trace-metrics", "Machine Trace Metrics", false, true)
38
39 MachineTraceMetrics::MachineTraceMetrics()
40   : MachineFunctionPass(ID), MF(0), TII(0), TRI(0), MRI(0), Loops(0) {
41   std::fill(Ensembles, array_endof(Ensembles), (Ensemble*)0);
42 }
43
44 void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
45   AU.setPreservesAll();
46   AU.addRequired<MachineBranchProbabilityInfo>();
47   AU.addRequired<MachineLoopInfo>();
48   MachineFunctionPass::getAnalysisUsage(AU);
49 }
50
51 bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
52   MF = &Func;
53   TII = MF->getTarget().getInstrInfo();
54   TRI = MF->getTarget().getRegisterInfo();
55   MRI = &MF->getRegInfo();
56   Loops = &getAnalysis<MachineLoopInfo>();
57   const TargetSubtargetInfo &ST =
58     MF->getTarget().getSubtarget<TargetSubtargetInfo>();
59   SchedModel.init(*ST.getSchedModel(), &ST, TII);
60   BlockInfo.resize(MF->getNumBlockIDs());
61   ProcResourceCycles.resize(MF->getNumBlockIDs() *
62                             SchedModel.getNumProcResourceKinds());
63   return false;
64 }
65
66 void MachineTraceMetrics::releaseMemory() {
67   MF = 0;
68   BlockInfo.clear();
69   for (unsigned i = 0; i != TS_NumStrategies; ++i) {
70     delete Ensembles[i];
71     Ensembles[i] = 0;
72   }
73 }
74
75 //===----------------------------------------------------------------------===//
76 //                          Fixed block information
77 //===----------------------------------------------------------------------===//
78 //
79 // The number of instructions in a basic block and the CPU resources used by
80 // those instructions don't depend on any given trace strategy.
81
82 /// Compute the resource usage in basic block MBB.
83 const MachineTraceMetrics::FixedBlockInfo*
84 MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
85   assert(MBB && "No basic block");
86   FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
87   if (FBI->hasResources())
88     return FBI;
89
90   // Compute resource usage in the block.
91   FBI->HasCalls = false;
92   unsigned InstrCount = 0;
93
94   // Add up per-processor resource cycles as well.
95   unsigned PRKinds = SchedModel.getNumProcResourceKinds();
96   SmallVector<unsigned, 32> PRCycles(PRKinds);
97
98   for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
99        I != E; ++I) {
100     const MachineInstr *MI = I;
101     if (MI->isTransient())
102       continue;
103     ++InstrCount;
104     if (MI->isCall())
105       FBI->HasCalls = true;
106
107     // Count processor resources used.
108     if (!SchedModel.hasInstrSchedModel())
109       continue;
110     const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(MI);
111     if (!SC->isValid())
112       continue;
113
114     for (TargetSchedModel::ProcResIter
115          PI = SchedModel.getWriteProcResBegin(SC),
116          PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
117       assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
118       PRCycles[PI->ProcResourceIdx] += PI->Cycles;
119     }
120   }
121   FBI->InstrCount = InstrCount;
122
123   // Scale the resource cycles so they are comparable.
124   unsigned PROffset = MBB->getNumber() * PRKinds;
125   for (unsigned K = 0; K != PRKinds; ++K)
126     ProcResourceCycles[PROffset + K] =
127       PRCycles[K] * SchedModel.getResourceFactor(K);
128
129   return FBI;
130 }
131
132 ArrayRef<unsigned>
133 MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
134   assert(BlockInfo[MBBNum].hasResources() &&
135          "getResources() must be called before getProcResourceCycles()");
136   unsigned PRKinds = SchedModel.getNumProcResourceKinds();
137   assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
138   return ArrayRef<unsigned>(ProcResourceCycles.data() + MBBNum * PRKinds,
139                             PRKinds);
140 }
141
142
143 //===----------------------------------------------------------------------===//
144 //                         Ensemble utility functions
145 //===----------------------------------------------------------------------===//
146
147 MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
148   : MTM(*ct) {
149   BlockInfo.resize(MTM.BlockInfo.size());
150   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
151   ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
152   ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
153 }
154
155 // Virtual destructor serves as an anchor.
156 MachineTraceMetrics::Ensemble::~Ensemble() {}
157
158 const MachineLoop*
159 MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
160   return MTM.Loops->getLoopFor(MBB);
161 }
162
163 // Update resource-related information in the TraceBlockInfo for MBB.
164 // Only update resources related to the trace above MBB.
165 void MachineTraceMetrics::Ensemble::
166 computeDepthResources(const MachineBasicBlock *MBB) {
167   TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
168   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
169   unsigned PROffset = MBB->getNumber() * PRKinds;
170
171   // Compute resources from trace above. The top block is simple.
172   if (!TBI->Pred) {
173     TBI->InstrDepth = 0;
174     TBI->Head = MBB->getNumber();
175     std::fill(ProcResourceDepths.begin() + PROffset,
176               ProcResourceDepths.begin() + PROffset + PRKinds, 0);
177     return;
178   }
179
180   // Compute from the block above. A post-order traversal ensures the
181   // predecessor is always computed first.
182   unsigned PredNum = TBI->Pred->getNumber();
183   TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
184   assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
185   const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
186   TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
187   TBI->Head = PredTBI->Head;
188
189   // Compute per-resource depths.
190   ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
191   ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
192   for (unsigned K = 0; K != PRKinds; ++K)
193     ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
194 }
195
196 // Update resource-related information in the TraceBlockInfo for MBB.
197 // Only update resources related to the trace below MBB.
198 void MachineTraceMetrics::Ensemble::
199 computeHeightResources(const MachineBasicBlock *MBB) {
200   TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
201   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
202   unsigned PROffset = MBB->getNumber() * PRKinds;
203
204   // Compute resources for the current block.
205   TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
206   ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
207
208   // The trace tail is done.
209   if (!TBI->Succ) {
210     TBI->Tail = MBB->getNumber();
211     std::copy(PRCycles.begin(), PRCycles.end(),
212               ProcResourceHeights.begin() + PROffset);
213     return;
214   }
215
216   // Compute from the block below. A post-order traversal ensures the
217   // predecessor is always computed first.
218   unsigned SuccNum = TBI->Succ->getNumber();
219   TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
220   assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
221   TBI->InstrHeight += SuccTBI->InstrHeight;
222   TBI->Tail = SuccTBI->Tail;
223
224   // Compute per-resource heights.
225   ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
226   for (unsigned K = 0; K != PRKinds; ++K)
227     ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
228 }
229
230 // Check if depth resources for MBB are valid and return the TBI.
231 // Return NULL if the resources have been invalidated.
232 const MachineTraceMetrics::TraceBlockInfo*
233 MachineTraceMetrics::Ensemble::
234 getDepthResources(const MachineBasicBlock *MBB) const {
235   const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
236   return TBI->hasValidDepth() ? TBI : 0;
237 }
238
239 // Check if height resources for MBB are valid and return the TBI.
240 // Return NULL if the resources have been invalidated.
241 const MachineTraceMetrics::TraceBlockInfo*
242 MachineTraceMetrics::Ensemble::
243 getHeightResources(const MachineBasicBlock *MBB) const {
244   const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
245   return TBI->hasValidHeight() ? TBI : 0;
246 }
247
248 /// Get an array of processor resource depths for MBB. Indexed by processor
249 /// resource kind, this array contains the scaled processor resources consumed
250 /// by all blocks preceding MBB in its trace. It does not include instructions
251 /// in MBB.
252 ///
253 /// Compare TraceBlockInfo::InstrDepth.
254 ArrayRef<unsigned>
255 MachineTraceMetrics::Ensemble::
256 getProcResourceDepths(unsigned MBBNum) const {
257   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
258   assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
259   return ArrayRef<unsigned>(ProcResourceDepths.data() + MBBNum * PRKinds,
260                             PRKinds);
261 }
262
263 /// Get an array of processor resource heights for MBB. Indexed by processor
264 /// resource kind, this array contains the scaled processor resources consumed
265 /// by this block and all blocks following it in its trace.
266 ///
267 /// Compare TraceBlockInfo::InstrHeight.
268 ArrayRef<unsigned>
269 MachineTraceMetrics::Ensemble::
270 getProcResourceHeights(unsigned MBBNum) const {
271   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
272   assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
273   return ArrayRef<unsigned>(ProcResourceHeights.data() + MBBNum * PRKinds,
274                             PRKinds);
275 }
276
277 //===----------------------------------------------------------------------===//
278 //                         Trace Selection Strategies
279 //===----------------------------------------------------------------------===//
280 //
281 // A trace selection strategy is implemented as a sub-class of Ensemble. The
282 // trace through a block B is computed by two DFS traversals of the CFG
283 // starting from B. One upwards, and one downwards. During the upwards DFS,
284 // pickTracePred() is called on the post-ordered blocks. During the downwards
285 // DFS, pickTraceSucc() is called in a post-order.
286 //
287
288 // We never allow traces that leave loops, but we do allow traces to enter
289 // nested loops. We also never allow traces to contain back-edges.
290 //
291 // This means that a loop header can never appear above the center block of a
292 // trace, except as the trace head. Below the center block, loop exiting edges
293 // are banned.
294 //
295 // Return true if an edge from the From loop to the To loop is leaving a loop.
296 // Either of To and From can be null.
297 static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
298   return From && !From->contains(To);
299 }
300
301 // MinInstrCountEnsemble - Pick the trace that executes the least number of
302 // instructions.
303 namespace {
304 class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
305   const char *getName() const { return "MinInstr"; }
306   const MachineBasicBlock *pickTracePred(const MachineBasicBlock*);
307   const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*);
308
309 public:
310   MinInstrCountEnsemble(MachineTraceMetrics *mtm)
311     : MachineTraceMetrics::Ensemble(mtm) {}
312 };
313 }
314
315 // Select the preferred predecessor for MBB.
316 const MachineBasicBlock*
317 MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
318   if (MBB->pred_empty())
319     return 0;
320   const MachineLoop *CurLoop = getLoopFor(MBB);
321   // Don't leave loops, and never follow back-edges.
322   if (CurLoop && MBB == CurLoop->getHeader())
323     return 0;
324   unsigned CurCount = MTM.getResources(MBB)->InstrCount;
325   const MachineBasicBlock *Best = 0;
326   unsigned BestDepth = 0;
327   for (MachineBasicBlock::const_pred_iterator
328        I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
329     const MachineBasicBlock *Pred = *I;
330     const MachineTraceMetrics::TraceBlockInfo *PredTBI =
331       getDepthResources(Pred);
332     // Ignore cycles that aren't natural loops.
333     if (!PredTBI)
334       continue;
335     // Pick the predecessor that would give this block the smallest InstrDepth.
336     unsigned Depth = PredTBI->InstrDepth + CurCount;
337     if (!Best || Depth < BestDepth)
338       Best = Pred, BestDepth = Depth;
339   }
340   return Best;
341 }
342
343 // Select the preferred successor for MBB.
344 const MachineBasicBlock*
345 MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
346   if (MBB->pred_empty())
347     return 0;
348   const MachineLoop *CurLoop = getLoopFor(MBB);
349   const MachineBasicBlock *Best = 0;
350   unsigned BestHeight = 0;
351   for (MachineBasicBlock::const_succ_iterator
352        I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
353     const MachineBasicBlock *Succ = *I;
354     // Don't consider back-edges.
355     if (CurLoop && Succ == CurLoop->getHeader())
356       continue;
357     // Don't consider successors exiting CurLoop.
358     if (isExitingLoop(CurLoop, getLoopFor(Succ)))
359       continue;
360     const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
361       getHeightResources(Succ);
362     // Ignore cycles that aren't natural loops.
363     if (!SuccTBI)
364       continue;
365     // Pick the successor that would give this block the smallest InstrHeight.
366     unsigned Height = SuccTBI->InstrHeight;
367     if (!Best || Height < BestHeight)
368       Best = Succ, BestHeight = Height;
369   }
370   return Best;
371 }
372
373 // Get an Ensemble sub-class for the requested trace strategy.
374 MachineTraceMetrics::Ensemble *
375 MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
376   assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
377   Ensemble *&E = Ensembles[strategy];
378   if (E)
379     return E;
380
381   // Allocate new Ensemble on demand.
382   switch (strategy) {
383   case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
384   default: llvm_unreachable("Invalid trace strategy enum");
385   }
386 }
387
388 void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
389   DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
390   BlockInfo[MBB->getNumber()].invalidate();
391   for (unsigned i = 0; i != TS_NumStrategies; ++i)
392     if (Ensembles[i])
393       Ensembles[i]->invalidate(MBB);
394 }
395
396 void MachineTraceMetrics::verifyAnalysis() const {
397   if (!MF)
398     return;
399 #ifndef NDEBUG
400   assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
401   for (unsigned i = 0; i != TS_NumStrategies; ++i)
402     if (Ensembles[i])
403       Ensembles[i]->verify();
404 #endif
405 }
406
407 //===----------------------------------------------------------------------===//
408 //                               Trace building
409 //===----------------------------------------------------------------------===//
410 //
411 // Traces are built by two CFG traversals. To avoid recomputing too much, use a
412 // set abstraction that confines the search to the current loop, and doesn't
413 // revisit blocks.
414
415 namespace {
416 struct LoopBounds {
417   MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
418   SmallPtrSet<const MachineBasicBlock*, 8> Visited;
419   const MachineLoopInfo *Loops;
420   bool Downward;
421   LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
422              const MachineLoopInfo *loops)
423     : Blocks(blocks), Loops(loops), Downward(false) {}
424 };
425 }
426
427 // Specialize po_iterator_storage in order to prune the post-order traversal so
428 // it is limited to the current loop and doesn't traverse the loop back edges.
429 namespace llvm {
430 template<>
431 class po_iterator_storage<LoopBounds, true> {
432   LoopBounds &LB;
433 public:
434   po_iterator_storage(LoopBounds &lb) : LB(lb) {}
435   void finishPostorder(const MachineBasicBlock*) {}
436
437   bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
438     // Skip already visited To blocks.
439     MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
440     if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
441       return false;
442     // From is null once when To is the trace center block.
443     if (From) {
444       if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
445         // Don't follow backedges, don't leave FromLoop when going upwards.
446         if ((LB.Downward ? To : From) == FromLoop->getHeader())
447           return false;
448         // Don't leave FromLoop.
449         if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
450           return false;
451       }
452     }
453     // To is a new block. Mark the block as visited in case the CFG has cycles
454     // that MachineLoopInfo didn't recognize as a natural loop.
455     return LB.Visited.insert(To);
456   }
457 };
458 }
459
460 /// Compute the trace through MBB.
461 void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
462   DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
463                << MBB->getNumber() << '\n');
464   // Set up loop bounds for the backwards post-order traversal.
465   LoopBounds Bounds(BlockInfo, MTM.Loops);
466
467   // Run an upwards post-order search for the trace start.
468   Bounds.Downward = false;
469   Bounds.Visited.clear();
470   typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
471   for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
472        I != E; ++I) {
473     DEBUG(dbgs() << "  pred for BB#" << I->getNumber() << ": ");
474     TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
475     // All the predecessors have been visited, pick the preferred one.
476     TBI.Pred = pickTracePred(*I);
477     DEBUG({
478       if (TBI.Pred)
479         dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
480       else
481         dbgs() << "null\n";
482     });
483     // The trace leading to I is now known, compute the depth resources.
484     computeDepthResources(*I);
485   }
486
487   // Run a downwards post-order search for the trace end.
488   Bounds.Downward = true;
489   Bounds.Visited.clear();
490   typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
491   for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
492        I != E; ++I) {
493     DEBUG(dbgs() << "  succ for BB#" << I->getNumber() << ": ");
494     TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
495     // All the successors have been visited, pick the preferred one.
496     TBI.Succ = pickTraceSucc(*I);
497     DEBUG({
498       if (TBI.Succ)
499         dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
500       else
501         dbgs() << "null\n";
502     });
503     // The trace leaving I is now known, compute the height resources.
504     computeHeightResources(*I);
505   }
506 }
507
508 /// Invalidate traces through BadMBB.
509 void
510 MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
511   SmallVector<const MachineBasicBlock*, 16> WorkList;
512   TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
513
514   // Invalidate height resources of blocks above MBB.
515   if (BadTBI.hasValidHeight()) {
516     BadTBI.invalidateHeight();
517     WorkList.push_back(BadMBB);
518     do {
519       const MachineBasicBlock *MBB = WorkList.pop_back_val();
520       DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
521             << " height.\n");
522       // Find any MBB predecessors that have MBB as their preferred successor.
523       // They are the only ones that need to be invalidated.
524       for (MachineBasicBlock::const_pred_iterator
525            I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
526         TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
527         if (!TBI.hasValidHeight())
528           continue;
529         if (TBI.Succ == MBB) {
530           TBI.invalidateHeight();
531           WorkList.push_back(*I);
532           continue;
533         }
534         // Verify that TBI.Succ is actually a *I successor.
535         assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
536       }
537     } while (!WorkList.empty());
538   }
539
540   // Invalidate depth resources of blocks below MBB.
541   if (BadTBI.hasValidDepth()) {
542     BadTBI.invalidateDepth();
543     WorkList.push_back(BadMBB);
544     do {
545       const MachineBasicBlock *MBB = WorkList.pop_back_val();
546       DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
547             << " depth.\n");
548       // Find any MBB successors that have MBB as their preferred predecessor.
549       // They are the only ones that need to be invalidated.
550       for (MachineBasicBlock::const_succ_iterator
551            I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
552         TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
553         if (!TBI.hasValidDepth())
554           continue;
555         if (TBI.Pred == MBB) {
556           TBI.invalidateDepth();
557           WorkList.push_back(*I);
558           continue;
559         }
560         // Verify that TBI.Pred is actually a *I predecessor.
561         assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
562       }
563     } while (!WorkList.empty());
564   }
565
566   // Clear any per-instruction data. We only have to do this for BadMBB itself
567   // because the instructions in that block may change. Other blocks may be
568   // invalidated, but their instructions will stay the same, so there is no
569   // need to erase the Cycle entries. They will be overwritten when we
570   // recompute.
571   for (MachineBasicBlock::const_iterator I = BadMBB->begin(), E = BadMBB->end();
572        I != E; ++I)
573     Cycles.erase(I);
574 }
575
576 void MachineTraceMetrics::Ensemble::verify() const {
577 #ifndef NDEBUG
578   assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
579          "Outdated BlockInfo size");
580   for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
581     const TraceBlockInfo &TBI = BlockInfo[Num];
582     if (TBI.hasValidDepth() && TBI.Pred) {
583       const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
584       assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
585       assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
586              "Trace is broken, depth should have been invalidated.");
587       const MachineLoop *Loop = getLoopFor(MBB);
588       assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
589     }
590     if (TBI.hasValidHeight() && TBI.Succ) {
591       const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
592       assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
593       assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
594              "Trace is broken, height should have been invalidated.");
595       const MachineLoop *Loop = getLoopFor(MBB);
596       const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
597       assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
598              "Trace contains backedge");
599     }
600   }
601 #endif
602 }
603
604 //===----------------------------------------------------------------------===//
605 //                             Data Dependencies
606 //===----------------------------------------------------------------------===//
607 //
608 // Compute the depth and height of each instruction based on data dependencies
609 // and instruction latencies. These cycle numbers assume that the CPU can issue
610 // an infinite number of instructions per cycle as long as their dependencies
611 // are ready.
612
613 // A data dependency is represented as a defining MI and operand numbers on the
614 // defining and using MI.
615 namespace {
616 struct DataDep {
617   const MachineInstr *DefMI;
618   unsigned DefOp;
619   unsigned UseOp;
620
621   DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
622     : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
623
624   /// Create a DataDep from an SSA form virtual register.
625   DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
626     : UseOp(UseOp) {
627     assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
628     MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
629     assert(!DefI.atEnd() && "Register has no defs");
630     DefMI = &*DefI;
631     DefOp = DefI.getOperandNo();
632     assert((++DefI).atEnd() && "Register has multiple defs");
633   }
634 };
635 }
636
637 // Get the input data dependencies that must be ready before UseMI can issue.
638 // Return true if UseMI has any physreg operands.
639 static bool getDataDeps(const MachineInstr *UseMI,
640                         SmallVectorImpl<DataDep> &Deps,
641                         const MachineRegisterInfo *MRI) {
642   bool HasPhysRegs = false;
643   for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
644     if (!MO->isReg())
645       continue;
646     unsigned Reg = MO->getReg();
647     if (!Reg)
648       continue;
649     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
650       HasPhysRegs = true;
651       continue;
652     }
653     // Collect virtual register reads.
654     if (MO->readsReg())
655       Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
656   }
657   return HasPhysRegs;
658 }
659
660 // Get the input data dependencies of a PHI instruction, using Pred as the
661 // preferred predecessor.
662 // This will add at most one dependency to Deps.
663 static void getPHIDeps(const MachineInstr *UseMI,
664                        SmallVectorImpl<DataDep> &Deps,
665                        const MachineBasicBlock *Pred,
666                        const MachineRegisterInfo *MRI) {
667   // No predecessor at the beginning of a trace. Ignore dependencies.
668   if (!Pred)
669     return;
670   assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
671   for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
672     if (UseMI->getOperand(i + 1).getMBB() == Pred) {
673       unsigned Reg = UseMI->getOperand(i).getReg();
674       Deps.push_back(DataDep(MRI, Reg, i));
675       return;
676     }
677   }
678 }
679
680 // Keep track of physreg data dependencies by recording each live register unit.
681 // Associate each regunit with an instruction operand. Depending on the
682 // direction instructions are scanned, it could be the operand that defined the
683 // regunit, or the highest operand to read the regunit.
684 namespace {
685 struct LiveRegUnit {
686   unsigned RegUnit;
687   unsigned Cycle;
688   const MachineInstr *MI;
689   unsigned Op;
690
691   unsigned getSparseSetIndex() const { return RegUnit; }
692
693   LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(0), Op(0) {}
694 };
695 }
696
697 // Identify physreg dependencies for UseMI, and update the live regunit
698 // tracking set when scanning instructions downwards.
699 static void updatePhysDepsDownwards(const MachineInstr *UseMI,
700                                     SmallVectorImpl<DataDep> &Deps,
701                                     SparseSet<LiveRegUnit> &RegUnits,
702                                     const TargetRegisterInfo *TRI) {
703   SmallVector<unsigned, 8> Kills;
704   SmallVector<unsigned, 8> LiveDefOps;
705
706   for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
707     if (!MO->isReg())
708       continue;
709     unsigned Reg = MO->getReg();
710     if (!TargetRegisterInfo::isPhysicalRegister(Reg))
711       continue;
712     // Track live defs and kills for updating RegUnits.
713     if (MO->isDef()) {
714       if (MO->isDead())
715         Kills.push_back(Reg);
716       else
717         LiveDefOps.push_back(MO.getOperandNo());
718     } else if (MO->isKill())
719       Kills.push_back(Reg);
720     // Identify dependencies.
721     if (!MO->readsReg())
722       continue;
723     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
724       SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
725       if (I == RegUnits.end())
726         continue;
727       Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
728       break;
729     }
730   }
731
732   // Update RegUnits to reflect live registers after UseMI.
733   // First kills.
734   for (unsigned i = 0, e = Kills.size(); i != e; ++i)
735     for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
736       RegUnits.erase(*Units);
737
738   // Second, live defs.
739   for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
740     unsigned DefOp = LiveDefOps[i];
741     for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
742          Units.isValid(); ++Units) {
743       LiveRegUnit &LRU = RegUnits[*Units];
744       LRU.MI = UseMI;
745       LRU.Op = DefOp;
746     }
747   }
748 }
749
750 /// The length of the critical path through a trace is the maximum of two path
751 /// lengths:
752 ///
753 /// 1. The maximum height+depth over all instructions in the trace center block.
754 ///
755 /// 2. The longest cross-block dependency chain. For small blocks, it is
756 ///    possible that the critical path through the trace doesn't include any
757 ///    instructions in the block.
758 ///
759 /// This function computes the second number from the live-in list of the
760 /// center block.
761 unsigned MachineTraceMetrics::Ensemble::
762 computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
763   assert(TBI.HasValidInstrDepths && "Missing depth info");
764   assert(TBI.HasValidInstrHeights && "Missing height info");
765   unsigned MaxLen = 0;
766   for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
767     const LiveInReg &LIR = TBI.LiveIns[i];
768     if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
769       continue;
770     const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
771     // Ignore dependencies outside the current trace.
772     const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
773     if (!DefTBI.isUsefulDominator(TBI))
774       continue;
775     unsigned Len = LIR.Height + Cycles[DefMI].Depth;
776     MaxLen = std::max(MaxLen, Len);
777   }
778   return MaxLen;
779 }
780
781 /// Compute instruction depths for all instructions above or in MBB in its
782 /// trace. This assumes that the trace through MBB has already been computed.
783 void MachineTraceMetrics::Ensemble::
784 computeInstrDepths(const MachineBasicBlock *MBB) {
785   // The top of the trace may already be computed, and HasValidInstrDepths
786   // implies Head->HasValidInstrDepths, so we only need to start from the first
787   // block in the trace that needs to be recomputed.
788   SmallVector<const MachineBasicBlock*, 8> Stack;
789   do {
790     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
791     assert(TBI.hasValidDepth() && "Incomplete trace");
792     if (TBI.HasValidInstrDepths)
793       break;
794     Stack.push_back(MBB);
795     MBB = TBI.Pred;
796   } while (MBB);
797
798   // FIXME: If MBB is non-null at this point, it is the last pre-computed block
799   // in the trace. We should track any live-out physregs that were defined in
800   // the trace. This is quite rare in SSA form, typically created by CSE
801   // hoisting a compare.
802   SparseSet<LiveRegUnit> RegUnits;
803   RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
804
805   // Go through trace blocks in top-down order, stopping after the center block.
806   SmallVector<DataDep, 8> Deps;
807   while (!Stack.empty()) {
808     MBB = Stack.pop_back_val();
809     DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
810     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
811     TBI.HasValidInstrDepths = true;
812     TBI.CriticalPath = 0;
813
814     // Print out resource depths here as well.
815     DEBUG({
816       dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
817       ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
818       for (unsigned K = 0; K != PRDepths.size(); ++K)
819         if (PRDepths[K]) {
820           unsigned Factor = MTM.SchedModel.getResourceFactor(K);
821           dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
822                  << MTM.SchedModel.getProcResource(K)->Name << " ("
823                  << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
824         }
825     });
826
827     // Also compute the critical path length through MBB when possible.
828     if (TBI.HasValidInstrHeights)
829       TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
830
831     for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
832          I != E; ++I) {
833       const MachineInstr *UseMI = I;
834
835       // Collect all data dependencies.
836       Deps.clear();
837       if (UseMI->isPHI())
838         getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
839       else if (getDataDeps(UseMI, Deps, MTM.MRI))
840         updatePhysDepsDownwards(UseMI, Deps, RegUnits, MTM.TRI);
841
842       // Filter and process dependencies, computing the earliest issue cycle.
843       unsigned Cycle = 0;
844       for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
845         const DataDep &Dep = Deps[i];
846         const TraceBlockInfo&DepTBI =
847           BlockInfo[Dep.DefMI->getParent()->getNumber()];
848         // Ignore dependencies from outside the current trace.
849         if (!DepTBI.isUsefulDominator(TBI))
850           continue;
851         assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
852         unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
853         // Add latency if DefMI is a real instruction. Transients get latency 0.
854         if (!Dep.DefMI->isTransient())
855           DepCycle += MTM.SchedModel
856             .computeOperandLatency(Dep.DefMI, Dep.DefOp, UseMI, Dep.UseOp,
857                                    /* FindMin = */ false);
858         Cycle = std::max(Cycle, DepCycle);
859       }
860       // Remember the instruction depth.
861       InstrCycles &MICycles = Cycles[UseMI];
862       MICycles.Depth = Cycle;
863
864       if (!TBI.HasValidInstrHeights) {
865         DEBUG(dbgs() << Cycle << '\t' << *UseMI);
866         continue;
867       }
868       // Update critical path length.
869       TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
870       DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *UseMI);
871     }
872   }
873 }
874
875 // Identify physreg dependencies for MI when scanning instructions upwards.
876 // Return the issue height of MI after considering any live regunits.
877 // Height is the issue height computed from virtual register dependencies alone.
878 static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
879                                       SparseSet<LiveRegUnit> &RegUnits,
880                                       const TargetSchedModel &SchedModel,
881                                       const TargetInstrInfo *TII,
882                                       const TargetRegisterInfo *TRI) {
883   SmallVector<unsigned, 8> ReadOps;
884   for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
885     if (!MO->isReg())
886       continue;
887     unsigned Reg = MO->getReg();
888     if (!TargetRegisterInfo::isPhysicalRegister(Reg))
889       continue;
890     if (MO->readsReg())
891       ReadOps.push_back(MO.getOperandNo());
892     if (!MO->isDef())
893       continue;
894     // This is a def of Reg. Remove corresponding entries from RegUnits, and
895     // update MI Height to consider the physreg dependencies.
896     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
897       SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
898       if (I == RegUnits.end())
899         continue;
900       unsigned DepHeight = I->Cycle;
901       if (!MI->isTransient()) {
902         // We may not know the UseMI of this dependency, if it came from the
903         // live-in list. SchedModel can handle a NULL UseMI.
904         DepHeight += SchedModel
905           .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op,
906                                  /* FindMin = */ false);
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, false);
945
946   // Update Heights[DefMI] to be the maximum height seen.
947   MIHeightMap::iterator I;
948   bool New;
949   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, false);
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 }