MachineBlockPlacement.cpp 129 KB

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