MachineBlockPlacement.cpp 146 KB

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