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