MachineBlockPlacement.cpp 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240
  1. //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
  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. //
  9. // This file implements basic block placement transformations using the CFG
  10. // structure and branch probability estimates.
  11. //
  12. // The pass strives to preserve the structure of the CFG (that is, retain
  13. // a topological ordering of basic blocks) in the absence of a *strong* signal
  14. // to the contrary from probabilities. However, within the CFG structure, it
  15. // attempts to choose an ordering which favors placing more likely sequences of
  16. // blocks adjacent to each other.
  17. //
  18. // The algorithm works from the inner-most loop within a function outward, and
  19. // at each stage walks through the basic blocks, trying to coalesce them into
  20. // sequential chains where allowed by the CFG (or demanded by heavy
  21. // probabilities). Finally, it walks the blocks in topological order, and the
  22. // first time it reaches a chain of basic blocks, it schedules them in the
  23. // function in-order.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "BranchFolding.h"
  27. #include "llvm/ADT/ArrayRef.h"
  28. #include "llvm/ADT/DenseMap.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/SetVector.h"
  31. #include "llvm/ADT/SmallPtrSet.h"
  32. #include "llvm/ADT/SmallVector.h"
  33. #include "llvm/ADT/Statistic.h"
  34. #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
  35. #include "llvm/CodeGen/MachineBasicBlock.h"
  36. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  37. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  38. #include "llvm/CodeGen/MachineFunction.h"
  39. #include "llvm/CodeGen/MachineFunctionPass.h"
  40. #include "llvm/CodeGen/MachineLoopInfo.h"
  41. #include "llvm/CodeGen/MachineModuleInfo.h"
  42. #include "llvm/CodeGen/MachinePostDominators.h"
  43. #include "llvm/CodeGen/TailDuplicator.h"
  44. #include "llvm/CodeGen/TargetInstrInfo.h"
  45. #include "llvm/CodeGen/TargetLowering.h"
  46. #include "llvm/CodeGen/TargetPassConfig.h"
  47. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  48. #include "llvm/IR/DebugLoc.h"
  49. #include "llvm/IR/Function.h"
  50. #include "llvm/Pass.h"
  51. #include "llvm/Support/Allocator.h"
  52. #include "llvm/Support/BlockFrequency.h"
  53. #include "llvm/Support/BranchProbability.h"
  54. #include "llvm/Support/CodeGen.h"
  55. #include "llvm/Support/CommandLine.h"
  56. #include "llvm/Support/Compiler.h"
  57. #include "llvm/Support/Debug.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #include "llvm/Target/TargetMachine.h"
  60. #include <algorithm>
  61. #include <cassert>
  62. #include <cstdint>
  63. #include <iterator>
  64. #include <memory>
  65. #include <string>
  66. #include <tuple>
  67. #include <utility>
  68. #include <vector>
  69. using namespace llvm;
  70. #define DEBUG_TYPE "block-placement"
  71. STATISTIC(NumCondBranches, "Number of conditional branches");
  72. STATISTIC(NumUncondBranches, "Number of unconditional branches");
  73. STATISTIC(CondBranchTakenFreq,
  74. "Potential frequency of taking conditional branches");
  75. STATISTIC(UncondBranchTakenFreq,
  76. "Potential frequency of taking unconditional branches");
  77. static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
  78. cl::desc("Force the alignment of all "
  79. "blocks in the function."),
  80. cl::init(0), cl::Hidden);
  81. static cl::opt<unsigned> AlignAllNonFallThruBlocks(
  82. "align-all-nofallthru-blocks",
  83. cl::desc("Force the alignment of all "
  84. "blocks that have no fall-through predecessors (i.e. don't add "
  85. "nops that are executed)."),
  86. cl::init(0), cl::Hidden);
  87. // FIXME: Find a good default for this flag and remove the flag.
  88. static cl::opt<unsigned> ExitBlockBias(
  89. "block-placement-exit-block-bias",
  90. cl::desc("Block frequency percentage a loop exit block needs "
  91. "over the original exit to be considered the new exit."),
  92. cl::init(0), cl::Hidden);
  93. // Definition:
  94. // - Outlining: placement of a basic block outside the chain or hot path.
  95. static cl::opt<unsigned> LoopToColdBlockRatio(
  96. "loop-to-cold-block-ratio",
  97. cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
  98. "(frequency of block) is greater than this ratio"),
  99. cl::init(5), cl::Hidden);
  100. static cl::opt<bool> ForceLoopColdBlock(
  101. "force-loop-cold-block",
  102. cl::desc("Force outlining cold blocks from loops."),
  103. cl::init(false), cl::Hidden);
  104. static cl::opt<bool>
  105. PreciseRotationCost("precise-rotation-cost",
  106. cl::desc("Model the cost of loop rotation more "
  107. "precisely by using profile data."),
  108. cl::init(false), cl::Hidden);
  109. static cl::opt<bool>
  110. ForcePreciseRotationCost("force-precise-rotation-cost",
  111. cl::desc("Force the use of precise cost "
  112. "loop rotation strategy."),
  113. cl::init(false), cl::Hidden);
  114. static cl::opt<unsigned> MisfetchCost(
  115. "misfetch-cost",
  116. cl::desc("Cost that models the probabilistic risk of an instruction "
  117. "misfetch due to a jump comparing to falling through, whose cost "
  118. "is zero."),
  119. cl::init(1), cl::Hidden);
  120. static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
  121. cl::desc("Cost of jump instructions."),
  122. cl::init(1), cl::Hidden);
  123. static cl::opt<bool>
  124. TailDupPlacement("tail-dup-placement",
  125. cl::desc("Perform tail duplication during placement. "
  126. "Creates more fallthrough opportunites in "
  127. "outline branches."),
  128. cl::init(true), cl::Hidden);
  129. static cl::opt<bool>
  130. BranchFoldPlacement("branch-fold-placement",
  131. cl::desc("Perform branch folding during placement. "
  132. "Reduces code size."),
  133. cl::init(true), cl::Hidden);
  134. // Heuristic for tail duplication.
  135. static cl::opt<unsigned> TailDupPlacementThreshold(
  136. "tail-dup-placement-threshold",
  137. cl::desc("Instruction cutoff for tail duplication during layout. "
  138. "Tail merging during layout is forced to have a threshold "
  139. "that won't conflict."), cl::init(2),
  140. cl::Hidden);
  141. // Heuristic for aggressive tail duplication.
  142. static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
  143. "tail-dup-placement-aggressive-threshold",
  144. cl::desc("Instruction cutoff for aggressive tail duplication during "
  145. "layout. Used at -O3. Tail merging during layout is forced to "
  146. "have a threshold that won't conflict."), cl::init(4),
  147. cl::Hidden);
  148. // Heuristic for tail duplication.
  149. static cl::opt<unsigned> TailDupPlacementPenalty(
  150. "tail-dup-placement-penalty",
  151. cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
  152. "Copying can increase fallthrough, but it also increases icache "
  153. "pressure. This parameter controls the penalty to account for that. "
  154. "Percent as integer."),
  155. cl::init(2),
  156. cl::Hidden);
  157. // Heuristic for triangle chains.
  158. static cl::opt<unsigned> TriangleChainCount(
  159. "triangle-chain-count",
  160. cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
  161. "triangle tail duplication heuristic to kick in. 0 to disable."),
  162. cl::init(2),
  163. cl::Hidden);
  164. extern cl::opt<unsigned> StaticLikelyProb;
  165. extern cl::opt<unsigned> ProfileLikelyProb;
  166. // Internal option used to control BFI display only after MBP pass.
  167. // Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
  168. // -view-block-layout-with-bfi=
  169. extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
  170. // Command line option to specify the name of the function for CFG dump
  171. // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
  172. extern cl::opt<std::string> ViewBlockFreqFuncName;
  173. namespace {
  174. class BlockChain;
  175. /// Type for our function-wide basic block -> block chain mapping.
  176. using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
  177. /// A chain of blocks which will be laid out contiguously.
  178. ///
  179. /// This is the datastructure representing a chain of consecutive blocks that
  180. /// are profitable to layout together in order to maximize fallthrough
  181. /// probabilities and code locality. We also can use a block chain to represent
  182. /// a sequence of basic blocks which have some external (correctness)
  183. /// requirement for sequential layout.
  184. ///
  185. /// Chains can be built around a single basic block and can be merged to grow
  186. /// them. They participate in a block-to-chain mapping, which is updated
  187. /// automatically as chains are merged together.
  188. class BlockChain {
  189. /// The sequence of blocks belonging to this chain.
  190. ///
  191. /// This is the sequence of blocks for a particular chain. These will be laid
  192. /// out in-order within the function.
  193. SmallVector<MachineBasicBlock *, 4> Blocks;
  194. /// A handle to the function-wide basic block to block chain mapping.
  195. ///
  196. /// This is retained in each block chain to simplify the computation of child
  197. /// block chains for SCC-formation and iteration. We store the edges to child
  198. /// basic blocks, and map them back to their associated chains using this
  199. /// structure.
  200. BlockToChainMapType &BlockToChain;
  201. public:
  202. /// Construct a new BlockChain.
  203. ///
  204. /// This builds a new block chain representing a single basic block in the
  205. /// function. It also registers itself as the chain that block participates
  206. /// in with the BlockToChain mapping.
  207. BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
  208. : Blocks(1, BB), BlockToChain(BlockToChain) {
  209. assert(BB && "Cannot create a chain with a null basic block");
  210. BlockToChain[BB] = this;
  211. }
  212. /// Iterator over blocks within the chain.
  213. using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
  214. using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
  215. /// Beginning of blocks within the chain.
  216. iterator begin() { return Blocks.begin(); }
  217. const_iterator begin() const { return Blocks.begin(); }
  218. /// End of blocks within the chain.
  219. iterator end() { return Blocks.end(); }
  220. const_iterator end() const { return Blocks.end(); }
  221. bool remove(MachineBasicBlock* BB) {
  222. for(iterator i = begin(); i != end(); ++i) {
  223. if (*i == BB) {
  224. Blocks.erase(i);
  225. return true;
  226. }
  227. }
  228. return false;
  229. }
  230. /// Merge a block chain into this one.
  231. ///
  232. /// This routine merges a block chain into this one. It takes care of forming
  233. /// a contiguous sequence of basic blocks, updating the edge list, and
  234. /// updating the block -> chain mapping. It does not free or tear down the
  235. /// old chain, but the old chain's block list is no longer valid.
  236. void merge(MachineBasicBlock *BB, BlockChain *Chain) {
  237. assert(BB && "Can't merge a null block.");
  238. assert(!Blocks.empty() && "Can't merge into an empty chain.");
  239. // Fast path in case we don't have a chain already.
  240. if (!Chain) {
  241. assert(!BlockToChain[BB] &&
  242. "Passed chain is null, but BB has entry in BlockToChain.");
  243. Blocks.push_back(BB);
  244. BlockToChain[BB] = this;
  245. return;
  246. }
  247. assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
  248. assert(Chain->begin() != Chain->end());
  249. // Update the incoming blocks to point to this chain, and add them to the
  250. // chain structure.
  251. for (MachineBasicBlock *ChainBB : *Chain) {
  252. Blocks.push_back(ChainBB);
  253. assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
  254. BlockToChain[ChainBB] = this;
  255. }
  256. }
  257. #ifndef NDEBUG
  258. /// Dump the blocks in this chain.
  259. LLVM_DUMP_METHOD void dump() {
  260. for (MachineBasicBlock *MBB : *this)
  261. MBB->dump();
  262. }
  263. #endif // NDEBUG
  264. /// Count of predecessors of any block within the chain which have not
  265. /// yet been scheduled. In general, we will delay scheduling this chain
  266. /// until those predecessors are scheduled (or we find a sufficiently good
  267. /// reason to override this heuristic.) Note that when forming loop chains,
  268. /// blocks outside the loop are ignored and treated as if they were already
  269. /// scheduled.
  270. ///
  271. /// Note: This field is reinitialized multiple times - once for each loop,
  272. /// and then once for the function as a whole.
  273. unsigned UnscheduledPredecessors = 0;
  274. };
  275. class MachineBlockPlacement : public MachineFunctionPass {
  276. /// A type for a block filter set.
  277. using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
  278. /// Pair struct containing basic block and taildup profitability
  279. struct BlockAndTailDupResult {
  280. MachineBasicBlock *BB;
  281. bool ShouldTailDup;
  282. };
  283. /// Triple struct containing edge weight and the edge.
  284. struct WeightedEdge {
  285. BlockFrequency Weight;
  286. MachineBasicBlock *Src;
  287. MachineBasicBlock *Dest;
  288. };
  289. /// work lists of blocks that are ready to be laid out
  290. SmallVector<MachineBasicBlock *, 16> BlockWorkList;
  291. SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
  292. /// Edges that have already been computed as optimal.
  293. DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
  294. /// Machine Function
  295. MachineFunction *F;
  296. /// A handle to the branch probability pass.
  297. const MachineBranchProbabilityInfo *MBPI;
  298. /// A handle to the function-wide block frequency pass.
  299. std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
  300. /// A handle to the loop info.
  301. MachineLoopInfo *MLI;
  302. /// Preferred loop exit.
  303. /// Member variable for convenience. It may be removed by duplication deep
  304. /// in the call stack.
  305. MachineBasicBlock *PreferredLoopExit;
  306. /// A handle to the target's instruction info.
  307. const TargetInstrInfo *TII;
  308. /// A handle to the target's lowering info.
  309. const TargetLoweringBase *TLI;
  310. /// A handle to the post dominator tree.
  311. MachinePostDominatorTree *MPDT;
  312. /// Duplicator used to duplicate tails during placement.
  313. ///
  314. /// Placement decisions can open up new tail duplication opportunities, but
  315. /// since tail duplication affects placement decisions of later blocks, it
  316. /// must be done inline.
  317. TailDuplicator TailDup;
  318. /// Allocator and owner of BlockChain structures.
  319. ///
  320. /// We build BlockChains lazily while processing the loop structure of
  321. /// a function. To reduce malloc traffic, we allocate them using this
  322. /// slab-like allocator, and destroy them after the pass completes. An
  323. /// important guarantee is that this allocator produces stable pointers to
  324. /// the chains.
  325. SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
  326. /// Function wide BasicBlock to BlockChain mapping.
  327. ///
  328. /// This mapping allows efficiently moving from any given basic block to the
  329. /// BlockChain it participates in, if any. We use it to, among other things,
  330. /// allow implicitly defining edges between chains as the existing edges
  331. /// between basic blocks.
  332. DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
  333. #ifndef NDEBUG
  334. /// The set of basic blocks that have terminators that cannot be fully
  335. /// analyzed. These basic blocks cannot be re-ordered safely by
  336. /// MachineBlockPlacement, and we must preserve physical layout of these
  337. /// blocks and their successors through the pass.
  338. SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
  339. #endif
  340. /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
  341. /// if the count goes to 0, add them to the appropriate work list.
  342. void markChainSuccessors(
  343. const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
  344. const BlockFilterSet *BlockFilter = nullptr);
  345. /// Decrease the UnscheduledPredecessors count for a single block, and
  346. /// if the count goes to 0, add them to the appropriate work list.
  347. void markBlockSuccessors(
  348. const BlockChain &Chain, const MachineBasicBlock *BB,
  349. const MachineBasicBlock *LoopHeaderBB,
  350. const BlockFilterSet *BlockFilter = nullptr);
  351. BranchProbability
  352. collectViableSuccessors(
  353. const MachineBasicBlock *BB, const BlockChain &Chain,
  354. const BlockFilterSet *BlockFilter,
  355. SmallVector<MachineBasicBlock *, 4> &Successors);
  356. bool shouldPredBlockBeOutlined(
  357. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  358. const BlockChain &Chain, const BlockFilterSet *BlockFilter,
  359. BranchProbability SuccProb, BranchProbability HotProb);
  360. bool repeatedlyTailDuplicateBlock(
  361. MachineBasicBlock *BB, MachineBasicBlock *&LPred,
  362. const MachineBasicBlock *LoopHeaderBB,
  363. BlockChain &Chain, BlockFilterSet *BlockFilter,
  364. MachineFunction::iterator &PrevUnplacedBlockIt);
  365. bool maybeTailDuplicateBlock(
  366. MachineBasicBlock *BB, MachineBasicBlock *LPred,
  367. BlockChain &Chain, BlockFilterSet *BlockFilter,
  368. MachineFunction::iterator &PrevUnplacedBlockIt,
  369. bool &DuplicatedToLPred);
  370. bool hasBetterLayoutPredecessor(
  371. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  372. const BlockChain &SuccChain, BranchProbability SuccProb,
  373. BranchProbability RealSuccProb, const BlockChain &Chain,
  374. const BlockFilterSet *BlockFilter);
  375. BlockAndTailDupResult selectBestSuccessor(
  376. const MachineBasicBlock *BB, const BlockChain &Chain,
  377. const BlockFilterSet *BlockFilter);
  378. MachineBasicBlock *selectBestCandidateBlock(
  379. const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
  380. MachineBasicBlock *getFirstUnplacedBlock(
  381. const BlockChain &PlacedChain,
  382. MachineFunction::iterator &PrevUnplacedBlockIt,
  383. const BlockFilterSet *BlockFilter);
  384. /// Add a basic block to the work list if it is appropriate.
  385. ///
  386. /// If the optional parameter BlockFilter is provided, only MBB
  387. /// present in the set will be added to the worklist. If nullptr
  388. /// is provided, no filtering occurs.
  389. void fillWorkLists(const MachineBasicBlock *MBB,
  390. SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
  391. const BlockFilterSet *BlockFilter);
  392. void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
  393. BlockFilterSet *BlockFilter = nullptr);
  394. bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock,
  395. const MachineBasicBlock *OldTop);
  396. bool hasViableTopFallthrough(const MachineBasicBlock *Top,
  397. const BlockFilterSet &LoopBlockSet);
  398. BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top,
  399. const BlockFilterSet &LoopBlockSet);
  400. BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop,
  401. const MachineBasicBlock *OldTop,
  402. const MachineBasicBlock *ExitBB,
  403. const BlockFilterSet &LoopBlockSet);
  404. MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop,
  405. const MachineLoop &L,
  406. const BlockFilterSet &LoopBlockSet,
  407. bool HasStaticProfileOnly = false);
  408. MachineBasicBlock *findBestLoopTop(
  409. const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
  410. MachineBasicBlock *findBestLoopTopNoProfile(
  411. const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
  412. MachineBasicBlock *findBestLoopExit(
  413. const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
  414. BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
  415. void buildLoopChains(const MachineLoop &L);
  416. void rotateLoop(
  417. BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
  418. const BlockFilterSet &LoopBlockSet);
  419. void rotateLoopWithProfile(
  420. BlockChain &LoopChain, const MachineLoop &L,
  421. const BlockFilterSet &LoopBlockSet);
  422. void buildCFGChains();
  423. void optimizeBranches();
  424. void alignBlocks();
  425. /// Returns true if a block should be tail-duplicated to increase fallthrough
  426. /// opportunities.
  427. bool shouldTailDuplicate(MachineBasicBlock *BB);
  428. /// Check the edge frequencies to see if tail duplication will increase
  429. /// fallthroughs.
  430. bool isProfitableToTailDup(
  431. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  432. BranchProbability QProb,
  433. const BlockChain &Chain, const BlockFilterSet *BlockFilter);
  434. /// Check for a trellis layout.
  435. bool isTrellis(const MachineBasicBlock *BB,
  436. const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
  437. const BlockChain &Chain, const BlockFilterSet *BlockFilter);
  438. /// Get the best successor given a trellis layout.
  439. BlockAndTailDupResult getBestTrellisSuccessor(
  440. const MachineBasicBlock *BB,
  441. const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
  442. BranchProbability AdjustedSumProb, const BlockChain &Chain,
  443. const BlockFilterSet *BlockFilter);
  444. /// Get the best pair of non-conflicting edges.
  445. static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
  446. const MachineBasicBlock *BB,
  447. MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
  448. /// Returns true if a block can tail duplicate into all unplaced
  449. /// predecessors. Filters based on loop.
  450. bool canTailDuplicateUnplacedPreds(
  451. const MachineBasicBlock *BB, MachineBasicBlock *Succ,
  452. const BlockChain &Chain, const BlockFilterSet *BlockFilter);
  453. /// Find chains of triangles to tail-duplicate where a global analysis works,
  454. /// but a local analysis would not find them.
  455. void precomputeTriangleChains();
  456. public:
  457. static char ID; // Pass identification, replacement for typeid
  458. MachineBlockPlacement() : MachineFunctionPass(ID) {
  459. initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
  460. }
  461. bool runOnMachineFunction(MachineFunction &F) override;
  462. bool allowTailDupPlacement() const {
  463. assert(F);
  464. return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
  465. }
  466. void getAnalysisUsage(AnalysisUsage &AU) const override {
  467. AU.addRequired<MachineBranchProbabilityInfo>();
  468. AU.addRequired<MachineBlockFrequencyInfo>();
  469. if (TailDupPlacement)
  470. AU.addRequired<MachinePostDominatorTree>();
  471. AU.addRequired<MachineLoopInfo>();
  472. AU.addRequired<TargetPassConfig>();
  473. MachineFunctionPass::getAnalysisUsage(AU);
  474. }
  475. };
  476. } // end anonymous namespace
  477. char MachineBlockPlacement::ID = 0;
  478. char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
  479. INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
  480. "Branch Probability Basic Block Placement", false, false)
  481. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  482. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  483. INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
  484. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  485. INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
  486. "Branch Probability Basic Block Placement", false, false)
  487. #ifndef NDEBUG
  488. /// Helper to print the name of a MBB.
  489. ///
  490. /// Only used by debug logging.
  491. static std::string getBlockName(const MachineBasicBlock *BB) {
  492. std::string Result;
  493. raw_string_ostream OS(Result);
  494. OS << printMBBReference(*BB);
  495. OS << " ('" << BB->getName() << "')";
  496. OS.flush();
  497. return Result;
  498. }
  499. #endif
  500. /// Mark a chain's successors as having one fewer preds.
  501. ///
  502. /// When a chain is being merged into the "placed" chain, this routine will
  503. /// quickly walk the successors of each block in the chain and mark them as
  504. /// having one fewer active predecessor. It also adds any successors of this
  505. /// chain which reach the zero-predecessor state to the appropriate worklist.
  506. void MachineBlockPlacement::markChainSuccessors(
  507. const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
  508. const BlockFilterSet *BlockFilter) {
  509. // Walk all the blocks in this chain, marking their successors as having
  510. // a predecessor placed.
  511. for (MachineBasicBlock *MBB : Chain) {
  512. markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
  513. }
  514. }
  515. /// Mark a single block's successors as having one fewer preds.
  516. ///
  517. /// Under normal circumstances, this is only called by markChainSuccessors,
  518. /// but if a block that was to be placed is completely tail-duplicated away,
  519. /// and was duplicated into the chain end, we need to redo markBlockSuccessors
  520. /// for just that block.
  521. void MachineBlockPlacement::markBlockSuccessors(
  522. const BlockChain &Chain, const MachineBasicBlock *MBB,
  523. const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
  524. // Add any successors for which this is the only un-placed in-loop
  525. // predecessor to the worklist as a viable candidate for CFG-neutral
  526. // placement. No subsequent placement of this block will violate the CFG
  527. // shape, so we get to use heuristics to choose a favorable placement.
  528. for (MachineBasicBlock *Succ : MBB->successors()) {
  529. if (BlockFilter && !BlockFilter->count(Succ))
  530. continue;
  531. BlockChain &SuccChain = *BlockToChain[Succ];
  532. // Disregard edges within a fixed chain, or edges to the loop header.
  533. if (&Chain == &SuccChain || Succ == LoopHeaderBB)
  534. continue;
  535. // This is a cross-chain edge that is within the loop, so decrement the
  536. // loop predecessor count of the destination chain.
  537. if (SuccChain.UnscheduledPredecessors == 0 ||
  538. --SuccChain.UnscheduledPredecessors > 0)
  539. continue;
  540. auto *NewBB = *SuccChain.begin();
  541. if (NewBB->isEHPad())
  542. EHPadWorkList.push_back(NewBB);
  543. else
  544. BlockWorkList.push_back(NewBB);
  545. }
  546. }
  547. /// This helper function collects the set of successors of block
  548. /// \p BB that are allowed to be its layout successors, and return
  549. /// the total branch probability of edges from \p BB to those
  550. /// blocks.
  551. BranchProbability MachineBlockPlacement::collectViableSuccessors(
  552. const MachineBasicBlock *BB, const BlockChain &Chain,
  553. const BlockFilterSet *BlockFilter,
  554. SmallVector<MachineBasicBlock *, 4> &Successors) {
  555. // Adjust edge probabilities by excluding edges pointing to blocks that is
  556. // either not in BlockFilter or is already in the current chain. Consider the
  557. // following CFG:
  558. //
  559. // --->A
  560. // | / \
  561. // | B C
  562. // | \ / \
  563. // ----D E
  564. //
  565. // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
  566. // A->C is chosen as a fall-through, D won't be selected as a successor of C
  567. // due to CFG constraint (the probability of C->D is not greater than
  568. // HotProb to break topo-order). If we exclude E that is not in BlockFilter
  569. // when calculating the probability of C->D, D will be selected and we
  570. // will get A C D B as the layout of this loop.
  571. auto AdjustedSumProb = BranchProbability::getOne();
  572. for (MachineBasicBlock *Succ : BB->successors()) {
  573. bool SkipSucc = false;
  574. if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
  575. SkipSucc = true;
  576. } else {
  577. BlockChain *SuccChain = BlockToChain[Succ];
  578. if (SuccChain == &Chain) {
  579. SkipSucc = true;
  580. } else if (Succ != *SuccChain->begin()) {
  581. LLVM_DEBUG(dbgs() << " " << getBlockName(Succ)
  582. << " -> Mid chain!\n");
  583. continue;
  584. }
  585. }
  586. if (SkipSucc)
  587. AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
  588. else
  589. Successors.push_back(Succ);
  590. }
  591. return AdjustedSumProb;
  592. }
  593. /// The helper function returns the branch probability that is adjusted
  594. /// or normalized over the new total \p AdjustedSumProb.
  595. static BranchProbability
  596. getAdjustedProbability(BranchProbability OrigProb,
  597. BranchProbability AdjustedSumProb) {
  598. BranchProbability SuccProb;
  599. uint32_t SuccProbN = OrigProb.getNumerator();
  600. uint32_t SuccProbD = AdjustedSumProb.getNumerator();
  601. if (SuccProbN >= SuccProbD)
  602. SuccProb = BranchProbability::getOne();
  603. else
  604. SuccProb = BranchProbability(SuccProbN, SuccProbD);
  605. return SuccProb;
  606. }
  607. /// Check if \p BB has exactly the successors in \p Successors.
  608. static bool
  609. hasSameSuccessors(MachineBasicBlock &BB,
  610. SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
  611. if (BB.succ_size() != Successors.size())
  612. return false;
  613. // We don't want to count self-loops
  614. if (Successors.count(&BB))
  615. return false;
  616. for (MachineBasicBlock *Succ : BB.successors())
  617. if (!Successors.count(Succ))
  618. return false;
  619. return true;
  620. }
  621. /// Check if a block should be tail duplicated to increase fallthrough
  622. /// opportunities.
  623. /// \p BB Block to check.
  624. bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
  625. // Blocks with single successors don't create additional fallthrough
  626. // opportunities. Don't duplicate them. TODO: When conditional exits are
  627. // analyzable, allow them to be duplicated.
  628. bool IsSimple = TailDup.isSimpleBB(BB);
  629. if (BB->succ_size() == 1)
  630. return false;
  631. return TailDup.shouldTailDuplicate(IsSimple, *BB);
  632. }
  633. /// Compare 2 BlockFrequency's with a small penalty for \p A.
  634. /// In order to be conservative, we apply a X% penalty to account for
  635. /// increased icache pressure and static heuristics. For small frequencies
  636. /// we use only the numerators to improve accuracy. For simplicity, we assume the
  637. /// penalty is less than 100%
  638. /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
  639. static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
  640. uint64_t EntryFreq) {
  641. BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
  642. BlockFrequency Gain = A - B;
  643. return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
  644. }
  645. /// Check the edge frequencies to see if tail duplication will increase
  646. /// fallthroughs. It only makes sense to call this function when
  647. /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
  648. /// always locally profitable if we would have picked \p Succ without
  649. /// considering duplication.
  650. bool MachineBlockPlacement::isProfitableToTailDup(
  651. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  652. BranchProbability QProb,
  653. const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
  654. // We need to do a probability calculation to make sure this is profitable.
  655. // First: does succ have a successor that post-dominates? This affects the
  656. // calculation. The 2 relevant cases are:
  657. // BB BB
  658. // | \Qout | \Qout
  659. // P| C |P C
  660. // = C' = C'
  661. // | /Qin | /Qin
  662. // | / | /
  663. // Succ Succ
  664. // / \ | \ V
  665. // U/ =V |U \
  666. // / \ = D
  667. // D E | /
  668. // | /
  669. // |/
  670. // PDom
  671. // '=' : Branch taken for that CFG edge
  672. // In the second case, Placing Succ while duplicating it into C prevents the
  673. // fallthrough of Succ into either D or PDom, because they now have C as an
  674. // unplaced predecessor
  675. // Start by figuring out which case we fall into
  676. MachineBasicBlock *PDom = nullptr;
  677. SmallVector<MachineBasicBlock *, 4> SuccSuccs;
  678. // Only scan the relevant successors
  679. auto AdjustedSuccSumProb =
  680. collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
  681. BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
  682. auto BBFreq = MBFI->getBlockFreq(BB);
  683. auto SuccFreq = MBFI->getBlockFreq(Succ);
  684. BlockFrequency P = BBFreq * PProb;
  685. BlockFrequency Qout = BBFreq * QProb;
  686. uint64_t EntryFreq = MBFI->getEntryFreq();
  687. // If there are no more successors, it is profitable to copy, as it strictly
  688. // increases fallthrough.
  689. if (SuccSuccs.size() == 0)
  690. return greaterWithBias(P, Qout, EntryFreq);
  691. auto BestSuccSucc = BranchProbability::getZero();
  692. // Find the PDom or the best Succ if no PDom exists.
  693. for (MachineBasicBlock *SuccSucc : SuccSuccs) {
  694. auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
  695. if (Prob > BestSuccSucc)
  696. BestSuccSucc = Prob;
  697. if (PDom == nullptr)
  698. if (MPDT->dominates(SuccSucc, Succ)) {
  699. PDom = SuccSucc;
  700. break;
  701. }
  702. }
  703. // For the comparisons, we need to know Succ's best incoming edge that isn't
  704. // from BB.
  705. auto SuccBestPred = BlockFrequency(0);
  706. for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
  707. if (SuccPred == Succ || SuccPred == BB
  708. || BlockToChain[SuccPred] == &Chain
  709. || (BlockFilter && !BlockFilter->count(SuccPred)))
  710. continue;
  711. auto Freq = MBFI->getBlockFreq(SuccPred)
  712. * MBPI->getEdgeProbability(SuccPred, Succ);
  713. if (Freq > SuccBestPred)
  714. SuccBestPred = Freq;
  715. }
  716. // Qin is Succ's best unplaced incoming edge that isn't BB
  717. BlockFrequency Qin = SuccBestPred;
  718. // If it doesn't have a post-dominating successor, here is the calculation:
  719. // BB BB
  720. // | \Qout | \
  721. // P| C | =
  722. // = C' | C
  723. // | /Qin | |
  724. // | / | C' (+Succ)
  725. // Succ Succ /|
  726. // / \ | \/ |
  727. // U/ =V | == |
  728. // / \ | / \|
  729. // D E D E
  730. // '=' : Branch taken for that CFG edge
  731. // Cost in the first case is: P + V
  732. // For this calculation, we always assume P > Qout. If Qout > P
  733. // The result of this function will be ignored at the caller.
  734. // Let F = SuccFreq - Qin
  735. // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
  736. if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
  737. BranchProbability UProb = BestSuccSucc;
  738. BranchProbability VProb = AdjustedSuccSumProb - UProb;
  739. BlockFrequency F = SuccFreq - Qin;
  740. BlockFrequency V = SuccFreq * VProb;
  741. BlockFrequency QinU = std::min(Qin, F) * UProb;
  742. BlockFrequency BaseCost = P + V;
  743. BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
  744. return greaterWithBias(BaseCost, DupCost, EntryFreq);
  745. }
  746. BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
  747. BranchProbability VProb = AdjustedSuccSumProb - UProb;
  748. BlockFrequency U = SuccFreq * UProb;
  749. BlockFrequency V = SuccFreq * VProb;
  750. BlockFrequency F = SuccFreq - Qin;
  751. // If there is a post-dominating successor, here is the calculation:
  752. // BB BB BB BB
  753. // | \Qout | \ | \Qout | \
  754. // |P C | = |P C | =
  755. // = C' |P C = C' |P C
  756. // | /Qin | | | /Qin | |
  757. // | / | C' (+Succ) | / | C' (+Succ)
  758. // Succ Succ /| Succ Succ /|
  759. // | \ V | \/ | | \ V | \/ |
  760. // |U \ |U /\ =? |U = |U /\ |
  761. // = D = = =?| | D | = =|
  762. // | / |/ D | / |/ D
  763. // | / | / | = | /
  764. // |/ | / |/ | =
  765. // Dom Dom Dom Dom
  766. // '=' : Branch taken for that CFG edge
  767. // The cost for taken branches in the first case is P + U
  768. // Let F = SuccFreq - Qin
  769. // The cost in the second case (assuming independence), given the layout:
  770. // BB, Succ, (C+Succ), D, Dom or the layout:
  771. // BB, Succ, D, Dom, (C+Succ)
  772. // is Qout + max(F, Qin) * U + min(F, Qin)
  773. // compare P + U vs Qout + P * U + Qin.
  774. //
  775. // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
  776. //
  777. // For the 3rd case, the cost is P + 2 * V
  778. // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
  779. // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
  780. if (UProb > AdjustedSuccSumProb / 2 &&
  781. !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
  782. Chain, BlockFilter))
  783. // Cases 3 & 4
  784. return greaterWithBias(
  785. (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
  786. EntryFreq);
  787. // Cases 1 & 2
  788. return greaterWithBias((P + U),
  789. (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
  790. std::max(Qin, F) * UProb),
  791. EntryFreq);
  792. }
  793. /// Check for a trellis layout. \p BB is the upper part of a trellis if its
  794. /// successors form the lower part of a trellis. A successor set S forms the
  795. /// lower part of a trellis if all of the predecessors of S are either in S or
  796. /// have all of S as successors. We ignore trellises where BB doesn't have 2
  797. /// successors because for fewer than 2, it's trivial, and for 3 or greater they
  798. /// are very uncommon and complex to compute optimally. Allowing edges within S
  799. /// is not strictly a trellis, but the same algorithm works, so we allow it.
  800. bool MachineBlockPlacement::isTrellis(
  801. const MachineBasicBlock *BB,
  802. const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
  803. const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
  804. // Technically BB could form a trellis with branching factor higher than 2.
  805. // But that's extremely uncommon.
  806. if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
  807. return false;
  808. SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
  809. BB->succ_end());
  810. // To avoid reviewing the same predecessors twice.
  811. SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
  812. for (MachineBasicBlock *Succ : ViableSuccs) {
  813. int PredCount = 0;
  814. for (auto SuccPred : Succ->predecessors()) {
  815. // Allow triangle successors, but don't count them.
  816. if (Successors.count(SuccPred)) {
  817. // Make sure that it is actually a triangle.
  818. for (MachineBasicBlock *CheckSucc : SuccPred->successors())
  819. if (!Successors.count(CheckSucc))
  820. return false;
  821. continue;
  822. }
  823. const BlockChain *PredChain = BlockToChain[SuccPred];
  824. if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
  825. PredChain == &Chain || PredChain == BlockToChain[Succ])
  826. continue;
  827. ++PredCount;
  828. // Perform the successor check only once.
  829. if (!SeenPreds.insert(SuccPred).second)
  830. continue;
  831. if (!hasSameSuccessors(*SuccPred, Successors))
  832. return false;
  833. }
  834. // If one of the successors has only BB as a predecessor, it is not a
  835. // trellis.
  836. if (PredCount < 1)
  837. return false;
  838. }
  839. return true;
  840. }
  841. /// Pick the highest total weight pair of edges that can both be laid out.
  842. /// The edges in \p Edges[0] are assumed to have a different destination than
  843. /// the edges in \p Edges[1]. Simple counting shows that the best pair is either
  844. /// the individual highest weight edges to the 2 different destinations, or in
  845. /// case of a conflict, one of them should be replaced with a 2nd best edge.
  846. std::pair<MachineBlockPlacement::WeightedEdge,
  847. MachineBlockPlacement::WeightedEdge>
  848. MachineBlockPlacement::getBestNonConflictingEdges(
  849. const MachineBasicBlock *BB,
  850. MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
  851. Edges) {
  852. // Sort the edges, and then for each successor, find the best incoming
  853. // predecessor. If the best incoming predecessors aren't the same,
  854. // then that is clearly the best layout. If there is a conflict, one of the
  855. // successors will have to fallthrough from the second best predecessor. We
  856. // compare which combination is better overall.
  857. // Sort for highest frequency.
  858. auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
  859. llvm::stable_sort(Edges[0], Cmp);
  860. llvm::stable_sort(Edges[1], Cmp);
  861. auto BestA = Edges[0].begin();
  862. auto BestB = Edges[1].begin();
  863. // Arrange for the correct answer to be in BestA and BestB
  864. // If the 2 best edges don't conflict, the answer is already there.
  865. if (BestA->Src == BestB->Src) {
  866. // Compare the total fallthrough of (Best + Second Best) for both pairs
  867. auto SecondBestA = std::next(BestA);
  868. auto SecondBestB = std::next(BestB);
  869. BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
  870. BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
  871. if (BestAScore < BestBScore)
  872. BestA = SecondBestA;
  873. else
  874. BestB = SecondBestB;
  875. }
  876. // Arrange for the BB edge to be in BestA if it exists.
  877. if (BestB->Src == BB)
  878. std::swap(BestA, BestB);
  879. return std::make_pair(*BestA, *BestB);
  880. }
  881. /// Get the best successor from \p BB based on \p BB being part of a trellis.
  882. /// We only handle trellises with 2 successors, so the algorithm is
  883. /// straightforward: Find the best pair of edges that don't conflict. We find
  884. /// the best incoming edge for each successor in the trellis. If those conflict,
  885. /// we consider which of them should be replaced with the second best.
  886. /// Upon return the two best edges will be in \p BestEdges. If one of the edges
  887. /// comes from \p BB, it will be in \p BestEdges[0]
  888. MachineBlockPlacement::BlockAndTailDupResult
  889. MachineBlockPlacement::getBestTrellisSuccessor(
  890. const MachineBasicBlock *BB,
  891. const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
  892. BranchProbability AdjustedSumProb, const BlockChain &Chain,
  893. const BlockFilterSet *BlockFilter) {
  894. BlockAndTailDupResult Result = {nullptr, false};
  895. SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
  896. BB->succ_end());
  897. // We assume size 2 because it's common. For general n, we would have to do
  898. // the Hungarian algorithm, but it's not worth the complexity because more
  899. // than 2 successors is fairly uncommon, and a trellis even more so.
  900. if (Successors.size() != 2 || ViableSuccs.size() != 2)
  901. return Result;
  902. // Collect the edge frequencies of all edges that form the trellis.
  903. SmallVector<WeightedEdge, 8> Edges[2];
  904. int SuccIndex = 0;
  905. for (auto Succ : ViableSuccs) {
  906. for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
  907. // Skip any placed predecessors that are not BB
  908. if (SuccPred != BB)
  909. if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
  910. BlockToChain[SuccPred] == &Chain ||
  911. BlockToChain[SuccPred] == BlockToChain[Succ])
  912. continue;
  913. BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
  914. MBPI->getEdgeProbability(SuccPred, Succ);
  915. Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
  916. }
  917. ++SuccIndex;
  918. }
  919. // Pick the best combination of 2 edges from all the edges in the trellis.
  920. WeightedEdge BestA, BestB;
  921. std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
  922. if (BestA.Src != BB) {
  923. // If we have a trellis, and BB doesn't have the best fallthrough edges,
  924. // we shouldn't choose any successor. We've already looked and there's a
  925. // better fallthrough edge for all the successors.
  926. LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
  927. return Result;
  928. }
  929. // Did we pick the triangle edge? If tail-duplication is profitable, do
  930. // that instead. Otherwise merge the triangle edge now while we know it is
  931. // optimal.
  932. if (BestA.Dest == BestB.Src) {
  933. // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
  934. // would be better.
  935. MachineBasicBlock *Succ1 = BestA.Dest;
  936. MachineBasicBlock *Succ2 = BestB.Dest;
  937. // Check to see if tail-duplication would be profitable.
  938. if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
  939. canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
  940. isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
  941. Chain, BlockFilter)) {
  942. LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
  943. MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
  944. dbgs() << " Selected: " << getBlockName(Succ2)
  945. << ", probability: " << Succ2Prob
  946. << " (Tail Duplicate)\n");
  947. Result.BB = Succ2;
  948. Result.ShouldTailDup = true;
  949. return Result;
  950. }
  951. }
  952. // We have already computed the optimal edge for the other side of the
  953. // trellis.
  954. ComputedEdges[BestB.Src] = { BestB.Dest, false };
  955. auto TrellisSucc = BestA.Dest;
  956. LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
  957. MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
  958. dbgs() << " Selected: " << getBlockName(TrellisSucc)
  959. << ", probability: " << SuccProb << " (Trellis)\n");
  960. Result.BB = TrellisSucc;
  961. return Result;
  962. }
  963. /// When the option allowTailDupPlacement() is on, this method checks if the
  964. /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
  965. /// into all of its unplaced, unfiltered predecessors, that are not BB.
  966. bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
  967. const MachineBasicBlock *BB, MachineBasicBlock *Succ,
  968. const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
  969. if (!shouldTailDuplicate(Succ))
  970. return false;
  971. // For CFG checking.
  972. SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
  973. BB->succ_end());
  974. for (MachineBasicBlock *Pred : Succ->predecessors()) {
  975. // Make sure all unplaced and unfiltered predecessors can be
  976. // tail-duplicated into.
  977. // Skip any blocks that are already placed or not in this loop.
  978. if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
  979. || BlockToChain[Pred] == &Chain)
  980. continue;
  981. if (!TailDup.canTailDuplicate(Succ, Pred)) {
  982. if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
  983. // This will result in a trellis after tail duplication, so we don't
  984. // need to copy Succ into this predecessor. In the presence
  985. // of a trellis tail duplication can continue to be profitable.
  986. // For example:
  987. // A A
  988. // |\ |\
  989. // | \ | \
  990. // | C | C+BB
  991. // | / | |
  992. // |/ | |
  993. // BB => BB |
  994. // |\ |\/|
  995. // | \ |/\|
  996. // | D | D
  997. // | / | /
  998. // |/ |/
  999. // Succ Succ
  1000. //
  1001. // After BB was duplicated into C, the layout looks like the one on the
  1002. // right. BB and C now have the same successors. When considering
  1003. // whether Succ can be duplicated into all its unplaced predecessors, we
  1004. // ignore C.
  1005. // We can do this because C already has a profitable fallthrough, namely
  1006. // D. TODO(iteratee): ignore sufficiently cold predecessors for
  1007. // duplication and for this test.
  1008. //
  1009. // This allows trellises to be laid out in 2 separate chains
  1010. // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
  1011. // because it allows the creation of 2 fallthrough paths with links
  1012. // between them, and we correctly identify the best layout for these
  1013. // CFGs. We want to extend trellises that the user created in addition
  1014. // to trellises created by tail-duplication, so we just look for the
  1015. // CFG.
  1016. continue;
  1017. return false;
  1018. }
  1019. }
  1020. return true;
  1021. }
  1022. /// Find chains of triangles where we believe it would be profitable to
  1023. /// tail-duplicate them all, but a local analysis would not find them.
  1024. /// There are 3 ways this can be profitable:
  1025. /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
  1026. /// longer chains)
  1027. /// 2) The chains are statically correlated. Branch probabilities have a very
  1028. /// U-shaped distribution.
  1029. /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
  1030. /// If the branches in a chain are likely to be from the same side of the
  1031. /// distribution as their predecessor, but are independent at runtime, this
  1032. /// transformation is profitable. (Because the cost of being wrong is a small
  1033. /// fixed cost, unlike the standard triangle layout where the cost of being
  1034. /// wrong scales with the # of triangles.)
  1035. /// 3) The chains are dynamically correlated. If the probability that a previous
  1036. /// branch was taken positively influences whether the next branch will be
  1037. /// taken
  1038. /// We believe that 2 and 3 are common enough to justify the small margin in 1.
  1039. void MachineBlockPlacement::precomputeTriangleChains() {
  1040. struct TriangleChain {
  1041. std::vector<MachineBasicBlock *> Edges;
  1042. TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
  1043. : Edges({src, dst}) {}
  1044. void append(MachineBasicBlock *dst) {
  1045. assert(getKey()->isSuccessor(dst) &&
  1046. "Attempting to append a block that is not a successor.");
  1047. Edges.push_back(dst);
  1048. }
  1049. unsigned count() const { return Edges.size() - 1; }
  1050. MachineBasicBlock *getKey() const {
  1051. return Edges.back();
  1052. }
  1053. };
  1054. if (TriangleChainCount == 0)
  1055. return;
  1056. LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
  1057. // Map from last block to the chain that contains it. This allows us to extend
  1058. // chains as we find new triangles.
  1059. DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
  1060. for (MachineBasicBlock &BB : *F) {
  1061. // If BB doesn't have 2 successors, it doesn't start a triangle.
  1062. if (BB.succ_size() != 2)
  1063. continue;
  1064. MachineBasicBlock *PDom = nullptr;
  1065. for (MachineBasicBlock *Succ : BB.successors()) {
  1066. if (!MPDT->dominates(Succ, &BB))
  1067. continue;
  1068. PDom = Succ;
  1069. break;
  1070. }
  1071. // If BB doesn't have a post-dominating successor, it doesn't form a
  1072. // triangle.
  1073. if (PDom == nullptr)
  1074. continue;
  1075. // If PDom has a hint that it is low probability, skip this triangle.
  1076. if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
  1077. continue;
  1078. // If PDom isn't eligible for duplication, this isn't the kind of triangle
  1079. // we're looking for.
  1080. if (!shouldTailDuplicate(PDom))
  1081. continue;
  1082. bool CanTailDuplicate = true;
  1083. // If PDom can't tail-duplicate into it's non-BB predecessors, then this
  1084. // isn't the kind of triangle we're looking for.
  1085. for (MachineBasicBlock* Pred : PDom->predecessors()) {
  1086. if (Pred == &BB)
  1087. continue;
  1088. if (!TailDup.canTailDuplicate(PDom, Pred)) {
  1089. CanTailDuplicate = false;
  1090. break;
  1091. }
  1092. }
  1093. // If we can't tail-duplicate PDom to its predecessors, then skip this
  1094. // triangle.
  1095. if (!CanTailDuplicate)
  1096. continue;
  1097. // Now we have an interesting triangle. Insert it if it's not part of an
  1098. // existing chain.
  1099. // Note: This cannot be replaced with a call insert() or emplace() because
  1100. // the find key is BB, but the insert/emplace key is PDom.
  1101. auto Found = TriangleChainMap.find(&BB);
  1102. // If it is, remove the chain from the map, grow it, and put it back in the
  1103. // map with the end as the new key.
  1104. if (Found != TriangleChainMap.end()) {
  1105. TriangleChain Chain = std::move(Found->second);
  1106. TriangleChainMap.erase(Found);
  1107. Chain.append(PDom);
  1108. TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
  1109. } else {
  1110. auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
  1111. assert(InsertResult.second && "Block seen twice.");
  1112. (void)InsertResult;
  1113. }
  1114. }
  1115. // Iterating over a DenseMap is safe here, because the only thing in the body
  1116. // of the loop is inserting into another DenseMap (ComputedEdges).
  1117. // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
  1118. for (auto &ChainPair : TriangleChainMap) {
  1119. TriangleChain &Chain = ChainPair.second;
  1120. // Benchmarking has shown that due to branch correlation duplicating 2 or
  1121. // more triangles is profitable, despite the calculations assuming
  1122. // independence.
  1123. if (Chain.count() < TriangleChainCount)
  1124. continue;
  1125. MachineBasicBlock *dst = Chain.Edges.back();
  1126. Chain.Edges.pop_back();
  1127. for (MachineBasicBlock *src : reverse(Chain.Edges)) {
  1128. LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
  1129. << getBlockName(dst)
  1130. << " as pre-computed based on triangles.\n");
  1131. auto InsertResult = ComputedEdges.insert({src, {dst, true}});
  1132. assert(InsertResult.second && "Block seen twice.");
  1133. (void)InsertResult;
  1134. dst = src;
  1135. }
  1136. }
  1137. }
  1138. // When profile is not present, return the StaticLikelyProb.
  1139. // When profile is available, we need to handle the triangle-shape CFG.
  1140. static BranchProbability getLayoutSuccessorProbThreshold(
  1141. const MachineBasicBlock *BB) {
  1142. if (!BB->getParent()->getFunction().hasProfileData())
  1143. return BranchProbability(StaticLikelyProb, 100);
  1144. if (BB->succ_size() == 2) {
  1145. const MachineBasicBlock *Succ1 = *BB->succ_begin();
  1146. const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
  1147. if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
  1148. /* See case 1 below for the cost analysis. For BB->Succ to
  1149. * be taken with smaller cost, the following needs to hold:
  1150. * Prob(BB->Succ) > 2 * Prob(BB->Pred)
  1151. * So the threshold T in the calculation below
  1152. * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
  1153. * So T / (1 - T) = 2, Yielding T = 2/3
  1154. * Also adding user specified branch bias, we have
  1155. * T = (2/3)*(ProfileLikelyProb/50)
  1156. * = (2*ProfileLikelyProb)/150)
  1157. */
  1158. return BranchProbability(2 * ProfileLikelyProb, 150);
  1159. }
  1160. }
  1161. return BranchProbability(ProfileLikelyProb, 100);
  1162. }
  1163. /// Checks to see if the layout candidate block \p Succ has a better layout
  1164. /// predecessor than \c BB. If yes, returns true.
  1165. /// \p SuccProb: The probability adjusted for only remaining blocks.
  1166. /// Only used for logging
  1167. /// \p RealSuccProb: The un-adjusted probability.
  1168. /// \p Chain: The chain that BB belongs to and Succ is being considered for.
  1169. /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
  1170. /// considered
  1171. bool MachineBlockPlacement::hasBetterLayoutPredecessor(
  1172. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  1173. const BlockChain &SuccChain, BranchProbability SuccProb,
  1174. BranchProbability RealSuccProb, const BlockChain &Chain,
  1175. const BlockFilterSet *BlockFilter) {
  1176. // There isn't a better layout when there are no unscheduled predecessors.
  1177. if (SuccChain.UnscheduledPredecessors == 0)
  1178. return false;
  1179. // There are two basic scenarios here:
  1180. // -------------------------------------
  1181. // Case 1: triangular shape CFG (if-then):
  1182. // BB
  1183. // | \
  1184. // | \
  1185. // | Pred
  1186. // | /
  1187. // Succ
  1188. // In this case, we are evaluating whether to select edge -> Succ, e.g.
  1189. // set Succ as the layout successor of BB. Picking Succ as BB's
  1190. // successor breaks the CFG constraints (FIXME: define these constraints).
  1191. // With this layout, Pred BB
  1192. // is forced to be outlined, so the overall cost will be cost of the
  1193. // branch taken from BB to Pred, plus the cost of back taken branch
  1194. // from Pred to Succ, as well as the additional cost associated
  1195. // with the needed unconditional jump instruction from Pred To Succ.
  1196. // The cost of the topological order layout is the taken branch cost
  1197. // from BB to Succ, so to make BB->Succ a viable candidate, the following
  1198. // must hold:
  1199. // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
  1200. // < freq(BB->Succ) * taken_branch_cost.
  1201. // Ignoring unconditional jump cost, we get
  1202. // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
  1203. // prob(BB->Succ) > 2 * prob(BB->Pred)
  1204. //
  1205. // When real profile data is available, we can precisely compute the
  1206. // probability threshold that is needed for edge BB->Succ to be considered.
  1207. // Without profile data, the heuristic requires the branch bias to be
  1208. // a lot larger to make sure the signal is very strong (e.g. 80% default).
  1209. // -----------------------------------------------------------------
  1210. // Case 2: diamond like CFG (if-then-else):
  1211. // S
  1212. // / \
  1213. // | \
  1214. // BB Pred
  1215. // \ /
  1216. // Succ
  1217. // ..
  1218. //
  1219. // The current block is BB and edge BB->Succ is now being evaluated.
  1220. // Note that edge S->BB was previously already selected because
  1221. // prob(S->BB) > prob(S->Pred).
  1222. // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
  1223. // choose Pred, we will have a topological ordering as shown on the left
  1224. // in the picture below. If we choose Succ, we have the solution as shown
  1225. // on the right:
  1226. //
  1227. // topo-order:
  1228. //
  1229. // S----- ---S
  1230. // | | | |
  1231. // ---BB | | BB
  1232. // | | | |
  1233. // | Pred-- | Succ--
  1234. // | | | |
  1235. // ---Succ ---Pred--
  1236. //
  1237. // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
  1238. // = freq(S->Pred) + freq(S->BB)
  1239. //
  1240. // If we have profile data (i.e, branch probabilities can be trusted), the
  1241. // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
  1242. // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
  1243. // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
  1244. // means the cost of topological order is greater.
  1245. // When profile data is not available, however, we need to be more
  1246. // conservative. If the branch prediction is wrong, breaking the topo-order
  1247. // will actually yield a layout with large cost. For this reason, we need
  1248. // strong biased branch at block S with Prob(S->BB) in order to select
  1249. // BB->Succ. This is equivalent to looking the CFG backward with backward
  1250. // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
  1251. // profile data).
  1252. // --------------------------------------------------------------------------
  1253. // Case 3: forked diamond
  1254. // S
  1255. // / \
  1256. // / \
  1257. // BB Pred
  1258. // | \ / |
  1259. // | \ / |
  1260. // | X |
  1261. // | / \ |
  1262. // | / \ |
  1263. // S1 S2
  1264. //
  1265. // The current block is BB and edge BB->S1 is now being evaluated.
  1266. // As above S->BB was already selected because
  1267. // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
  1268. //
  1269. // topo-order:
  1270. //
  1271. // S-------| ---S
  1272. // | | | |
  1273. // ---BB | | BB
  1274. // | | | |
  1275. // | Pred----| | S1----
  1276. // | | | |
  1277. // --(S1 or S2) ---Pred--
  1278. // |
  1279. // S2
  1280. //
  1281. // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
  1282. // + min(freq(Pred->S1), freq(Pred->S2))
  1283. // Non-topo-order cost:
  1284. // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
  1285. // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
  1286. // is 0. Then the non topo layout is better when
  1287. // freq(S->Pred) < freq(BB->S1).
  1288. // This is exactly what is checked below.
  1289. // Note there are other shapes that apply (Pred may not be a single block,
  1290. // but they all fit this general pattern.)
  1291. BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
  1292. // Make sure that a hot successor doesn't have a globally more
  1293. // important predecessor.
  1294. BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
  1295. bool BadCFGConflict = false;
  1296. for (MachineBasicBlock *Pred : Succ->predecessors()) {
  1297. if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
  1298. (BlockFilter && !BlockFilter->count(Pred)) ||
  1299. BlockToChain[Pred] == &Chain ||
  1300. // This check is redundant except for look ahead. This function is
  1301. // called for lookahead by isProfitableToTailDup when BB hasn't been
  1302. // placed yet.
  1303. (Pred == BB))
  1304. continue;
  1305. // Do backward checking.
  1306. // For all cases above, we need a backward checking to filter out edges that
  1307. // are not 'strongly' biased.
  1308. // BB Pred
  1309. // \ /
  1310. // Succ
  1311. // We select edge BB->Succ if
  1312. // freq(BB->Succ) > freq(Succ) * HotProb
  1313. // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
  1314. // HotProb
  1315. // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
  1316. // Case 1 is covered too, because the first equation reduces to:
  1317. // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
  1318. BlockFrequency PredEdgeFreq =
  1319. MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
  1320. if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
  1321. BadCFGConflict = true;
  1322. break;
  1323. }
  1324. }
  1325. if (BadCFGConflict) {
  1326. LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> "
  1327. << SuccProb << " (prob) (non-cold CFG conflict)\n");
  1328. return true;
  1329. }
  1330. return false;
  1331. }
  1332. /// Select the best successor for a block.
  1333. ///
  1334. /// This looks across all successors of a particular block and attempts to
  1335. /// select the "best" one to be the layout successor. It only considers direct
  1336. /// successors which also pass the block filter. It will attempt to avoid
  1337. /// breaking CFG structure, but cave and break such structures in the case of
  1338. /// very hot successor edges.
  1339. ///
  1340. /// \returns The best successor block found, or null if none are viable, along
  1341. /// with a boolean indicating if tail duplication is necessary.
  1342. MachineBlockPlacement::BlockAndTailDupResult
  1343. MachineBlockPlacement::selectBestSuccessor(
  1344. const MachineBasicBlock *BB, const BlockChain &Chain,
  1345. const BlockFilterSet *BlockFilter) {
  1346. const BranchProbability HotProb(StaticLikelyProb, 100);
  1347. BlockAndTailDupResult BestSucc = { nullptr, false };
  1348. auto BestProb = BranchProbability::getZero();
  1349. SmallVector<MachineBasicBlock *, 4> Successors;
  1350. auto AdjustedSumProb =
  1351. collectViableSuccessors(BB, Chain, BlockFilter, Successors);
  1352. LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
  1353. << "\n");
  1354. // if we already precomputed the best successor for BB, return that if still
  1355. // applicable.
  1356. auto FoundEdge = ComputedEdges.find(BB);
  1357. if (FoundEdge != ComputedEdges.end()) {
  1358. MachineBasicBlock *Succ = FoundEdge->second.BB;
  1359. ComputedEdges.erase(FoundEdge);
  1360. BlockChain *SuccChain = BlockToChain[Succ];
  1361. if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
  1362. SuccChain != &Chain && Succ == *SuccChain->begin())
  1363. return FoundEdge->second;
  1364. }
  1365. // if BB is part of a trellis, Use the trellis to determine the optimal
  1366. // fallthrough edges
  1367. if (isTrellis(BB, Successors, Chain, BlockFilter))
  1368. return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
  1369. BlockFilter);
  1370. // For blocks with CFG violations, we may be able to lay them out anyway with
  1371. // tail-duplication. We keep this vector so we can perform the probability
  1372. // calculations the minimum number of times.
  1373. SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
  1374. DupCandidates;
  1375. for (MachineBasicBlock *Succ : Successors) {
  1376. auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
  1377. BranchProbability SuccProb =
  1378. getAdjustedProbability(RealSuccProb, AdjustedSumProb);
  1379. BlockChain &SuccChain = *BlockToChain[Succ];
  1380. // Skip the edge \c BB->Succ if block \c Succ has a better layout
  1381. // predecessor that yields lower global cost.
  1382. if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
  1383. Chain, BlockFilter)) {
  1384. // If tail duplication would make Succ profitable, place it.
  1385. if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
  1386. DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
  1387. continue;
  1388. }
  1389. LLVM_DEBUG(
  1390. dbgs() << " Candidate: " << getBlockName(Succ)
  1391. << ", probability: " << SuccProb
  1392. << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
  1393. << "\n");
  1394. if (BestSucc.BB && BestProb >= SuccProb) {
  1395. LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n");
  1396. continue;
  1397. }
  1398. LLVM_DEBUG(dbgs() << " Setting it as best candidate\n");
  1399. BestSucc.BB = Succ;
  1400. BestProb = SuccProb;
  1401. }
  1402. // Handle the tail duplication candidates in order of decreasing probability.
  1403. // Stop at the first one that is profitable. Also stop if they are less
  1404. // profitable than BestSucc. Position is important because we preserve it and
  1405. // prefer first best match. Here we aren't comparing in order, so we capture
  1406. // the position instead.
  1407. llvm::stable_sort(DupCandidates,
  1408. [](std::tuple<BranchProbability, MachineBasicBlock *> L,
  1409. std::tuple<BranchProbability, MachineBasicBlock *> R) {
  1410. return std::get<0>(L) > std::get<0>(R);
  1411. });
  1412. for (auto &Tup : DupCandidates) {
  1413. BranchProbability DupProb;
  1414. MachineBasicBlock *Succ;
  1415. std::tie(DupProb, Succ) = Tup;
  1416. if (DupProb < BestProb)
  1417. break;
  1418. if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
  1419. && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
  1420. LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ)
  1421. << ", probability: " << DupProb
  1422. << " (Tail Duplicate)\n");
  1423. BestSucc.BB = Succ;
  1424. BestSucc.ShouldTailDup = true;
  1425. break;
  1426. }
  1427. }
  1428. if (BestSucc.BB)
  1429. LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
  1430. return BestSucc;
  1431. }
  1432. /// Select the best block from a worklist.
  1433. ///
  1434. /// This looks through the provided worklist as a list of candidate basic
  1435. /// blocks and select the most profitable one to place. The definition of
  1436. /// profitable only really makes sense in the context of a loop. This returns
  1437. /// the most frequently visited block in the worklist, which in the case of
  1438. /// a loop, is the one most desirable to be physically close to the rest of the
  1439. /// loop body in order to improve i-cache behavior.
  1440. ///
  1441. /// \returns The best block found, or null if none are viable.
  1442. MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
  1443. const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
  1444. // Once we need to walk the worklist looking for a candidate, cleanup the
  1445. // worklist of already placed entries.
  1446. // FIXME: If this shows up on profiles, it could be folded (at the cost of
  1447. // some code complexity) into the loop below.
  1448. WorkList.erase(llvm::remove_if(WorkList,
  1449. [&](MachineBasicBlock *BB) {
  1450. return BlockToChain.lookup(BB) == &Chain;
  1451. }),
  1452. WorkList.end());
  1453. if (WorkList.empty())
  1454. return nullptr;
  1455. bool IsEHPad = WorkList[0]->isEHPad();
  1456. MachineBasicBlock *BestBlock = nullptr;
  1457. BlockFrequency BestFreq;
  1458. for (MachineBasicBlock *MBB : WorkList) {
  1459. assert(MBB->isEHPad() == IsEHPad &&
  1460. "EHPad mismatch between block and work list.");
  1461. BlockChain &SuccChain = *BlockToChain[MBB];
  1462. if (&SuccChain == &Chain)
  1463. continue;
  1464. assert(SuccChain.UnscheduledPredecessors == 0 &&
  1465. "Found CFG-violating block");
  1466. BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
  1467. LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
  1468. MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
  1469. // For ehpad, we layout the least probable first as to avoid jumping back
  1470. // from least probable landingpads to more probable ones.
  1471. //
  1472. // FIXME: Using probability is probably (!) not the best way to achieve
  1473. // this. We should probably have a more principled approach to layout
  1474. // cleanup code.
  1475. //
  1476. // The goal is to get:
  1477. //
  1478. // +--------------------------+
  1479. // | V
  1480. // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
  1481. //
  1482. // Rather than:
  1483. //
  1484. // +-------------------------------------+
  1485. // V |
  1486. // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
  1487. if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
  1488. continue;
  1489. BestBlock = MBB;
  1490. BestFreq = CandidateFreq;
  1491. }
  1492. return BestBlock;
  1493. }
  1494. /// Retrieve the first unplaced basic block.
  1495. ///
  1496. /// This routine is called when we are unable to use the CFG to walk through
  1497. /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
  1498. /// We walk through the function's blocks in order, starting from the
  1499. /// LastUnplacedBlockIt. We update this iterator on each call to avoid
  1500. /// re-scanning the entire sequence on repeated calls to this routine.
  1501. MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
  1502. const BlockChain &PlacedChain,
  1503. MachineFunction::iterator &PrevUnplacedBlockIt,
  1504. const BlockFilterSet *BlockFilter) {
  1505. for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
  1506. ++I) {
  1507. if (BlockFilter && !BlockFilter->count(&*I))
  1508. continue;
  1509. if (BlockToChain[&*I] != &PlacedChain) {
  1510. PrevUnplacedBlockIt = I;
  1511. // Now select the head of the chain to which the unplaced block belongs
  1512. // as the block to place. This will force the entire chain to be placed,
  1513. // and satisfies the requirements of merging chains.
  1514. return *BlockToChain[&*I]->begin();
  1515. }
  1516. }
  1517. return nullptr;
  1518. }
  1519. void MachineBlockPlacement::fillWorkLists(
  1520. const MachineBasicBlock *MBB,
  1521. SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
  1522. const BlockFilterSet *BlockFilter = nullptr) {
  1523. BlockChain &Chain = *BlockToChain[MBB];
  1524. if (!UpdatedPreds.insert(&Chain).second)
  1525. return;
  1526. assert(
  1527. Chain.UnscheduledPredecessors == 0 &&
  1528. "Attempting to place block with unscheduled predecessors in worklist.");
  1529. for (MachineBasicBlock *ChainBB : Chain) {
  1530. assert(BlockToChain[ChainBB] == &Chain &&
  1531. "Block in chain doesn't match BlockToChain map.");
  1532. for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
  1533. if (BlockFilter && !BlockFilter->count(Pred))
  1534. continue;
  1535. if (BlockToChain[Pred] == &Chain)
  1536. continue;
  1537. ++Chain.UnscheduledPredecessors;
  1538. }
  1539. }
  1540. if (Chain.UnscheduledPredecessors != 0)
  1541. return;
  1542. MachineBasicBlock *BB = *Chain.begin();
  1543. if (BB->isEHPad())
  1544. EHPadWorkList.push_back(BB);
  1545. else
  1546. BlockWorkList.push_back(BB);
  1547. }
  1548. void MachineBlockPlacement::buildChain(
  1549. const MachineBasicBlock *HeadBB, BlockChain &Chain,
  1550. BlockFilterSet *BlockFilter) {
  1551. assert(HeadBB && "BB must not be null.\n");
  1552. assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
  1553. MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
  1554. const MachineBasicBlock *LoopHeaderBB = HeadBB;
  1555. markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
  1556. MachineBasicBlock *BB = *std::prev(Chain.end());
  1557. while (true) {
  1558. assert(BB && "null block found at end of chain in loop.");
  1559. assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
  1560. assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
  1561. // Look for the best viable successor if there is one to place immediately
  1562. // after this block.
  1563. auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
  1564. MachineBasicBlock* BestSucc = Result.BB;
  1565. bool ShouldTailDup = Result.ShouldTailDup;
  1566. if (allowTailDupPlacement())
  1567. ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
  1568. // If an immediate successor isn't available, look for the best viable
  1569. // block among those we've identified as not violating the loop's CFG at
  1570. // this point. This won't be a fallthrough, but it will increase locality.
  1571. if (!BestSucc)
  1572. BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
  1573. if (!BestSucc)
  1574. BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
  1575. if (!BestSucc) {
  1576. BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
  1577. if (!BestSucc)
  1578. break;
  1579. LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
  1580. "layout successor until the CFG reduces\n");
  1581. }
  1582. // Placement may have changed tail duplication opportunities.
  1583. // Check for that now.
  1584. if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
  1585. // If the chosen successor was duplicated into all its predecessors,
  1586. // don't bother laying it out, just go round the loop again with BB as
  1587. // the chain end.
  1588. if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
  1589. BlockFilter, PrevUnplacedBlockIt))
  1590. continue;
  1591. }
  1592. // Place this block, updating the datastructures to reflect its placement.
  1593. BlockChain &SuccChain = *BlockToChain[BestSucc];
  1594. // Zero out UnscheduledPredecessors for the successor we're about to merge in case
  1595. // we selected a successor that didn't fit naturally into the CFG.
  1596. SuccChain.UnscheduledPredecessors = 0;
  1597. LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
  1598. << getBlockName(BestSucc) << "\n");
  1599. markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
  1600. Chain.merge(BestSucc, &SuccChain);
  1601. BB = *std::prev(Chain.end());
  1602. }
  1603. LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
  1604. << getBlockName(*Chain.begin()) << "\n");
  1605. }
  1606. // If bottom of block BB has only one successor OldTop, in most cases it is
  1607. // profitable to move it before OldTop, except the following case:
  1608. //
  1609. // -->OldTop<-
  1610. // | . |
  1611. // | . |
  1612. // | . |
  1613. // ---Pred |
  1614. // | |
  1615. // BB-----
  1616. //
  1617. // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
  1618. // layout the other successor below it, so it can't reduce taken branch.
  1619. // In this case we keep its original layout.
  1620. bool
  1621. MachineBlockPlacement::canMoveBottomBlockToTop(
  1622. const MachineBasicBlock *BottomBlock,
  1623. const MachineBasicBlock *OldTop) {
  1624. if (BottomBlock->pred_size() != 1)
  1625. return true;
  1626. MachineBasicBlock *Pred = *BottomBlock->pred_begin();
  1627. if (Pred->succ_size() != 2)
  1628. return true;
  1629. MachineBasicBlock *OtherBB = *Pred->succ_begin();
  1630. if (OtherBB == BottomBlock)
  1631. OtherBB = *Pred->succ_rbegin();
  1632. if (OtherBB == OldTop)
  1633. return false;
  1634. return true;
  1635. }
  1636. // Find out the possible fall through frequence to the top of a loop.
  1637. BlockFrequency
  1638. MachineBlockPlacement::TopFallThroughFreq(
  1639. const MachineBasicBlock *Top,
  1640. const BlockFilterSet &LoopBlockSet) {
  1641. BlockFrequency MaxFreq = 0;
  1642. for (MachineBasicBlock *Pred : Top->predecessors()) {
  1643. BlockChain *PredChain = BlockToChain[Pred];
  1644. if (!LoopBlockSet.count(Pred) &&
  1645. (!PredChain || Pred == *std::prev(PredChain->end()))) {
  1646. // Found a Pred block can be placed before Top.
  1647. // Check if Top is the best successor of Pred.
  1648. auto TopProb = MBPI->getEdgeProbability(Pred, Top);
  1649. bool TopOK = true;
  1650. for (MachineBasicBlock *Succ : Pred->successors()) {
  1651. auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
  1652. BlockChain *SuccChain = BlockToChain[Succ];
  1653. // Check if Succ can be placed after Pred.
  1654. // Succ should not be in any chain, or it is the head of some chain.
  1655. if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
  1656. (!SuccChain || Succ == *SuccChain->begin())) {
  1657. TopOK = false;
  1658. break;
  1659. }
  1660. }
  1661. if (TopOK) {
  1662. BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
  1663. MBPI->getEdgeProbability(Pred, Top);
  1664. if (EdgeFreq > MaxFreq)
  1665. MaxFreq = EdgeFreq;
  1666. }
  1667. }
  1668. }
  1669. return MaxFreq;
  1670. }
  1671. // Compute the fall through gains when move NewTop before OldTop.
  1672. //
  1673. // In following diagram, edges marked as "-" are reduced fallthrough, edges
  1674. // marked as "+" are increased fallthrough, this function computes
  1675. //
  1676. // SUM(increased fallthrough) - SUM(decreased fallthrough)
  1677. //
  1678. // |
  1679. // | -
  1680. // V
  1681. // --->OldTop
  1682. // | .
  1683. // | .
  1684. // +| . +
  1685. // | Pred --->
  1686. // | |-
  1687. // | V
  1688. // --- NewTop <---
  1689. // |-
  1690. // V
  1691. //
  1692. BlockFrequency
  1693. MachineBlockPlacement::FallThroughGains(
  1694. const MachineBasicBlock *NewTop,
  1695. const MachineBasicBlock *OldTop,
  1696. const MachineBasicBlock *ExitBB,
  1697. const BlockFilterSet &LoopBlockSet) {
  1698. BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
  1699. BlockFrequency FallThrough2Exit = 0;
  1700. if (ExitBB)
  1701. FallThrough2Exit = MBFI->getBlockFreq(NewTop) *
  1702. MBPI->getEdgeProbability(NewTop, ExitBB);
  1703. BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) *
  1704. MBPI->getEdgeProbability(NewTop, OldTop);
  1705. // Find the best Pred of NewTop.
  1706. MachineBasicBlock *BestPred = nullptr;
  1707. BlockFrequency FallThroughFromPred = 0;
  1708. for (MachineBasicBlock *Pred : NewTop->predecessors()) {
  1709. if (!LoopBlockSet.count(Pred))
  1710. continue;
  1711. BlockChain *PredChain = BlockToChain[Pred];
  1712. if (!PredChain || Pred == *std::prev(PredChain->end())) {
  1713. BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
  1714. MBPI->getEdgeProbability(Pred, NewTop);
  1715. if (EdgeFreq > FallThroughFromPred) {
  1716. FallThroughFromPred = EdgeFreq;
  1717. BestPred = Pred;
  1718. }
  1719. }
  1720. }
  1721. // If NewTop is not placed after Pred, another successor can be placed
  1722. // after Pred.
  1723. BlockFrequency NewFreq = 0;
  1724. if (BestPred) {
  1725. for (MachineBasicBlock *Succ : BestPred->successors()) {
  1726. if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
  1727. continue;
  1728. if (ComputedEdges.find(Succ) != ComputedEdges.end())
  1729. continue;
  1730. BlockChain *SuccChain = BlockToChain[Succ];
  1731. if ((SuccChain && (Succ != *SuccChain->begin())) ||
  1732. (SuccChain == BlockToChain[BestPred]))
  1733. continue;
  1734. BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
  1735. MBPI->getEdgeProbability(BestPred, Succ);
  1736. if (EdgeFreq > NewFreq)
  1737. NewFreq = EdgeFreq;
  1738. }
  1739. BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
  1740. MBPI->getEdgeProbability(BestPred, NewTop);
  1741. if (NewFreq > OrigEdgeFreq) {
  1742. // If NewTop is not the best successor of Pred, then Pred doesn't
  1743. // fallthrough to NewTop. So there is no FallThroughFromPred and
  1744. // NewFreq.
  1745. NewFreq = 0;
  1746. FallThroughFromPred = 0;
  1747. }
  1748. }
  1749. BlockFrequency Result = 0;
  1750. BlockFrequency Gains = BackEdgeFreq + NewFreq;
  1751. BlockFrequency Lost = FallThrough2Top + FallThrough2Exit +
  1752. FallThroughFromPred;
  1753. if (Gains > Lost)
  1754. Result = Gains - Lost;
  1755. return Result;
  1756. }
  1757. /// Helper function of findBestLoopTop. Find the best loop top block
  1758. /// from predecessors of old top.
  1759. ///
  1760. /// Look for a block which is strictly better than the old top for laying
  1761. /// out before the old top of the loop. This looks for only two patterns:
  1762. ///
  1763. /// 1. a block has only one successor, the old loop top
  1764. ///
  1765. /// Because such a block will always result in an unconditional jump,
  1766. /// rotating it in front of the old top is always profitable.
  1767. ///
  1768. /// 2. a block has two successors, one is old top, another is exit
  1769. /// and it has more than one predecessors
  1770. ///
  1771. /// If it is below one of its predecessors P, only P can fall through to
  1772. /// it, all other predecessors need a jump to it, and another conditional
  1773. /// jump to loop header. If it is moved before loop header, all its
  1774. /// predecessors jump to it, then fall through to loop header. So all its
  1775. /// predecessors except P can reduce one taken branch.
  1776. /// At the same time, move it before old top increases the taken branch
  1777. /// to loop exit block, so the reduced taken branch will be compared with
  1778. /// the increased taken branch to the loop exit block.
  1779. ///
  1780. /// This pattern is enabled only when PlainMode is false.
  1781. MachineBasicBlock *
  1782. MachineBlockPlacement::findBestLoopTopHelper(
  1783. MachineBasicBlock *OldTop,
  1784. const MachineLoop &L,
  1785. const BlockFilterSet &LoopBlockSet,
  1786. bool HasStaticProfileOnly) {
  1787. // Check that the header hasn't been fused with a preheader block due to
  1788. // crazy branches. If it has, we need to start with the header at the top to
  1789. // prevent pulling the preheader into the loop body.
  1790. BlockChain &HeaderChain = *BlockToChain[OldTop];
  1791. if (!LoopBlockSet.count(*HeaderChain.begin()))
  1792. return OldTop;
  1793. LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop)
  1794. << "\n");
  1795. BlockFrequency BestGains = 0;
  1796. MachineBasicBlock *BestPred = nullptr;
  1797. for (MachineBasicBlock *Pred : OldTop->predecessors()) {
  1798. if (!LoopBlockSet.count(Pred))
  1799. continue;
  1800. if (Pred == L.getHeader())
  1801. continue;
  1802. LLVM_DEBUG(dbgs() << " old top pred: " << getBlockName(Pred) << ", has "
  1803. << Pred->succ_size() << " successors, ";
  1804. MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
  1805. if (Pred->succ_size() > 2)
  1806. continue;
  1807. if (!canMoveBottomBlockToTop(Pred, OldTop))
  1808. continue;
  1809. if (HasStaticProfileOnly) {
  1810. // In plain mode we consider pattern 1 only.
  1811. if (Pred->succ_size() > 1)
  1812. continue;
  1813. BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
  1814. if (!BestPred || PredFreq > BestGains ||
  1815. (!(PredFreq < BestGains) &&
  1816. Pred->isLayoutSuccessor(OldTop))) {
  1817. BestPred = Pred;
  1818. BestGains = PredFreq;
  1819. }
  1820. } else {
  1821. // With profile information we also consider pattern 2.
  1822. MachineBasicBlock *OtherBB = nullptr;
  1823. if (Pred->succ_size() == 2) {
  1824. OtherBB = *Pred->succ_begin();
  1825. if (OtherBB == OldTop)
  1826. OtherBB = *Pred->succ_rbegin();
  1827. }
  1828. // And more sophisticated cost model.
  1829. BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB,
  1830. LoopBlockSet);
  1831. if ((Gains > 0) && (Gains > BestGains ||
  1832. ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) {
  1833. BestPred = Pred;
  1834. BestGains = Gains;
  1835. }
  1836. }
  1837. }
  1838. // If no direct predecessor is fine, just use the loop header.
  1839. if (!BestPred) {
  1840. LLVM_DEBUG(dbgs() << " final top unchanged\n");
  1841. return OldTop;
  1842. }
  1843. // Walk backwards through any straight line of predecessors.
  1844. while (BestPred->pred_size() == 1 &&
  1845. (*BestPred->pred_begin())->succ_size() == 1 &&
  1846. *BestPred->pred_begin() != L.getHeader())
  1847. BestPred = *BestPred->pred_begin();
  1848. LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
  1849. return BestPred;
  1850. }
  1851. /// Find the best loop top block for layout in FDO mode.
  1852. ///
  1853. /// This function iteratively calls findBestLoopTopHelper, until no new better
  1854. /// BB can be found.
  1855. MachineBasicBlock *
  1856. MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
  1857. const BlockFilterSet &LoopBlockSet) {
  1858. // Placing the latch block before the header may introduce an extra branch
  1859. // that skips this block the first time the loop is executed, which we want
  1860. // to avoid when optimising for size.
  1861. // FIXME: in theory there is a case that does not introduce a new branch,
  1862. // i.e. when the layout predecessor does not fallthrough to the loop header.
  1863. // In practice this never happens though: there always seems to be a preheader
  1864. // that can fallthrough and that is also placed before the header.
  1865. if (F->getFunction().hasOptSize())
  1866. return L.getHeader();
  1867. MachineBasicBlock *OldTop = nullptr;
  1868. MachineBasicBlock *NewTop = L.getHeader();
  1869. while (NewTop != OldTop) {
  1870. OldTop = NewTop;
  1871. NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
  1872. if (NewTop != OldTop)
  1873. ComputedEdges[NewTop] = { OldTop, false };
  1874. }
  1875. return NewTop;
  1876. }
  1877. /// Find the best loop top block for layout in plain mode. It is less agressive
  1878. /// than findBestLoopTop.
  1879. ///
  1880. /// Look for a block which is strictly better than the loop header for laying
  1881. /// out at the top of the loop. This looks for one and only one pattern:
  1882. /// a latch block with no conditional exit. This block will cause a conditional
  1883. /// jump around it or will be the bottom of the loop if we lay it out in place,
  1884. /// but if it doesn't end up at the bottom of the loop for any reason,
  1885. /// rotation alone won't fix it. Because such a block will always result in an
  1886. /// unconditional jump (for the backedge) rotating it in front of the loop
  1887. /// header is always profitable.
  1888. MachineBasicBlock *
  1889. MachineBlockPlacement::findBestLoopTopNoProfile(
  1890. const MachineLoop &L,
  1891. const BlockFilterSet &LoopBlockSet) {
  1892. // Placing the latch block before the header may introduce an extra branch
  1893. // that skips this block the first time the loop is executed, which we want
  1894. // to avoid when optimising for size.
  1895. // FIXME: in theory there is a case that does not introduce a new branch,
  1896. // i.e. when the layout predecessor does not fallthrough to the loop header.
  1897. // In practice this never happens though: there always seems to be a preheader
  1898. // that can fallthrough and that is also placed before the header.
  1899. if (F->getFunction().hasOptSize())
  1900. return L.getHeader();
  1901. return findBestLoopTopHelper(L.getHeader(), L, LoopBlockSet, true);
  1902. }
  1903. /// Find the best loop exiting block for layout.
  1904. ///
  1905. /// This routine implements the logic to analyze the loop looking for the best
  1906. /// block to layout at the top of the loop. Typically this is done to maximize
  1907. /// fallthrough opportunities.
  1908. MachineBasicBlock *
  1909. MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
  1910. const BlockFilterSet &LoopBlockSet) {
  1911. // We don't want to layout the loop linearly in all cases. If the loop header
  1912. // is just a normal basic block in the loop, we want to look for what block
  1913. // within the loop is the best one to layout at the top. However, if the loop
  1914. // header has be pre-merged into a chain due to predecessors not having
  1915. // analyzable branches, *and* the predecessor it is merged with is *not* part
  1916. // of the loop, rotating the header into the middle of the loop will create
  1917. // a non-contiguous range of blocks which is Very Bad. So start with the
  1918. // header and only rotate if safe.
  1919. BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
  1920. if (!LoopBlockSet.count(*HeaderChain.begin()))
  1921. return nullptr;
  1922. BlockFrequency BestExitEdgeFreq;
  1923. unsigned BestExitLoopDepth = 0;
  1924. MachineBasicBlock *ExitingBB = nullptr;
  1925. // If there are exits to outer loops, loop rotation can severely limit
  1926. // fallthrough opportunities unless it selects such an exit. Keep a set of
  1927. // blocks where rotating to exit with that block will reach an outer loop.
  1928. SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
  1929. LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
  1930. << getBlockName(L.getHeader()) << "\n");
  1931. for (MachineBasicBlock *MBB : L.getBlocks()) {
  1932. BlockChain &Chain = *BlockToChain[MBB];
  1933. // Ensure that this block is at the end of a chain; otherwise it could be
  1934. // mid-way through an inner loop or a successor of an unanalyzable branch.
  1935. if (MBB != *std::prev(Chain.end()))
  1936. continue;
  1937. // Now walk the successors. We need to establish whether this has a viable
  1938. // exiting successor and whether it has a viable non-exiting successor.
  1939. // We store the old exiting state and restore it if a viable looping
  1940. // successor isn't found.
  1941. MachineBasicBlock *OldExitingBB = ExitingBB;
  1942. BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
  1943. bool HasLoopingSucc = false;
  1944. for (MachineBasicBlock *Succ : MBB->successors()) {
  1945. if (Succ->isEHPad())
  1946. continue;
  1947. if (Succ == MBB)
  1948. continue;
  1949. BlockChain &SuccChain = *BlockToChain[Succ];
  1950. // Don't split chains, either this chain or the successor's chain.
  1951. if (&Chain == &SuccChain) {
  1952. LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
  1953. << getBlockName(Succ) << " (chain conflict)\n");
  1954. continue;
  1955. }
  1956. auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
  1957. if (LoopBlockSet.count(Succ)) {
  1958. LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
  1959. << getBlockName(Succ) << " (" << SuccProb << ")\n");
  1960. HasLoopingSucc = true;
  1961. continue;
  1962. }
  1963. unsigned SuccLoopDepth = 0;
  1964. if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
  1965. SuccLoopDepth = ExitLoop->getLoopDepth();
  1966. if (ExitLoop->contains(&L))
  1967. BlocksExitingToOuterLoop.insert(MBB);
  1968. }
  1969. BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
  1970. LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
  1971. << getBlockName(Succ) << " [L:" << SuccLoopDepth
  1972. << "] (";
  1973. MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
  1974. // Note that we bias this toward an existing layout successor to retain
  1975. // incoming order in the absence of better information. The exit must have
  1976. // a frequency higher than the current exit before we consider breaking
  1977. // the layout.
  1978. BranchProbability Bias(100 - ExitBlockBias, 100);
  1979. if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
  1980. ExitEdgeFreq > BestExitEdgeFreq ||
  1981. (MBB->isLayoutSuccessor(Succ) &&
  1982. !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
  1983. BestExitEdgeFreq = ExitEdgeFreq;
  1984. ExitingBB = MBB;
  1985. }
  1986. }
  1987. if (!HasLoopingSucc) {
  1988. // Restore the old exiting state, no viable looping successor was found.
  1989. ExitingBB = OldExitingBB;
  1990. BestExitEdgeFreq = OldBestExitEdgeFreq;
  1991. }
  1992. }
  1993. // Without a candidate exiting block or with only a single block in the
  1994. // loop, just use the loop header to layout the loop.
  1995. if (!ExitingBB) {
  1996. LLVM_DEBUG(
  1997. dbgs() << " No other candidate exit blocks, using loop header\n");
  1998. return nullptr;
  1999. }
  2000. if (L.getNumBlocks() == 1) {
  2001. LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
  2002. return nullptr;
  2003. }
  2004. // Also, if we have exit blocks which lead to outer loops but didn't select
  2005. // one of them as the exiting block we are rotating toward, disable loop
  2006. // rotation altogether.
  2007. if (!BlocksExitingToOuterLoop.empty() &&
  2008. !BlocksExitingToOuterLoop.count(ExitingBB))
  2009. return nullptr;
  2010. LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB)
  2011. << "\n");
  2012. return ExitingBB;
  2013. }
  2014. /// Check if there is a fallthrough to loop header Top.
  2015. ///
  2016. /// 1. Look for a Pred that can be layout before Top.
  2017. /// 2. Check if Top is the most possible successor of Pred.
  2018. bool
  2019. MachineBlockPlacement::hasViableTopFallthrough(
  2020. const MachineBasicBlock *Top,
  2021. const BlockFilterSet &LoopBlockSet) {
  2022. for (MachineBasicBlock *Pred : Top->predecessors()) {
  2023. BlockChain *PredChain = BlockToChain[Pred];
  2024. if (!LoopBlockSet.count(Pred) &&
  2025. (!PredChain || Pred == *std::prev(PredChain->end()))) {
  2026. // Found a Pred block can be placed before Top.
  2027. // Check if Top is the best successor of Pred.
  2028. auto TopProb = MBPI->getEdgeProbability(Pred, Top);
  2029. bool TopOK = true;
  2030. for (MachineBasicBlock *Succ : Pred->successors()) {
  2031. auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
  2032. BlockChain *SuccChain = BlockToChain[Succ];
  2033. // Check if Succ can be placed after Pred.
  2034. // Succ should not be in any chain, or it is the head of some chain.
  2035. if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
  2036. TopOK = false;
  2037. break;
  2038. }
  2039. }
  2040. if (TopOK)
  2041. return true;
  2042. }
  2043. }
  2044. return false;
  2045. }
  2046. /// Attempt to rotate an exiting block to the bottom of the loop.
  2047. ///
  2048. /// Once we have built a chain, try to rotate it to line up the hot exit block
  2049. /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
  2050. /// branches. For example, if the loop has fallthrough into its header and out
  2051. /// of its bottom already, don't rotate it.
  2052. void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
  2053. const MachineBasicBlock *ExitingBB,
  2054. const BlockFilterSet &LoopBlockSet) {
  2055. if (!ExitingBB)
  2056. return;
  2057. MachineBasicBlock *Top = *LoopChain.begin();
  2058. MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
  2059. // If ExitingBB is already the last one in a chain then nothing to do.
  2060. if (Bottom == ExitingBB)
  2061. return;
  2062. bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
  2063. // If the header has viable fallthrough, check whether the current loop
  2064. // bottom is a viable exiting block. If so, bail out as rotating will
  2065. // introduce an unnecessary branch.
  2066. if (ViableTopFallthrough) {
  2067. for (MachineBasicBlock *Succ : Bottom->successors()) {
  2068. BlockChain *SuccChain = BlockToChain[Succ];
  2069. if (!LoopBlockSet.count(Succ) &&
  2070. (!SuccChain || Succ == *SuccChain->begin()))
  2071. return;
  2072. }
  2073. }
  2074. BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
  2075. if (ExitIt == LoopChain.end())
  2076. return;
  2077. // Rotating a loop exit to the bottom when there is a fallthrough to top
  2078. // trades the entry fallthrough for an exit fallthrough.
  2079. // If there is no bottom->top edge, but the chosen exit block does have
  2080. // a fallthrough, we break that fallthrough for nothing in return.
  2081. // Let's consider an example. We have a built chain of basic blocks
  2082. // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
  2083. // By doing a rotation we get
  2084. // Bk+1, ..., Bn, B1, ..., Bk
  2085. // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
  2086. // If we had a fallthrough Bk -> Bk+1 it is broken now.
  2087. // It might be compensated by fallthrough Bn -> B1.
  2088. // So we have a condition to avoid creation of extra branch by loop rotation.
  2089. // All below must be true to avoid loop rotation:
  2090. // If there is a fallthrough to top (B1)
  2091. // There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
  2092. // There is no fallthrough from bottom (Bn) to top (B1).
  2093. // Please note that there is no exit fallthrough from Bn because we checked it
  2094. // above.
  2095. if (ViableTopFallthrough) {
  2096. assert(std::next(ExitIt) != LoopChain.end() &&
  2097. "Exit should not be last BB");
  2098. MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
  2099. if (ExitingBB->isSuccessor(NextBlockInChain))
  2100. if (!Bottom->isSuccessor(Top))
  2101. return;
  2102. }
  2103. LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
  2104. << " at bottom\n");
  2105. std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
  2106. }
  2107. /// Attempt to rotate a loop based on profile data to reduce branch cost.
  2108. ///
  2109. /// With profile data, we can determine the cost in terms of missed fall through
  2110. /// opportunities when rotating a loop chain and select the best rotation.
  2111. /// Basically, there are three kinds of cost to consider for each rotation:
  2112. /// 1. The possibly missed fall through edge (if it exists) from BB out of
  2113. /// the loop to the loop header.
  2114. /// 2. The possibly missed fall through edges (if they exist) from the loop
  2115. /// exits to BB out of the loop.
  2116. /// 3. The missed fall through edge (if it exists) from the last BB to the
  2117. /// first BB in the loop chain.
  2118. /// Therefore, the cost for a given rotation is the sum of costs listed above.
  2119. /// We select the best rotation with the smallest cost.
  2120. void MachineBlockPlacement::rotateLoopWithProfile(
  2121. BlockChain &LoopChain, const MachineLoop &L,
  2122. const BlockFilterSet &LoopBlockSet) {
  2123. auto RotationPos = LoopChain.end();
  2124. BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
  2125. // A utility lambda that scales up a block frequency by dividing it by a
  2126. // branch probability which is the reciprocal of the scale.
  2127. auto ScaleBlockFrequency = [](BlockFrequency Freq,
  2128. unsigned Scale) -> BlockFrequency {
  2129. if (Scale == 0)
  2130. return 0;
  2131. // Use operator / between BlockFrequency and BranchProbability to implement
  2132. // saturating multiplication.
  2133. return Freq / BranchProbability(1, Scale);
  2134. };
  2135. // Compute the cost of the missed fall-through edge to the loop header if the
  2136. // chain head is not the loop header. As we only consider natural loops with
  2137. // single header, this computation can be done only once.
  2138. BlockFrequency HeaderFallThroughCost(0);
  2139. MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
  2140. for (auto *Pred : ChainHeaderBB->predecessors()) {
  2141. BlockChain *PredChain = BlockToChain[Pred];
  2142. if (!LoopBlockSet.count(Pred) &&
  2143. (!PredChain || Pred == *std::prev(PredChain->end()))) {
  2144. auto EdgeFreq = MBFI->getBlockFreq(Pred) *
  2145. MBPI->getEdgeProbability(Pred, ChainHeaderBB);
  2146. auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
  2147. // If the predecessor has only an unconditional jump to the header, we
  2148. // need to consider the cost of this jump.
  2149. if (Pred->succ_size() == 1)
  2150. FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
  2151. HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
  2152. }
  2153. }
  2154. // Here we collect all exit blocks in the loop, and for each exit we find out
  2155. // its hottest exit edge. For each loop rotation, we define the loop exit cost
  2156. // as the sum of frequencies of exit edges we collect here, excluding the exit
  2157. // edge from the tail of the loop chain.
  2158. SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
  2159. for (auto BB : LoopChain) {
  2160. auto LargestExitEdgeProb = BranchProbability::getZero();
  2161. for (auto *Succ : BB->successors()) {
  2162. BlockChain *SuccChain = BlockToChain[Succ];
  2163. if (!LoopBlockSet.count(Succ) &&
  2164. (!SuccChain || Succ == *SuccChain->begin())) {
  2165. auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
  2166. LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
  2167. }
  2168. }
  2169. if (LargestExitEdgeProb > BranchProbability::getZero()) {
  2170. auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
  2171. ExitsWithFreq.emplace_back(BB, ExitFreq);
  2172. }
  2173. }
  2174. // In this loop we iterate every block in the loop chain and calculate the
  2175. // cost assuming the block is the head of the loop chain. When the loop ends,
  2176. // we should have found the best candidate as the loop chain's head.
  2177. for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
  2178. EndIter = LoopChain.end();
  2179. Iter != EndIter; Iter++, TailIter++) {
  2180. // TailIter is used to track the tail of the loop chain if the block we are
  2181. // checking (pointed by Iter) is the head of the chain.
  2182. if (TailIter == LoopChain.end())
  2183. TailIter = LoopChain.begin();
  2184. auto TailBB = *TailIter;
  2185. // Calculate the cost by putting this BB to the top.
  2186. BlockFrequency Cost = 0;
  2187. // If the current BB is the loop header, we need to take into account the
  2188. // cost of the missed fall through edge from outside of the loop to the
  2189. // header.
  2190. if (Iter != LoopChain.begin())
  2191. Cost += HeaderFallThroughCost;
  2192. // Collect the loop exit cost by summing up frequencies of all exit edges
  2193. // except the one from the chain tail.
  2194. for (auto &ExitWithFreq : ExitsWithFreq)
  2195. if (TailBB != ExitWithFreq.first)
  2196. Cost += ExitWithFreq.second;
  2197. // The cost of breaking the once fall-through edge from the tail to the top
  2198. // of the loop chain. Here we need to consider three cases:
  2199. // 1. If the tail node has only one successor, then we will get an
  2200. // additional jmp instruction. So the cost here is (MisfetchCost +
  2201. // JumpInstCost) * tail node frequency.
  2202. // 2. If the tail node has two successors, then we may still get an
  2203. // additional jmp instruction if the layout successor after the loop
  2204. // chain is not its CFG successor. Note that the more frequently executed
  2205. // jmp instruction will be put ahead of the other one. Assume the
  2206. // frequency of those two branches are x and y, where x is the frequency
  2207. // of the edge to the chain head, then the cost will be
  2208. // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
  2209. // 3. If the tail node has more than two successors (this rarely happens),
  2210. // we won't consider any additional cost.
  2211. if (TailBB->isSuccessor(*Iter)) {
  2212. auto TailBBFreq = MBFI->getBlockFreq(TailBB);
  2213. if (TailBB->succ_size() == 1)
  2214. Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
  2215. MisfetchCost + JumpInstCost);
  2216. else if (TailBB->succ_size() == 2) {
  2217. auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
  2218. auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
  2219. auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
  2220. ? TailBBFreq * TailToHeadProb.getCompl()
  2221. : TailToHeadFreq;
  2222. Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
  2223. ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
  2224. }
  2225. }
  2226. LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
  2227. << getBlockName(*Iter)
  2228. << " to the top: " << Cost.getFrequency() << "\n");
  2229. if (Cost < SmallestRotationCost) {
  2230. SmallestRotationCost = Cost;
  2231. RotationPos = Iter;
  2232. }
  2233. }
  2234. if (RotationPos != LoopChain.end()) {
  2235. LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
  2236. << " to the top\n");
  2237. std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
  2238. }
  2239. }
  2240. /// Collect blocks in the given loop that are to be placed.
  2241. ///
  2242. /// When profile data is available, exclude cold blocks from the returned set;
  2243. /// otherwise, collect all blocks in the loop.
  2244. MachineBlockPlacement::BlockFilterSet
  2245. MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
  2246. BlockFilterSet LoopBlockSet;
  2247. // Filter cold blocks off from LoopBlockSet when profile data is available.
  2248. // Collect the sum of frequencies of incoming edges to the loop header from
  2249. // outside. If we treat the loop as a super block, this is the frequency of
  2250. // the loop. Then for each block in the loop, we calculate the ratio between
  2251. // its frequency and the frequency of the loop block. When it is too small,
  2252. // don't add it to the loop chain. If there are outer loops, then this block
  2253. // will be merged into the first outer loop chain for which this block is not
  2254. // cold anymore. This needs precise profile data and we only do this when
  2255. // profile data is available.
  2256. if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
  2257. BlockFrequency LoopFreq(0);
  2258. for (auto LoopPred : L.getHeader()->predecessors())
  2259. if (!L.contains(LoopPred))
  2260. LoopFreq += MBFI->getBlockFreq(LoopPred) *
  2261. MBPI->getEdgeProbability(LoopPred, L.getHeader());
  2262. for (MachineBasicBlock *LoopBB : L.getBlocks()) {
  2263. auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
  2264. if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
  2265. continue;
  2266. LoopBlockSet.insert(LoopBB);
  2267. }
  2268. } else
  2269. LoopBlockSet.insert(L.block_begin(), L.block_end());
  2270. return LoopBlockSet;
  2271. }
  2272. /// Forms basic block chains from the natural loop structures.
  2273. ///
  2274. /// These chains are designed to preserve the existing *structure* of the code
  2275. /// as much as possible. We can then stitch the chains together in a way which
  2276. /// both preserves the topological structure and minimizes taken conditional
  2277. /// branches.
  2278. void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
  2279. // First recurse through any nested loops, building chains for those inner
  2280. // loops.
  2281. for (const MachineLoop *InnerLoop : L)
  2282. buildLoopChains(*InnerLoop);
  2283. assert(BlockWorkList.empty() &&
  2284. "BlockWorkList not empty when starting to build loop chains.");
  2285. assert(EHPadWorkList.empty() &&
  2286. "EHPadWorkList not empty when starting to build loop chains.");
  2287. BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
  2288. // Check if we have profile data for this function. If yes, we will rotate
  2289. // this loop by modeling costs more precisely which requires the profile data
  2290. // for better layout.
  2291. bool RotateLoopWithProfile =
  2292. ForcePreciseRotationCost ||
  2293. (PreciseRotationCost && F->getFunction().hasProfileData());
  2294. // First check to see if there is an obviously preferable top block for the
  2295. // loop. This will default to the header, but may end up as one of the
  2296. // predecessors to the header if there is one which will result in strictly
  2297. // fewer branches in the loop body.
  2298. MachineBasicBlock *LoopTop =
  2299. (RotateLoopWithProfile || F->getFunction().hasProfileData()) ?
  2300. findBestLoopTop(L, LoopBlockSet) :
  2301. findBestLoopTopNoProfile(L, LoopBlockSet);
  2302. // If we selected just the header for the loop top, look for a potentially
  2303. // profitable exit block in the event that rotating the loop can eliminate
  2304. // branches by placing an exit edge at the bottom.
  2305. //
  2306. // Loops are processed innermost to uttermost, make sure we clear
  2307. // PreferredLoopExit before processing a new loop.
  2308. PreferredLoopExit = nullptr;
  2309. if (!RotateLoopWithProfile && LoopTop == L.getHeader())
  2310. PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
  2311. BlockChain &LoopChain = *BlockToChain[LoopTop];
  2312. // FIXME: This is a really lame way of walking the chains in the loop: we
  2313. // walk the blocks, and use a set to prevent visiting a particular chain
  2314. // twice.
  2315. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  2316. assert(LoopChain.UnscheduledPredecessors == 0 &&
  2317. "LoopChain should not have unscheduled predecessors.");
  2318. UpdatedPreds.insert(&LoopChain);
  2319. for (const MachineBasicBlock *LoopBB : LoopBlockSet)
  2320. fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
  2321. buildChain(LoopTop, LoopChain, &LoopBlockSet);
  2322. if (RotateLoopWithProfile) {
  2323. if (LoopTop == L.getHeader())
  2324. rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
  2325. } else
  2326. rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
  2327. LLVM_DEBUG({
  2328. // Crash at the end so we get all of the debugging output first.
  2329. bool BadLoop = false;
  2330. if (LoopChain.UnscheduledPredecessors) {
  2331. BadLoop = true;
  2332. dbgs() << "Loop chain contains a block without its preds placed!\n"
  2333. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  2334. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
  2335. }
  2336. for (MachineBasicBlock *ChainBB : LoopChain) {
  2337. dbgs() << " ... " << getBlockName(ChainBB) << "\n";
  2338. if (!LoopBlockSet.remove(ChainBB)) {
  2339. // We don't mark the loop as bad here because there are real situations
  2340. // where this can occur. For example, with an unanalyzable fallthrough
  2341. // from a loop block to a non-loop block or vice versa.
  2342. dbgs() << "Loop chain contains a block not contained by the loop!\n"
  2343. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  2344. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  2345. << " Bad block: " << getBlockName(ChainBB) << "\n";
  2346. }
  2347. }
  2348. if (!LoopBlockSet.empty()) {
  2349. BadLoop = true;
  2350. for (const MachineBasicBlock *LoopBB : LoopBlockSet)
  2351. dbgs() << "Loop contains blocks never placed into a chain!\n"
  2352. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  2353. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  2354. << " Bad block: " << getBlockName(LoopBB) << "\n";
  2355. }
  2356. assert(!BadLoop && "Detected problems with the placement of this loop.");
  2357. });
  2358. BlockWorkList.clear();
  2359. EHPadWorkList.clear();
  2360. }
  2361. void MachineBlockPlacement::buildCFGChains() {
  2362. // Ensure that every BB in the function has an associated chain to simplify
  2363. // the assumptions of the remaining algorithm.
  2364. SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
  2365. for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
  2366. ++FI) {
  2367. MachineBasicBlock *BB = &*FI;
  2368. BlockChain *Chain =
  2369. new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
  2370. // Also, merge any blocks which we cannot reason about and must preserve
  2371. // the exact fallthrough behavior for.
  2372. while (true) {
  2373. Cond.clear();
  2374. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  2375. if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
  2376. break;
  2377. MachineFunction::iterator NextFI = std::next(FI);
  2378. MachineBasicBlock *NextBB = &*NextFI;
  2379. // Ensure that the layout successor is a viable block, as we know that
  2380. // fallthrough is a possibility.
  2381. assert(NextFI != FE && "Can't fallthrough past the last block.");
  2382. LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
  2383. << getBlockName(BB) << " -> " << getBlockName(NextBB)
  2384. << "\n");
  2385. Chain->merge(NextBB, nullptr);
  2386. #ifndef NDEBUG
  2387. BlocksWithUnanalyzableExits.insert(&*BB);
  2388. #endif
  2389. FI = NextFI;
  2390. BB = NextBB;
  2391. }
  2392. }
  2393. // Build any loop-based chains.
  2394. PreferredLoopExit = nullptr;
  2395. for (MachineLoop *L : *MLI)
  2396. buildLoopChains(*L);
  2397. assert(BlockWorkList.empty() &&
  2398. "BlockWorkList should be empty before building final chain.");
  2399. assert(EHPadWorkList.empty() &&
  2400. "EHPadWorkList should be empty before building final chain.");
  2401. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  2402. for (MachineBasicBlock &MBB : *F)
  2403. fillWorkLists(&MBB, UpdatedPreds);
  2404. BlockChain &FunctionChain = *BlockToChain[&F->front()];
  2405. buildChain(&F->front(), FunctionChain);
  2406. #ifndef NDEBUG
  2407. using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
  2408. #endif
  2409. LLVM_DEBUG({
  2410. // Crash at the end so we get all of the debugging output first.
  2411. bool BadFunc = false;
  2412. FunctionBlockSetType FunctionBlockSet;
  2413. for (MachineBasicBlock &MBB : *F)
  2414. FunctionBlockSet.insert(&MBB);
  2415. for (MachineBasicBlock *ChainBB : FunctionChain)
  2416. if (!FunctionBlockSet.erase(ChainBB)) {
  2417. BadFunc = true;
  2418. dbgs() << "Function chain contains a block not in the function!\n"
  2419. << " Bad block: " << getBlockName(ChainBB) << "\n";
  2420. }
  2421. if (!FunctionBlockSet.empty()) {
  2422. BadFunc = true;
  2423. for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
  2424. dbgs() << "Function contains blocks never placed into a chain!\n"
  2425. << " Bad block: " << getBlockName(RemainingBB) << "\n";
  2426. }
  2427. assert(!BadFunc && "Detected problems with the block placement.");
  2428. });
  2429. // Splice the blocks into place.
  2430. MachineFunction::iterator InsertPos = F->begin();
  2431. LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
  2432. for (MachineBasicBlock *ChainBB : FunctionChain) {
  2433. LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
  2434. : " ... ")
  2435. << getBlockName(ChainBB) << "\n");
  2436. if (InsertPos != MachineFunction::iterator(ChainBB))
  2437. F->splice(InsertPos, ChainBB);
  2438. else
  2439. ++InsertPos;
  2440. // Update the terminator of the previous block.
  2441. if (ChainBB == *FunctionChain.begin())
  2442. continue;
  2443. MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
  2444. // FIXME: It would be awesome of updateTerminator would just return rather
  2445. // than assert when the branch cannot be analyzed in order to remove this
  2446. // boiler plate.
  2447. Cond.clear();
  2448. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  2449. #ifndef NDEBUG
  2450. if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
  2451. // Given the exact block placement we chose, we may actually not _need_ to
  2452. // be able to edit PrevBB's terminator sequence, but not being _able_ to
  2453. // do that at this point is a bug.
  2454. assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
  2455. !PrevBB->canFallThrough()) &&
  2456. "Unexpected block with un-analyzable fallthrough!");
  2457. Cond.clear();
  2458. TBB = FBB = nullptr;
  2459. }
  2460. #endif
  2461. // The "PrevBB" is not yet updated to reflect current code layout, so,
  2462. // o. it may fall-through to a block without explicit "goto" instruction
  2463. // before layout, and no longer fall-through it after layout; or
  2464. // o. just opposite.
  2465. //
  2466. // analyzeBranch() may return erroneous value for FBB when these two
  2467. // situations take place. For the first scenario FBB is mistakenly set NULL;
  2468. // for the 2nd scenario, the FBB, which is expected to be NULL, is
  2469. // mistakenly pointing to "*BI".
  2470. // Thus, if the future change needs to use FBB before the layout is set, it
  2471. // has to correct FBB first by using the code similar to the following:
  2472. //
  2473. // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
  2474. // PrevBB->updateTerminator();
  2475. // Cond.clear();
  2476. // TBB = FBB = nullptr;
  2477. // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
  2478. // // FIXME: This should never take place.
  2479. // TBB = FBB = nullptr;
  2480. // }
  2481. // }
  2482. if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
  2483. PrevBB->updateTerminator();
  2484. }
  2485. // Fixup the last block.
  2486. Cond.clear();
  2487. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  2488. if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
  2489. F->back().updateTerminator();
  2490. BlockWorkList.clear();
  2491. EHPadWorkList.clear();
  2492. }
  2493. void MachineBlockPlacement::optimizeBranches() {
  2494. BlockChain &FunctionChain = *BlockToChain[&F->front()];
  2495. SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
  2496. // Now that all the basic blocks in the chain have the proper layout,
  2497. // make a final call to AnalyzeBranch with AllowModify set.
  2498. // Indeed, the target may be able to optimize the branches in a way we
  2499. // cannot because all branches may not be analyzable.
  2500. // E.g., the target may be able to remove an unconditional branch to
  2501. // a fallthrough when it occurs after predicated terminators.
  2502. SmallVector<MachineBasicBlock*, 4> EmptyBB;
  2503. for (MachineBasicBlock *ChainBB : FunctionChain) {
  2504. Cond.clear();
  2505. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  2506. if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
  2507. // If PrevBB has a two-way branch, try to re-order the branches
  2508. // such that we branch to the successor with higher probability first.
  2509. if (TBB && !Cond.empty() && FBB &&
  2510. MBPI->getEdgeProbability(ChainBB, FBB) >
  2511. MBPI->getEdgeProbability(ChainBB, TBB) &&
  2512. !TII->reverseBranchCondition(Cond)) {
  2513. LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
  2514. << getBlockName(ChainBB) << "\n");
  2515. LLVM_DEBUG(dbgs() << " Edge probability: "
  2516. << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
  2517. << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
  2518. DebugLoc dl; // FIXME: this is nowhere
  2519. TII->removeBranch(*ChainBB);
  2520. TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
  2521. ChainBB->updateTerminator();
  2522. } else if (Cond.empty() && TBB && ChainBB != TBB && !TBB->empty() &&
  2523. !TBB->canFallThrough()) {
  2524. // When ChainBB is unconditional branch to the TBB, and TBB has no
  2525. // fallthrough predecessor and fallthrough successor, try to merge
  2526. // ChainBB and TBB. This is legal under the one of following conditions:
  2527. // 1. ChainBB is empty except for an unconditional branch.
  2528. // 2. TBB has only one predecessor.
  2529. MachineFunction::iterator I(TBB);
  2530. if (((TBB == &*F->begin()) || !std::prev(I)->canFallThrough()) &&
  2531. (TailDup.isSimpleBB(ChainBB) || (TBB->pred_size() == 1))) {
  2532. TII->removeBranch(*ChainBB);
  2533. ChainBB->removeSuccessor(TBB);
  2534. // Update the CFG.
  2535. while (!TBB->pred_empty()) {
  2536. MachineBasicBlock *Pred = *(TBB->pred_end()-1);
  2537. Pred->ReplaceUsesOfBlockWith(TBB, ChainBB);
  2538. }
  2539. for (MachineBasicBlock *Succ : TBB->successors())
  2540. ChainBB->addSuccessor(Succ, MBPI->getEdgeProbability(TBB, Succ));
  2541. // Move all the instructions of TBB to ChainBB.
  2542. ChainBB->splice(ChainBB->end(), TBB, TBB->begin(), TBB->end());
  2543. EmptyBB.push_back(TBB);
  2544. }
  2545. }
  2546. }
  2547. }
  2548. for (auto BB: EmptyBB) {
  2549. MLI->removeBlock(BB);
  2550. FunctionChain.remove(BB);
  2551. BlockToChain.erase(BB);
  2552. F->erase(BB);
  2553. }
  2554. }
  2555. void MachineBlockPlacement::alignBlocks() {
  2556. // Walk through the backedges of the function now that we have fully laid out
  2557. // the basic blocks and align the destination of each backedge. We don't rely
  2558. // exclusively on the loop info here so that we can align backedges in
  2559. // unnatural CFGs and backedges that were introduced purely because of the
  2560. // loop rotations done during this layout pass.
  2561. if (F->getFunction().hasMinSize() ||
  2562. (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
  2563. return;
  2564. BlockChain &FunctionChain = *BlockToChain[&F->front()];
  2565. if (FunctionChain.begin() == FunctionChain.end())
  2566. return; // Empty chain.
  2567. const BranchProbability ColdProb(1, 5); // 20%
  2568. BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
  2569. BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
  2570. for (MachineBasicBlock *ChainBB : FunctionChain) {
  2571. if (ChainBB == *FunctionChain.begin())
  2572. continue;
  2573. // Don't align non-looping basic blocks. These are unlikely to execute
  2574. // enough times to matter in practice. Note that we'll still handle
  2575. // unnatural CFGs inside of a natural outer loop (the common case) and
  2576. // rotated loops.
  2577. MachineLoop *L = MLI->getLoopFor(ChainBB);
  2578. if (!L)
  2579. continue;
  2580. unsigned Align = TLI->getPrefLoopAlignment(L);
  2581. if (!Align)
  2582. continue; // Don't care about loop alignment.
  2583. // If the block is cold relative to the function entry don't waste space
  2584. // aligning it.
  2585. BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
  2586. if (Freq < WeightedEntryFreq)
  2587. continue;
  2588. // If the block is cold relative to its loop header, don't align it
  2589. // regardless of what edges into the block exist.
  2590. MachineBasicBlock *LoopHeader = L->getHeader();
  2591. BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
  2592. if (Freq < (LoopHeaderFreq * ColdProb))
  2593. continue;
  2594. // Check for the existence of a non-layout predecessor which would benefit
  2595. // from aligning this block.
  2596. MachineBasicBlock *LayoutPred =
  2597. &*std::prev(MachineFunction::iterator(ChainBB));
  2598. // Force alignment if all the predecessors are jumps. We already checked
  2599. // that the block isn't cold above.
  2600. if (!LayoutPred->isSuccessor(ChainBB)) {
  2601. ChainBB->setAlignment(Align);
  2602. continue;
  2603. }
  2604. // Align this block if the layout predecessor's edge into this block is
  2605. // cold relative to the block. When this is true, other predecessors make up
  2606. // all of the hot entries into the block and thus alignment is likely to be
  2607. // important.
  2608. BranchProbability LayoutProb =
  2609. MBPI->getEdgeProbability(LayoutPred, ChainBB);
  2610. BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
  2611. if (LayoutEdgeFreq <= (Freq * ColdProb))
  2612. ChainBB->setAlignment(Align);
  2613. }
  2614. }
  2615. /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
  2616. /// it was duplicated into its chain predecessor and removed.
  2617. /// \p BB - Basic block that may be duplicated.
  2618. ///
  2619. /// \p LPred - Chosen layout predecessor of \p BB.
  2620. /// Updated to be the chain end if LPred is removed.
  2621. /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
  2622. /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
  2623. /// Used to identify which blocks to update predecessor
  2624. /// counts.
  2625. /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
  2626. /// chosen in the given order due to unnatural CFG
  2627. /// only needed if \p BB is removed and
  2628. /// \p PrevUnplacedBlockIt pointed to \p BB.
  2629. /// @return true if \p BB was removed.
  2630. bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
  2631. MachineBasicBlock *BB, MachineBasicBlock *&LPred,
  2632. const MachineBasicBlock *LoopHeaderBB,
  2633. BlockChain &Chain, BlockFilterSet *BlockFilter,
  2634. MachineFunction::iterator &PrevUnplacedBlockIt) {
  2635. bool Removed, DuplicatedToLPred;
  2636. bool DuplicatedToOriginalLPred;
  2637. Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
  2638. PrevUnplacedBlockIt,
  2639. DuplicatedToLPred);
  2640. if (!Removed)
  2641. return false;
  2642. DuplicatedToOriginalLPred = DuplicatedToLPred;
  2643. // Iteratively try to duplicate again. It can happen that a block that is
  2644. // duplicated into is still small enough to be duplicated again.
  2645. // No need to call markBlockSuccessors in this case, as the blocks being
  2646. // duplicated from here on are already scheduled.
  2647. // Note that DuplicatedToLPred always implies Removed.
  2648. while (DuplicatedToLPred) {
  2649. assert(Removed && "Block must have been removed to be duplicated into its "
  2650. "layout predecessor.");
  2651. MachineBasicBlock *DupBB, *DupPred;
  2652. // The removal callback causes Chain.end() to be updated when a block is
  2653. // removed. On the first pass through the loop, the chain end should be the
  2654. // same as it was on function entry. On subsequent passes, because we are
  2655. // duplicating the block at the end of the chain, if it is removed the
  2656. // chain will have shrunk by one block.
  2657. BlockChain::iterator ChainEnd = Chain.end();
  2658. DupBB = *(--ChainEnd);
  2659. // Now try to duplicate again.
  2660. if (ChainEnd == Chain.begin())
  2661. break;
  2662. DupPred = *std::prev(ChainEnd);
  2663. Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
  2664. PrevUnplacedBlockIt,
  2665. DuplicatedToLPred);
  2666. }
  2667. // If BB was duplicated into LPred, it is now scheduled. But because it was
  2668. // removed, markChainSuccessors won't be called for its chain. Instead we
  2669. // call markBlockSuccessors for LPred to achieve the same effect. This must go
  2670. // at the end because repeating the tail duplication can increase the number
  2671. // of unscheduled predecessors.
  2672. LPred = *std::prev(Chain.end());
  2673. if (DuplicatedToOriginalLPred)
  2674. markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
  2675. return true;
  2676. }
  2677. /// Tail duplicate \p BB into (some) predecessors if profitable.
  2678. /// \p BB - Basic block that may be duplicated
  2679. /// \p LPred - Chosen layout predecessor of \p BB
  2680. /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
  2681. /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
  2682. /// Used to identify which blocks to update predecessor
  2683. /// counts.
  2684. /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
  2685. /// chosen in the given order due to unnatural CFG
  2686. /// only needed if \p BB is removed and
  2687. /// \p PrevUnplacedBlockIt pointed to \p BB.
  2688. /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
  2689. /// only be true if the block was removed.
  2690. /// \return - True if the block was duplicated into all preds and removed.
  2691. bool MachineBlockPlacement::maybeTailDuplicateBlock(
  2692. MachineBasicBlock *BB, MachineBasicBlock *LPred,
  2693. BlockChain &Chain, BlockFilterSet *BlockFilter,
  2694. MachineFunction::iterator &PrevUnplacedBlockIt,
  2695. bool &DuplicatedToLPred) {
  2696. DuplicatedToLPred = false;
  2697. if (!shouldTailDuplicate(BB))
  2698. return false;
  2699. LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
  2700. << "\n");
  2701. // This has to be a callback because none of it can be done after
  2702. // BB is deleted.
  2703. bool Removed = false;
  2704. auto RemovalCallback =
  2705. [&](MachineBasicBlock *RemBB) {
  2706. // Signal to outer function
  2707. Removed = true;
  2708. // Conservative default.
  2709. bool InWorkList = true;
  2710. // Remove from the Chain and Chain Map
  2711. if (BlockToChain.count(RemBB)) {
  2712. BlockChain *Chain = BlockToChain[RemBB];
  2713. InWorkList = Chain->UnscheduledPredecessors == 0;
  2714. Chain->remove(RemBB);
  2715. BlockToChain.erase(RemBB);
  2716. }
  2717. // Handle the unplaced block iterator
  2718. if (&(*PrevUnplacedBlockIt) == RemBB) {
  2719. PrevUnplacedBlockIt++;
  2720. }
  2721. // Handle the Work Lists
  2722. if (InWorkList) {
  2723. SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
  2724. if (RemBB->isEHPad())
  2725. RemoveList = EHPadWorkList;
  2726. RemoveList.erase(
  2727. llvm::remove_if(RemoveList,
  2728. [RemBB](MachineBasicBlock *BB) {
  2729. return BB == RemBB;
  2730. }),
  2731. RemoveList.end());
  2732. }
  2733. // Handle the filter set
  2734. if (BlockFilter) {
  2735. BlockFilter->remove(RemBB);
  2736. }
  2737. // Remove the block from loop info.
  2738. MLI->removeBlock(RemBB);
  2739. if (RemBB == PreferredLoopExit)
  2740. PreferredLoopExit = nullptr;
  2741. LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
  2742. << getBlockName(RemBB) << "\n");
  2743. };
  2744. auto RemovalCallbackRef =
  2745. function_ref<void(MachineBasicBlock*)>(RemovalCallback);
  2746. SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
  2747. bool IsSimple = TailDup.isSimpleBB(BB);
  2748. TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
  2749. &DuplicatedPreds, &RemovalCallbackRef);
  2750. // Update UnscheduledPredecessors to reflect tail-duplication.
  2751. DuplicatedToLPred = false;
  2752. for (MachineBasicBlock *Pred : DuplicatedPreds) {
  2753. // We're only looking for unscheduled predecessors that match the filter.
  2754. BlockChain* PredChain = BlockToChain[Pred];
  2755. if (Pred == LPred)
  2756. DuplicatedToLPred = true;
  2757. if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
  2758. || PredChain == &Chain)
  2759. continue;
  2760. for (MachineBasicBlock *NewSucc : Pred->successors()) {
  2761. if (BlockFilter && !BlockFilter->count(NewSucc))
  2762. continue;
  2763. BlockChain *NewChain = BlockToChain[NewSucc];
  2764. if (NewChain != &Chain && NewChain != PredChain)
  2765. NewChain->UnscheduledPredecessors++;
  2766. }
  2767. }
  2768. return Removed;
  2769. }
  2770. bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
  2771. if (skipFunction(MF.getFunction()))
  2772. return false;
  2773. // Check for single-block functions and skip them.
  2774. if (std::next(MF.begin()) == MF.end())
  2775. return false;
  2776. F = &MF;
  2777. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  2778. MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
  2779. getAnalysis<MachineBlockFrequencyInfo>());
  2780. MLI = &getAnalysis<MachineLoopInfo>();
  2781. TII = MF.getSubtarget().getInstrInfo();
  2782. TLI = MF.getSubtarget().getTargetLowering();
  2783. MPDT = nullptr;
  2784. // Initialize PreferredLoopExit to nullptr here since it may never be set if
  2785. // there are no MachineLoops.
  2786. PreferredLoopExit = nullptr;
  2787. assert(BlockToChain.empty() &&
  2788. "BlockToChain map should be empty before starting placement.");
  2789. assert(ComputedEdges.empty() &&
  2790. "Computed Edge map should be empty before starting placement.");
  2791. unsigned TailDupSize = TailDupPlacementThreshold;
  2792. // If only the aggressive threshold is explicitly set, use it.
  2793. if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
  2794. TailDupPlacementThreshold.getNumOccurrences() == 0)
  2795. TailDupSize = TailDupPlacementAggressiveThreshold;
  2796. TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
  2797. // For aggressive optimization, we can adjust some thresholds to be less
  2798. // conservative.
  2799. if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
  2800. // At O3 we should be more willing to copy blocks for tail duplication. This
  2801. // increases size pressure, so we only do it at O3
  2802. // Do this unless only the regular threshold is explicitly set.
  2803. if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
  2804. TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
  2805. TailDupSize = TailDupPlacementAggressiveThreshold;
  2806. }
  2807. if (allowTailDupPlacement()) {
  2808. MPDT = &getAnalysis<MachinePostDominatorTree>();
  2809. if (MF.getFunction().hasOptSize())
  2810. TailDupSize = 1;
  2811. bool PreRegAlloc = false;
  2812. TailDup.initMF(MF, PreRegAlloc, MBPI, /* LayoutMode */ true, TailDupSize);
  2813. precomputeTriangleChains();
  2814. }
  2815. buildCFGChains();
  2816. // Changing the layout can create new tail merging opportunities.
  2817. // TailMerge can create jump into if branches that make CFG irreducible for
  2818. // HW that requires structured CFG.
  2819. bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
  2820. PassConfig->getEnableTailMerge() &&
  2821. BranchFoldPlacement;
  2822. // No tail merging opportunities if the block number is less than four.
  2823. if (MF.size() > 3 && EnableTailMerge) {
  2824. unsigned TailMergeSize = TailDupSize + 1;
  2825. BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
  2826. *MBPI, TailMergeSize);
  2827. if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
  2828. getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
  2829. /*AfterPlacement=*/true)) {
  2830. // Redo the layout if tail merging creates/removes/moves blocks.
  2831. BlockToChain.clear();
  2832. ComputedEdges.clear();
  2833. // Must redo the post-dominator tree if blocks were changed.
  2834. if (MPDT)
  2835. MPDT->runOnMachineFunction(MF);
  2836. ChainAllocator.DestroyAll();
  2837. buildCFGChains();
  2838. }
  2839. }
  2840. // optimizeBranches() may change the blocks, but we haven't updated the
  2841. // post-dominator tree. Because the post-dominator tree won't be used after
  2842. // this function and this pass don't preserve the post-dominator tree.
  2843. optimizeBranches();
  2844. alignBlocks();
  2845. BlockToChain.clear();
  2846. ComputedEdges.clear();
  2847. ChainAllocator.DestroyAll();
  2848. if (AlignAllBlock)
  2849. // Align all of the blocks in the function to a specific alignment.
  2850. for (MachineBasicBlock &MBB : MF)
  2851. MBB.setAlignment(AlignAllBlock);
  2852. else if (AlignAllNonFallThruBlocks) {
  2853. // Align all of the blocks that have no fall-through predecessors to a
  2854. // specific alignment.
  2855. for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
  2856. auto LayoutPred = std::prev(MBI);
  2857. if (!LayoutPred->isSuccessor(&*MBI))
  2858. MBI->setAlignment(AlignAllNonFallThruBlocks);
  2859. }
  2860. }
  2861. if (ViewBlockLayoutWithBFI != GVDT_None &&
  2862. (ViewBlockFreqFuncName.empty() ||
  2863. F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
  2864. MBFI->view("MBP." + MF.getName(), false);
  2865. }
  2866. // We always return true as we have no way to track whether the final order
  2867. // differs from the original order.
  2868. return true;
  2869. }
  2870. namespace {
  2871. /// A pass to compute block placement statistics.
  2872. ///
  2873. /// A separate pass to compute interesting statistics for evaluating block
  2874. /// placement. This is separate from the actual placement pass so that they can
  2875. /// be computed in the absence of any placement transformations or when using
  2876. /// alternative placement strategies.
  2877. class MachineBlockPlacementStats : public MachineFunctionPass {
  2878. /// A handle to the branch probability pass.
  2879. const MachineBranchProbabilityInfo *MBPI;
  2880. /// A handle to the function-wide block frequency pass.
  2881. const MachineBlockFrequencyInfo *MBFI;
  2882. public:
  2883. static char ID; // Pass identification, replacement for typeid
  2884. MachineBlockPlacementStats() : MachineFunctionPass(ID) {
  2885. initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
  2886. }
  2887. bool runOnMachineFunction(MachineFunction &F) override;
  2888. void getAnalysisUsage(AnalysisUsage &AU) const override {
  2889. AU.addRequired<MachineBranchProbabilityInfo>();
  2890. AU.addRequired<MachineBlockFrequencyInfo>();
  2891. AU.setPreservesAll();
  2892. MachineFunctionPass::getAnalysisUsage(AU);
  2893. }
  2894. };
  2895. } // end anonymous namespace
  2896. char MachineBlockPlacementStats::ID = 0;
  2897. char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
  2898. INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
  2899. "Basic Block Placement Stats", false, false)
  2900. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  2901. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  2902. INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
  2903. "Basic Block Placement Stats", false, false)
  2904. bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
  2905. // Check for single-block functions and skip them.
  2906. if (std::next(F.begin()) == F.end())
  2907. return false;
  2908. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  2909. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  2910. for (MachineBasicBlock &MBB : F) {
  2911. BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
  2912. Statistic &NumBranches =
  2913. (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
  2914. Statistic &BranchTakenFreq =
  2915. (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
  2916. for (MachineBasicBlock *Succ : MBB.successors()) {
  2917. // Skip if this successor is a fallthrough.
  2918. if (MBB.isLayoutSuccessor(Succ))
  2919. continue;
  2920. BlockFrequency EdgeFreq =
  2921. BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
  2922. ++NumBranches;
  2923. BranchTakenFreq += EdgeFreq.getFrequency();
  2924. }
  2925. }
  2926. return false;
  2927. }