MachineTraceMetrics.cpp 49 KB

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