MachineTraceMetrics.cpp 49 KB

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