JumpThreading.cpp 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068
  1. //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
  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 the Jump Threading pass.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/Scalar/JumpThreading.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/DenseSet.h"
  15. #include "llvm/ADT/MapVector.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/AliasAnalysis.h"
  22. #include "llvm/Analysis/BlockFrequencyInfo.h"
  23. #include "llvm/Analysis/BranchProbabilityInfo.h"
  24. #include "llvm/Analysis/CFG.h"
  25. #include "llvm/Analysis/ConstantFolding.h"
  26. #include "llvm/Analysis/DomTreeUpdater.h"
  27. #include "llvm/Analysis/GlobalsModRef.h"
  28. #include "llvm/Analysis/GuardUtils.h"
  29. #include "llvm/Analysis/InstructionSimplify.h"
  30. #include "llvm/Analysis/LazyValueInfo.h"
  31. #include "llvm/Analysis/Loads.h"
  32. #include "llvm/Analysis/LoopInfo.h"
  33. #include "llvm/Analysis/MemoryLocation.h"
  34. #include "llvm/Analysis/TargetLibraryInfo.h"
  35. #include "llvm/Analysis/TargetTransformInfo.h"
  36. #include "llvm/Analysis/ValueTracking.h"
  37. #include "llvm/IR/BasicBlock.h"
  38. #include "llvm/IR/CFG.h"
  39. #include "llvm/IR/Constant.h"
  40. #include "llvm/IR/ConstantRange.h"
  41. #include "llvm/IR/Constants.h"
  42. #include "llvm/IR/DataLayout.h"
  43. #include "llvm/IR/Dominators.h"
  44. #include "llvm/IR/Function.h"
  45. #include "llvm/IR/InstrTypes.h"
  46. #include "llvm/IR/Instruction.h"
  47. #include "llvm/IR/Instructions.h"
  48. #include "llvm/IR/IntrinsicInst.h"
  49. #include "llvm/IR/Intrinsics.h"
  50. #include "llvm/IR/LLVMContext.h"
  51. #include "llvm/IR/MDBuilder.h"
  52. #include "llvm/IR/Metadata.h"
  53. #include "llvm/IR/Module.h"
  54. #include "llvm/IR/PassManager.h"
  55. #include "llvm/IR/PatternMatch.h"
  56. #include "llvm/IR/Type.h"
  57. #include "llvm/IR/Use.h"
  58. #include "llvm/IR/User.h"
  59. #include "llvm/IR/Value.h"
  60. #include "llvm/InitializePasses.h"
  61. #include "llvm/Pass.h"
  62. #include "llvm/Support/BlockFrequency.h"
  63. #include "llvm/Support/BranchProbability.h"
  64. #include "llvm/Support/Casting.h"
  65. #include "llvm/Support/CommandLine.h"
  66. #include "llvm/Support/Debug.h"
  67. #include "llvm/Support/raw_ostream.h"
  68. #include "llvm/Transforms/Scalar.h"
  69. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  70. #include "llvm/Transforms/Utils/Cloning.h"
  71. #include "llvm/Transforms/Utils/Local.h"
  72. #include "llvm/Transforms/Utils/SSAUpdater.h"
  73. #include "llvm/Transforms/Utils/ValueMapper.h"
  74. #include <algorithm>
  75. #include <cassert>
  76. #include <cstddef>
  77. #include <cstdint>
  78. #include <iterator>
  79. #include <memory>
  80. #include <utility>
  81. using namespace llvm;
  82. using namespace jumpthreading;
  83. #define DEBUG_TYPE "jump-threading"
  84. STATISTIC(NumThreads, "Number of jumps threaded");
  85. STATISTIC(NumFolds, "Number of terminators folded");
  86. STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
  87. static cl::opt<unsigned>
  88. BBDuplicateThreshold("jump-threading-threshold",
  89. cl::desc("Max block size to duplicate for jump threading"),
  90. cl::init(6), cl::Hidden);
  91. static cl::opt<unsigned>
  92. ImplicationSearchThreshold(
  93. "jump-threading-implication-search-threshold",
  94. cl::desc("The number of predecessors to search for a stronger "
  95. "condition to use to thread over a weaker condition"),
  96. cl::init(3), cl::Hidden);
  97. static cl::opt<bool> PrintLVIAfterJumpThreading(
  98. "print-lvi-after-jump-threading",
  99. cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false),
  100. cl::Hidden);
  101. static cl::opt<bool> JumpThreadingFreezeSelectCond(
  102. "jump-threading-freeze-select-cond",
  103. cl::desc("Freeze the condition when unfolding select"), cl::init(false),
  104. cl::Hidden);
  105. static cl::opt<bool> ThreadAcrossLoopHeaders(
  106. "jump-threading-across-loop-headers",
  107. cl::desc("Allow JumpThreading to thread across loop headers, for testing"),
  108. cl::init(false), cl::Hidden);
  109. namespace {
  110. /// This pass performs 'jump threading', which looks at blocks that have
  111. /// multiple predecessors and multiple successors. If one or more of the
  112. /// predecessors of the block can be proven to always jump to one of the
  113. /// successors, we forward the edge from the predecessor to the successor by
  114. /// duplicating the contents of this block.
  115. ///
  116. /// An example of when this can occur is code like this:
  117. ///
  118. /// if () { ...
  119. /// X = 4;
  120. /// }
  121. /// if (X < 3) {
  122. ///
  123. /// In this case, the unconditional branch at the end of the first if can be
  124. /// revectored to the false side of the second if.
  125. class JumpThreading : public FunctionPass {
  126. JumpThreadingPass Impl;
  127. public:
  128. static char ID; // Pass identification
  129. JumpThreading(bool InsertFreezeWhenUnfoldingSelect = false, int T = -1)
  130. : FunctionPass(ID), Impl(InsertFreezeWhenUnfoldingSelect, T) {
  131. initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
  132. }
  133. bool runOnFunction(Function &F) override;
  134. void getAnalysisUsage(AnalysisUsage &AU) const override {
  135. AU.addRequired<DominatorTreeWrapperPass>();
  136. AU.addPreserved<DominatorTreeWrapperPass>();
  137. AU.addRequired<AAResultsWrapperPass>();
  138. AU.addRequired<LazyValueInfoWrapperPass>();
  139. AU.addPreserved<LazyValueInfoWrapperPass>();
  140. AU.addPreserved<GlobalsAAWrapperPass>();
  141. AU.addRequired<TargetLibraryInfoWrapperPass>();
  142. AU.addRequired<TargetTransformInfoWrapperPass>();
  143. }
  144. void releaseMemory() override { Impl.releaseMemory(); }
  145. };
  146. } // end anonymous namespace
  147. char JumpThreading::ID = 0;
  148. INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
  149. "Jump Threading", false, false)
  150. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  151. INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
  152. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  153. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  154. INITIALIZE_PASS_END(JumpThreading, "jump-threading",
  155. "Jump Threading", false, false)
  156. // Public interface to the Jump Threading pass
  157. FunctionPass *llvm::createJumpThreadingPass(bool InsertFr, int Threshold) {
  158. return new JumpThreading(InsertFr, Threshold);
  159. }
  160. JumpThreadingPass::JumpThreadingPass(bool InsertFr, int T) {
  161. InsertFreezeWhenUnfoldingSelect = JumpThreadingFreezeSelectCond | InsertFr;
  162. DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
  163. }
  164. // Update branch probability information according to conditional
  165. // branch probability. This is usually made possible for cloned branches
  166. // in inline instances by the context specific profile in the caller.
  167. // For instance,
  168. //
  169. // [Block PredBB]
  170. // [Branch PredBr]
  171. // if (t) {
  172. // Block A;
  173. // } else {
  174. // Block B;
  175. // }
  176. //
  177. // [Block BB]
  178. // cond = PN([true, %A], [..., %B]); // PHI node
  179. // [Branch CondBr]
  180. // if (cond) {
  181. // ... // P(cond == true) = 1%
  182. // }
  183. //
  184. // Here we know that when block A is taken, cond must be true, which means
  185. // P(cond == true | A) = 1
  186. //
  187. // Given that P(cond == true) = P(cond == true | A) * P(A) +
  188. // P(cond == true | B) * P(B)
  189. // we get:
  190. // P(cond == true ) = P(A) + P(cond == true | B) * P(B)
  191. //
  192. // which gives us:
  193. // P(A) is less than P(cond == true), i.e.
  194. // P(t == true) <= P(cond == true)
  195. //
  196. // In other words, if we know P(cond == true) is unlikely, we know
  197. // that P(t == true) is also unlikely.
  198. //
  199. static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) {
  200. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  201. if (!CondBr)
  202. return;
  203. uint64_t TrueWeight, FalseWeight;
  204. if (!CondBr->extractProfMetadata(TrueWeight, FalseWeight))
  205. return;
  206. if (TrueWeight + FalseWeight == 0)
  207. // Zero branch_weights do not give a hint for getting branch probabilities.
  208. // Technically it would result in division by zero denominator, which is
  209. // TrueWeight + FalseWeight.
  210. return;
  211. // Returns the outgoing edge of the dominating predecessor block
  212. // that leads to the PhiNode's incoming block:
  213. auto GetPredOutEdge =
  214. [](BasicBlock *IncomingBB,
  215. BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
  216. auto *PredBB = IncomingBB;
  217. auto *SuccBB = PhiBB;
  218. SmallPtrSet<BasicBlock *, 16> Visited;
  219. while (true) {
  220. BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
  221. if (PredBr && PredBr->isConditional())
  222. return {PredBB, SuccBB};
  223. Visited.insert(PredBB);
  224. auto *SinglePredBB = PredBB->getSinglePredecessor();
  225. if (!SinglePredBB)
  226. return {nullptr, nullptr};
  227. // Stop searching when SinglePredBB has been visited. It means we see
  228. // an unreachable loop.
  229. if (Visited.count(SinglePredBB))
  230. return {nullptr, nullptr};
  231. SuccBB = PredBB;
  232. PredBB = SinglePredBB;
  233. }
  234. };
  235. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  236. Value *PhiOpnd = PN->getIncomingValue(i);
  237. ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
  238. if (!CI || !CI->getType()->isIntegerTy(1))
  239. continue;
  240. BranchProbability BP =
  241. (CI->isOne() ? BranchProbability::getBranchProbability(
  242. TrueWeight, TrueWeight + FalseWeight)
  243. : BranchProbability::getBranchProbability(
  244. FalseWeight, TrueWeight + FalseWeight));
  245. auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB);
  246. if (!PredOutEdge.first)
  247. return;
  248. BasicBlock *PredBB = PredOutEdge.first;
  249. BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
  250. if (!PredBr)
  251. return;
  252. uint64_t PredTrueWeight, PredFalseWeight;
  253. // FIXME: We currently only set the profile data when it is missing.
  254. // With PGO, this can be used to refine even existing profile data with
  255. // context information. This needs to be done after more performance
  256. // testing.
  257. if (PredBr->extractProfMetadata(PredTrueWeight, PredFalseWeight))
  258. continue;
  259. // We can not infer anything useful when BP >= 50%, because BP is the
  260. // upper bound probability value.
  261. if (BP >= BranchProbability(50, 100))
  262. continue;
  263. SmallVector<uint32_t, 2> Weights;
  264. if (PredBr->getSuccessor(0) == PredOutEdge.second) {
  265. Weights.push_back(BP.getNumerator());
  266. Weights.push_back(BP.getCompl().getNumerator());
  267. } else {
  268. Weights.push_back(BP.getCompl().getNumerator());
  269. Weights.push_back(BP.getNumerator());
  270. }
  271. PredBr->setMetadata(LLVMContext::MD_prof,
  272. MDBuilder(PredBr->getParent()->getContext())
  273. .createBranchWeights(Weights));
  274. }
  275. }
  276. /// runOnFunction - Toplevel algorithm.
  277. bool JumpThreading::runOnFunction(Function &F) {
  278. if (skipFunction(F))
  279. return false;
  280. auto TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  281. // Jump Threading has no sense for the targets with divergent CF
  282. if (TTI->hasBranchDivergence())
  283. return false;
  284. auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  285. auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  286. auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
  287. auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  288. DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
  289. std::unique_ptr<BlockFrequencyInfo> BFI;
  290. std::unique_ptr<BranchProbabilityInfo> BPI;
  291. if (F.hasProfileData()) {
  292. LoopInfo LI{DominatorTree(F)};
  293. BPI.reset(new BranchProbabilityInfo(F, LI, TLI));
  294. BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
  295. }
  296. bool Changed = Impl.runImpl(F, TLI, TTI, LVI, AA, &DTU, F.hasProfileData(),
  297. std::move(BFI), std::move(BPI));
  298. if (PrintLVIAfterJumpThreading) {
  299. dbgs() << "LVI for function '" << F.getName() << "':\n";
  300. LVI->printLVI(F, DTU.getDomTree(), dbgs());
  301. }
  302. return Changed;
  303. }
  304. PreservedAnalyses JumpThreadingPass::run(Function &F,
  305. FunctionAnalysisManager &AM) {
  306. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  307. // Jump Threading has no sense for the targets with divergent CF
  308. if (TTI.hasBranchDivergence())
  309. return PreservedAnalyses::all();
  310. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  311. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  312. auto &LVI = AM.getResult<LazyValueAnalysis>(F);
  313. auto &AA = AM.getResult<AAManager>(F);
  314. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  315. std::unique_ptr<BlockFrequencyInfo> BFI;
  316. std::unique_ptr<BranchProbabilityInfo> BPI;
  317. if (F.hasProfileData()) {
  318. LoopInfo LI{DominatorTree(F)};
  319. BPI.reset(new BranchProbabilityInfo(F, LI, &TLI));
  320. BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
  321. }
  322. bool Changed = runImpl(F, &TLI, &TTI, &LVI, &AA, &DTU, F.hasProfileData(),
  323. std::move(BFI), std::move(BPI));
  324. if (PrintLVIAfterJumpThreading) {
  325. dbgs() << "LVI for function '" << F.getName() << "':\n";
  326. LVI.printLVI(F, DTU.getDomTree(), dbgs());
  327. }
  328. if (!Changed)
  329. return PreservedAnalyses::all();
  330. PreservedAnalyses PA;
  331. PA.preserve<DominatorTreeAnalysis>();
  332. PA.preserve<LazyValueAnalysis>();
  333. return PA;
  334. }
  335. bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
  336. TargetTransformInfo *TTI_, LazyValueInfo *LVI_,
  337. AliasAnalysis *AA_, DomTreeUpdater *DTU_,
  338. bool HasProfileData_,
  339. std::unique_ptr<BlockFrequencyInfo> BFI_,
  340. std::unique_ptr<BranchProbabilityInfo> BPI_) {
  341. LLVM_DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
  342. TLI = TLI_;
  343. TTI = TTI_;
  344. LVI = LVI_;
  345. AA = AA_;
  346. DTU = DTU_;
  347. BFI.reset();
  348. BPI.reset();
  349. // When profile data is available, we need to update edge weights after
  350. // successful jump threading, which requires both BPI and BFI being available.
  351. HasProfileData = HasProfileData_;
  352. auto *GuardDecl = F.getParent()->getFunction(
  353. Intrinsic::getName(Intrinsic::experimental_guard));
  354. HasGuards = GuardDecl && !GuardDecl->use_empty();
  355. if (HasProfileData) {
  356. BPI = std::move(BPI_);
  357. BFI = std::move(BFI_);
  358. }
  359. // Reduce the number of instructions duplicated when optimizing strictly for
  360. // size.
  361. if (BBDuplicateThreshold.getNumOccurrences())
  362. BBDupThreshold = BBDuplicateThreshold;
  363. else if (F.hasFnAttribute(Attribute::MinSize))
  364. BBDupThreshold = 3;
  365. else
  366. BBDupThreshold = DefaultBBDupThreshold;
  367. // JumpThreading must not processes blocks unreachable from entry. It's a
  368. // waste of compute time and can potentially lead to hangs.
  369. SmallPtrSet<BasicBlock *, 16> Unreachable;
  370. assert(DTU && "DTU isn't passed into JumpThreading before using it.");
  371. assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed.");
  372. DominatorTree &DT = DTU->getDomTree();
  373. for (auto &BB : F)
  374. if (!DT.isReachableFromEntry(&BB))
  375. Unreachable.insert(&BB);
  376. if (!ThreadAcrossLoopHeaders)
  377. findLoopHeaders(F);
  378. bool EverChanged = false;
  379. bool Changed;
  380. do {
  381. Changed = false;
  382. for (auto &BB : F) {
  383. if (Unreachable.count(&BB))
  384. continue;
  385. while (processBlock(&BB)) // Thread all of the branches we can over BB.
  386. Changed = true;
  387. // Jump threading may have introduced redundant debug values into BB
  388. // which should be removed.
  389. if (Changed)
  390. RemoveRedundantDbgInstrs(&BB);
  391. // Stop processing BB if it's the entry or is now deleted. The following
  392. // routines attempt to eliminate BB and locating a suitable replacement
  393. // for the entry is non-trivial.
  394. if (&BB == &F.getEntryBlock() || DTU->isBBPendingDeletion(&BB))
  395. continue;
  396. if (pred_empty(&BB)) {
  397. // When processBlock makes BB unreachable it doesn't bother to fix up
  398. // the instructions in it. We must remove BB to prevent invalid IR.
  399. LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName()
  400. << "' with terminator: " << *BB.getTerminator()
  401. << '\n');
  402. LoopHeaders.erase(&BB);
  403. LVI->eraseBlock(&BB);
  404. DeleteDeadBlock(&BB, DTU);
  405. Changed = true;
  406. continue;
  407. }
  408. // processBlock doesn't thread BBs with unconditional TIs. However, if BB
  409. // is "almost empty", we attempt to merge BB with its sole successor.
  410. auto *BI = dyn_cast<BranchInst>(BB.getTerminator());
  411. if (BI && BI->isUnconditional()) {
  412. BasicBlock *Succ = BI->getSuccessor(0);
  413. if (
  414. // The terminator must be the only non-phi instruction in BB.
  415. BB.getFirstNonPHIOrDbg(true)->isTerminator() &&
  416. // Don't alter Loop headers and latches to ensure another pass can
  417. // detect and transform nested loops later.
  418. !LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) &&
  419. TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU)) {
  420. RemoveRedundantDbgInstrs(Succ);
  421. // BB is valid for cleanup here because we passed in DTU. F remains
  422. // BB's parent until a DTU->getDomTree() event.
  423. LVI->eraseBlock(&BB);
  424. Changed = true;
  425. }
  426. }
  427. }
  428. EverChanged |= Changed;
  429. } while (Changed);
  430. LoopHeaders.clear();
  431. return EverChanged;
  432. }
  433. // Replace uses of Cond with ToVal when safe to do so. If all uses are
  434. // replaced, we can remove Cond. We cannot blindly replace all uses of Cond
  435. // because we may incorrectly replace uses when guards/assumes are uses of
  436. // of `Cond` and we used the guards/assume to reason about the `Cond` value
  437. // at the end of block. RAUW unconditionally replaces all uses
  438. // including the guards/assumes themselves and the uses before the
  439. // guard/assume.
  440. static void replaceFoldableUses(Instruction *Cond, Value *ToVal) {
  441. assert(Cond->getType() == ToVal->getType());
  442. auto *BB = Cond->getParent();
  443. // We can unconditionally replace all uses in non-local blocks (i.e. uses
  444. // strictly dominated by BB), since LVI information is true from the
  445. // terminator of BB.
  446. replaceNonLocalUsesWith(Cond, ToVal);
  447. for (Instruction &I : reverse(*BB)) {
  448. // Reached the Cond whose uses we are trying to replace, so there are no
  449. // more uses.
  450. if (&I == Cond)
  451. break;
  452. // We only replace uses in instructions that are guaranteed to reach the end
  453. // of BB, where we know Cond is ToVal.
  454. if (!isGuaranteedToTransferExecutionToSuccessor(&I))
  455. break;
  456. I.replaceUsesOfWith(Cond, ToVal);
  457. }
  458. if (Cond->use_empty() && !Cond->mayHaveSideEffects())
  459. Cond->eraseFromParent();
  460. }
  461. /// Return the cost of duplicating a piece of this block from first non-phi
  462. /// and before StopAt instruction to thread across it. Stop scanning the block
  463. /// when exceeding the threshold. If duplication is impossible, returns ~0U.
  464. static unsigned getJumpThreadDuplicationCost(const TargetTransformInfo *TTI,
  465. BasicBlock *BB,
  466. Instruction *StopAt,
  467. unsigned Threshold) {
  468. assert(StopAt->getParent() == BB && "Not an instruction from proper BB?");
  469. /// Ignore PHI nodes, these will be flattened when duplication happens.
  470. BasicBlock::const_iterator I(BB->getFirstNonPHI());
  471. // FIXME: THREADING will delete values that are just used to compute the
  472. // branch, so they shouldn't count against the duplication cost.
  473. unsigned Bonus = 0;
  474. if (BB->getTerminator() == StopAt) {
  475. // Threading through a switch statement is particularly profitable. If this
  476. // block ends in a switch, decrease its cost to make it more likely to
  477. // happen.
  478. if (isa<SwitchInst>(StopAt))
  479. Bonus = 6;
  480. // The same holds for indirect branches, but slightly more so.
  481. if (isa<IndirectBrInst>(StopAt))
  482. Bonus = 8;
  483. }
  484. // Bump the threshold up so the early exit from the loop doesn't skip the
  485. // terminator-based Size adjustment at the end.
  486. Threshold += Bonus;
  487. // Sum up the cost of each instruction until we get to the terminator. Don't
  488. // include the terminator because the copy won't include it.
  489. unsigned Size = 0;
  490. for (; &*I != StopAt; ++I) {
  491. // Stop scanning the block if we've reached the threshold.
  492. if (Size > Threshold)
  493. return Size;
  494. // Bail out if this instruction gives back a token type, it is not possible
  495. // to duplicate it if it is used outside this BB.
  496. if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
  497. return ~0U;
  498. // Blocks with NoDuplicate are modelled as having infinite cost, so they
  499. // are never duplicated.
  500. if (const CallInst *CI = dyn_cast<CallInst>(I))
  501. if (CI->cannotDuplicate() || CI->isConvergent())
  502. return ~0U;
  503. if (TTI->getUserCost(&*I, TargetTransformInfo::TCK_SizeAndLatency)
  504. == TargetTransformInfo::TCC_Free)
  505. continue;
  506. // All other instructions count for at least one unit.
  507. ++Size;
  508. // Calls are more expensive. If they are non-intrinsic calls, we model them
  509. // as having cost of 4. If they are a non-vector intrinsic, we model them
  510. // as having cost of 2 total, and if they are a vector intrinsic, we model
  511. // them as having cost 1.
  512. if (const CallInst *CI = dyn_cast<CallInst>(I)) {
  513. if (!isa<IntrinsicInst>(CI))
  514. Size += 3;
  515. else if (!CI->getType()->isVectorTy())
  516. Size += 1;
  517. }
  518. }
  519. return Size > Bonus ? Size - Bonus : 0;
  520. }
  521. /// findLoopHeaders - We do not want jump threading to turn proper loop
  522. /// structures into irreducible loops. Doing this breaks up the loop nesting
  523. /// hierarchy and pessimizes later transformations. To prevent this from
  524. /// happening, we first have to find the loop headers. Here we approximate this
  525. /// by finding targets of backedges in the CFG.
  526. ///
  527. /// Note that there definitely are cases when we want to allow threading of
  528. /// edges across a loop header. For example, threading a jump from outside the
  529. /// loop (the preheader) to an exit block of the loop is definitely profitable.
  530. /// It is also almost always profitable to thread backedges from within the loop
  531. /// to exit blocks, and is often profitable to thread backedges to other blocks
  532. /// within the loop (forming a nested loop). This simple analysis is not rich
  533. /// enough to track all of these properties and keep it up-to-date as the CFG
  534. /// mutates, so we don't allow any of these transformations.
  535. void JumpThreadingPass::findLoopHeaders(Function &F) {
  536. SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
  537. FindFunctionBackedges(F, Edges);
  538. for (const auto &Edge : Edges)
  539. LoopHeaders.insert(Edge.second);
  540. }
  541. /// getKnownConstant - Helper method to determine if we can thread over a
  542. /// terminator with the given value as its condition, and if so what value to
  543. /// use for that. What kind of value this is depends on whether we want an
  544. /// integer or a block address, but an undef is always accepted.
  545. /// Returns null if Val is null or not an appropriate constant.
  546. static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
  547. if (!Val)
  548. return nullptr;
  549. // Undef is "known" enough.
  550. if (UndefValue *U = dyn_cast<UndefValue>(Val))
  551. return U;
  552. if (Preference == WantBlockAddress)
  553. return dyn_cast<BlockAddress>(Val->stripPointerCasts());
  554. return dyn_cast<ConstantInt>(Val);
  555. }
  556. /// computeValueKnownInPredecessors - Given a basic block BB and a value V, see
  557. /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
  558. /// in any of our predecessors. If so, return the known list of value and pred
  559. /// BB in the result vector.
  560. ///
  561. /// This returns true if there were any known values.
  562. bool JumpThreadingPass::computeValueKnownInPredecessorsImpl(
  563. Value *V, BasicBlock *BB, PredValueInfo &Result,
  564. ConstantPreference Preference, DenseSet<Value *> &RecursionSet,
  565. Instruction *CxtI) {
  566. // This method walks up use-def chains recursively. Because of this, we could
  567. // get into an infinite loop going around loops in the use-def chain. To
  568. // prevent this, keep track of what (value, block) pairs we've already visited
  569. // and terminate the search if we loop back to them
  570. if (!RecursionSet.insert(V).second)
  571. return false;
  572. // If V is a constant, then it is known in all predecessors.
  573. if (Constant *KC = getKnownConstant(V, Preference)) {
  574. for (BasicBlock *Pred : predecessors(BB))
  575. Result.emplace_back(KC, Pred);
  576. return !Result.empty();
  577. }
  578. // If V is a non-instruction value, or an instruction in a different block,
  579. // then it can't be derived from a PHI.
  580. Instruction *I = dyn_cast<Instruction>(V);
  581. if (!I || I->getParent() != BB) {
  582. // Okay, if this is a live-in value, see if it has a known value at the end
  583. // of any of our predecessors.
  584. //
  585. // FIXME: This should be an edge property, not a block end property.
  586. /// TODO: Per PR2563, we could infer value range information about a
  587. /// predecessor based on its terminator.
  588. //
  589. // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
  590. // "I" is a non-local compare-with-a-constant instruction. This would be
  591. // able to handle value inequalities better, for example if the compare is
  592. // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
  593. // Perhaps getConstantOnEdge should be smart enough to do this?
  594. for (BasicBlock *P : predecessors(BB)) {
  595. // If the value is known by LazyValueInfo to be a constant in a
  596. // predecessor, use that information to try to thread this block.
  597. Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
  598. if (Constant *KC = getKnownConstant(PredCst, Preference))
  599. Result.emplace_back(KC, P);
  600. }
  601. return !Result.empty();
  602. }
  603. /// If I is a PHI node, then we know the incoming values for any constants.
  604. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  605. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  606. Value *InVal = PN->getIncomingValue(i);
  607. if (Constant *KC = getKnownConstant(InVal, Preference)) {
  608. Result.emplace_back(KC, PN->getIncomingBlock(i));
  609. } else {
  610. Constant *CI = LVI->getConstantOnEdge(InVal,
  611. PN->getIncomingBlock(i),
  612. BB, CxtI);
  613. if (Constant *KC = getKnownConstant(CI, Preference))
  614. Result.emplace_back(KC, PN->getIncomingBlock(i));
  615. }
  616. }
  617. return !Result.empty();
  618. }
  619. // Handle Cast instructions.
  620. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  621. Value *Source = CI->getOperand(0);
  622. computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
  623. RecursionSet, CxtI);
  624. if (Result.empty())
  625. return false;
  626. // Convert the known values.
  627. for (auto &R : Result)
  628. R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType());
  629. return true;
  630. }
  631. if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
  632. Value *Source = FI->getOperand(0);
  633. computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
  634. RecursionSet, CxtI);
  635. erase_if(Result, [](auto &Pair) {
  636. return !isGuaranteedNotToBeUndefOrPoison(Pair.first);
  637. });
  638. return !Result.empty();
  639. }
  640. // Handle some boolean conditions.
  641. if (I->getType()->getPrimitiveSizeInBits() == 1) {
  642. using namespace PatternMatch;
  643. if (Preference != WantInteger)
  644. return false;
  645. // X | true -> true
  646. // X & false -> false
  647. Value *Op0, *Op1;
  648. if (match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
  649. match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
  650. PredValueInfoTy LHSVals, RHSVals;
  651. computeValueKnownInPredecessorsImpl(Op0, BB, LHSVals, WantInteger,
  652. RecursionSet, CxtI);
  653. computeValueKnownInPredecessorsImpl(Op1, BB, RHSVals, WantInteger,
  654. RecursionSet, CxtI);
  655. if (LHSVals.empty() && RHSVals.empty())
  656. return false;
  657. ConstantInt *InterestingVal;
  658. if (match(I, m_LogicalOr()))
  659. InterestingVal = ConstantInt::getTrue(I->getContext());
  660. else
  661. InterestingVal = ConstantInt::getFalse(I->getContext());
  662. SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
  663. // Scan for the sentinel. If we find an undef, force it to the
  664. // interesting value: x|undef -> true and x&undef -> false.
  665. for (const auto &LHSVal : LHSVals)
  666. if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
  667. Result.emplace_back(InterestingVal, LHSVal.second);
  668. LHSKnownBBs.insert(LHSVal.second);
  669. }
  670. for (const auto &RHSVal : RHSVals)
  671. if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
  672. // If we already inferred a value for this block on the LHS, don't
  673. // re-add it.
  674. if (!LHSKnownBBs.count(RHSVal.second))
  675. Result.emplace_back(InterestingVal, RHSVal.second);
  676. }
  677. return !Result.empty();
  678. }
  679. // Handle the NOT form of XOR.
  680. if (I->getOpcode() == Instruction::Xor &&
  681. isa<ConstantInt>(I->getOperand(1)) &&
  682. cast<ConstantInt>(I->getOperand(1))->isOne()) {
  683. computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result,
  684. WantInteger, RecursionSet, CxtI);
  685. if (Result.empty())
  686. return false;
  687. // Invert the known values.
  688. for (auto &R : Result)
  689. R.first = ConstantExpr::getNot(R.first);
  690. return true;
  691. }
  692. // Try to simplify some other binary operator values.
  693. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
  694. if (Preference != WantInteger)
  695. return false;
  696. if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
  697. PredValueInfoTy LHSVals;
  698. computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
  699. WantInteger, RecursionSet, CxtI);
  700. // Try to use constant folding to simplify the binary operator.
  701. for (const auto &LHSVal : LHSVals) {
  702. Constant *V = LHSVal.first;
  703. Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
  704. if (Constant *KC = getKnownConstant(Folded, WantInteger))
  705. Result.emplace_back(KC, LHSVal.second);
  706. }
  707. }
  708. return !Result.empty();
  709. }
  710. // Handle compare with phi operand, where the PHI is defined in this block.
  711. if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  712. if (Preference != WantInteger)
  713. return false;
  714. Type *CmpType = Cmp->getType();
  715. Value *CmpLHS = Cmp->getOperand(0);
  716. Value *CmpRHS = Cmp->getOperand(1);
  717. CmpInst::Predicate Pred = Cmp->getPredicate();
  718. PHINode *PN = dyn_cast<PHINode>(CmpLHS);
  719. if (!PN)
  720. PN = dyn_cast<PHINode>(CmpRHS);
  721. if (PN && PN->getParent() == BB) {
  722. const DataLayout &DL = PN->getModule()->getDataLayout();
  723. // We can do this simplification if any comparisons fold to true or false.
  724. // See if any do.
  725. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  726. BasicBlock *PredBB = PN->getIncomingBlock(i);
  727. Value *LHS, *RHS;
  728. if (PN == CmpLHS) {
  729. LHS = PN->getIncomingValue(i);
  730. RHS = CmpRHS->DoPHITranslation(BB, PredBB);
  731. } else {
  732. LHS = CmpLHS->DoPHITranslation(BB, PredBB);
  733. RHS = PN->getIncomingValue(i);
  734. }
  735. Value *Res = SimplifyCmpInst(Pred, LHS, RHS, {DL});
  736. if (!Res) {
  737. if (!isa<Constant>(RHS))
  738. continue;
  739. // getPredicateOnEdge call will make no sense if LHS is defined in BB.
  740. auto LHSInst = dyn_cast<Instruction>(LHS);
  741. if (LHSInst && LHSInst->getParent() == BB)
  742. continue;
  743. LazyValueInfo::Tristate
  744. ResT = LVI->getPredicateOnEdge(Pred, LHS,
  745. cast<Constant>(RHS), PredBB, BB,
  746. CxtI ? CxtI : Cmp);
  747. if (ResT == LazyValueInfo::Unknown)
  748. continue;
  749. Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
  750. }
  751. if (Constant *KC = getKnownConstant(Res, WantInteger))
  752. Result.emplace_back(KC, PredBB);
  753. }
  754. return !Result.empty();
  755. }
  756. // If comparing a live-in value against a constant, see if we know the
  757. // live-in value on any predecessors.
  758. if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) {
  759. Constant *CmpConst = cast<Constant>(CmpRHS);
  760. if (!isa<Instruction>(CmpLHS) ||
  761. cast<Instruction>(CmpLHS)->getParent() != BB) {
  762. for (BasicBlock *P : predecessors(BB)) {
  763. // If the value is known by LazyValueInfo to be a constant in a
  764. // predecessor, use that information to try to thread this block.
  765. LazyValueInfo::Tristate Res =
  766. LVI->getPredicateOnEdge(Pred, CmpLHS,
  767. CmpConst, P, BB, CxtI ? CxtI : Cmp);
  768. if (Res == LazyValueInfo::Unknown)
  769. continue;
  770. Constant *ResC = ConstantInt::get(CmpType, Res);
  771. Result.emplace_back(ResC, P);
  772. }
  773. return !Result.empty();
  774. }
  775. // InstCombine can fold some forms of constant range checks into
  776. // (icmp (add (x, C1)), C2). See if we have we have such a thing with
  777. // x as a live-in.
  778. {
  779. using namespace PatternMatch;
  780. Value *AddLHS;
  781. ConstantInt *AddConst;
  782. if (isa<ConstantInt>(CmpConst) &&
  783. match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
  784. if (!isa<Instruction>(AddLHS) ||
  785. cast<Instruction>(AddLHS)->getParent() != BB) {
  786. for (BasicBlock *P : predecessors(BB)) {
  787. // If the value is known by LazyValueInfo to be a ConstantRange in
  788. // a predecessor, use that information to try to thread this
  789. // block.
  790. ConstantRange CR = LVI->getConstantRangeOnEdge(
  791. AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
  792. // Propagate the range through the addition.
  793. CR = CR.add(AddConst->getValue());
  794. // Get the range where the compare returns true.
  795. ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
  796. Pred, cast<ConstantInt>(CmpConst)->getValue());
  797. Constant *ResC;
  798. if (CmpRange.contains(CR))
  799. ResC = ConstantInt::getTrue(CmpType);
  800. else if (CmpRange.inverse().contains(CR))
  801. ResC = ConstantInt::getFalse(CmpType);
  802. else
  803. continue;
  804. Result.emplace_back(ResC, P);
  805. }
  806. return !Result.empty();
  807. }
  808. }
  809. }
  810. // Try to find a constant value for the LHS of a comparison,
  811. // and evaluate it statically if we can.
  812. PredValueInfoTy LHSVals;
  813. computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
  814. WantInteger, RecursionSet, CxtI);
  815. for (const auto &LHSVal : LHSVals) {
  816. Constant *V = LHSVal.first;
  817. Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst);
  818. if (Constant *KC = getKnownConstant(Folded, WantInteger))
  819. Result.emplace_back(KC, LHSVal.second);
  820. }
  821. return !Result.empty();
  822. }
  823. }
  824. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  825. // Handle select instructions where at least one operand is a known constant
  826. // and we can figure out the condition value for any predecessor block.
  827. Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
  828. Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
  829. PredValueInfoTy Conds;
  830. if ((TrueVal || FalseVal) &&
  831. computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds,
  832. WantInteger, RecursionSet, CxtI)) {
  833. for (auto &C : Conds) {
  834. Constant *Cond = C.first;
  835. // Figure out what value to use for the condition.
  836. bool KnownCond;
  837. if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
  838. // A known boolean.
  839. KnownCond = CI->isOne();
  840. } else {
  841. assert(isa<UndefValue>(Cond) && "Unexpected condition value");
  842. // Either operand will do, so be sure to pick the one that's a known
  843. // constant.
  844. // FIXME: Do this more cleverly if both values are known constants?
  845. KnownCond = (TrueVal != nullptr);
  846. }
  847. // See if the select has a known constant value for this predecessor.
  848. if (Constant *Val = KnownCond ? TrueVal : FalseVal)
  849. Result.emplace_back(Val, C.second);
  850. }
  851. return !Result.empty();
  852. }
  853. }
  854. // If all else fails, see if LVI can figure out a constant value for us.
  855. assert(CxtI->getParent() == BB && "CxtI should be in BB");
  856. Constant *CI = LVI->getConstant(V, CxtI);
  857. if (Constant *KC = getKnownConstant(CI, Preference)) {
  858. for (BasicBlock *Pred : predecessors(BB))
  859. Result.emplace_back(KC, Pred);
  860. }
  861. return !Result.empty();
  862. }
  863. /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
  864. /// in an undefined jump, decide which block is best to revector to.
  865. ///
  866. /// Since we can pick an arbitrary destination, we pick the successor with the
  867. /// fewest predecessors. This should reduce the in-degree of the others.
  868. static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) {
  869. Instruction *BBTerm = BB->getTerminator();
  870. unsigned MinSucc = 0;
  871. BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
  872. // Compute the successor with the minimum number of predecessors.
  873. unsigned MinNumPreds = pred_size(TestBB);
  874. for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
  875. TestBB = BBTerm->getSuccessor(i);
  876. unsigned NumPreds = pred_size(TestBB);
  877. if (NumPreds < MinNumPreds) {
  878. MinSucc = i;
  879. MinNumPreds = NumPreds;
  880. }
  881. }
  882. return MinSucc;
  883. }
  884. static bool hasAddressTakenAndUsed(BasicBlock *BB) {
  885. if (!BB->hasAddressTaken()) return false;
  886. // If the block has its address taken, it may be a tree of dead constants
  887. // hanging off of it. These shouldn't keep the block alive.
  888. BlockAddress *BA = BlockAddress::get(BB);
  889. BA->removeDeadConstantUsers();
  890. return !BA->use_empty();
  891. }
  892. /// processBlock - If there are any predecessors whose control can be threaded
  893. /// through to a successor, transform them now.
  894. bool JumpThreadingPass::processBlock(BasicBlock *BB) {
  895. // If the block is trivially dead, just return and let the caller nuke it.
  896. // This simplifies other transformations.
  897. if (DTU->isBBPendingDeletion(BB) ||
  898. (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()))
  899. return false;
  900. // If this block has a single predecessor, and if that pred has a single
  901. // successor, merge the blocks. This encourages recursive jump threading
  902. // because now the condition in this block can be threaded through
  903. // predecessors of our predecessor block.
  904. if (maybeMergeBasicBlockIntoOnlyPred(BB))
  905. return true;
  906. if (tryToUnfoldSelectInCurrBB(BB))
  907. return true;
  908. // Look if we can propagate guards to predecessors.
  909. if (HasGuards && processGuards(BB))
  910. return true;
  911. // What kind of constant we're looking for.
  912. ConstantPreference Preference = WantInteger;
  913. // Look to see if the terminator is a conditional branch, switch or indirect
  914. // branch, if not we can't thread it.
  915. Value *Condition;
  916. Instruction *Terminator = BB->getTerminator();
  917. if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
  918. // Can't thread an unconditional jump.
  919. if (BI->isUnconditional()) return false;
  920. Condition = BI->getCondition();
  921. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
  922. Condition = SI->getCondition();
  923. } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
  924. // Can't thread indirect branch with no successors.
  925. if (IB->getNumSuccessors() == 0) return false;
  926. Condition = IB->getAddress()->stripPointerCasts();
  927. Preference = WantBlockAddress;
  928. } else {
  929. return false; // Must be an invoke or callbr.
  930. }
  931. // Keep track if we constant folded the condition in this invocation.
  932. bool ConstantFolded = false;
  933. // Run constant folding to see if we can reduce the condition to a simple
  934. // constant.
  935. if (Instruction *I = dyn_cast<Instruction>(Condition)) {
  936. Value *SimpleVal =
  937. ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
  938. if (SimpleVal) {
  939. I->replaceAllUsesWith(SimpleVal);
  940. if (isInstructionTriviallyDead(I, TLI))
  941. I->eraseFromParent();
  942. Condition = SimpleVal;
  943. ConstantFolded = true;
  944. }
  945. }
  946. // If the terminator is branching on an undef or freeze undef, we can pick any
  947. // of the successors to branch to. Let getBestDestForJumpOnUndef decide.
  948. auto *FI = dyn_cast<FreezeInst>(Condition);
  949. if (isa<UndefValue>(Condition) ||
  950. (FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) {
  951. unsigned BestSucc = getBestDestForJumpOnUndef(BB);
  952. std::vector<DominatorTree::UpdateType> Updates;
  953. // Fold the branch/switch.
  954. Instruction *BBTerm = BB->getTerminator();
  955. Updates.reserve(BBTerm->getNumSuccessors());
  956. for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
  957. if (i == BestSucc) continue;
  958. BasicBlock *Succ = BBTerm->getSuccessor(i);
  959. Succ->removePredecessor(BB, true);
  960. Updates.push_back({DominatorTree::Delete, BB, Succ});
  961. }
  962. LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
  963. << "' folding undef terminator: " << *BBTerm << '\n');
  964. BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
  965. ++NumFolds;
  966. BBTerm->eraseFromParent();
  967. DTU->applyUpdatesPermissive(Updates);
  968. if (FI)
  969. FI->eraseFromParent();
  970. return true;
  971. }
  972. // If the terminator of this block is branching on a constant, simplify the
  973. // terminator to an unconditional branch. This can occur due to threading in
  974. // other blocks.
  975. if (getKnownConstant(Condition, Preference)) {
  976. LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
  977. << "' folding terminator: " << *BB->getTerminator()
  978. << '\n');
  979. ++NumFolds;
  980. ConstantFoldTerminator(BB, true, nullptr, DTU);
  981. if (HasProfileData)
  982. BPI->eraseBlock(BB);
  983. return true;
  984. }
  985. Instruction *CondInst = dyn_cast<Instruction>(Condition);
  986. // All the rest of our checks depend on the condition being an instruction.
  987. if (!CondInst) {
  988. // FIXME: Unify this with code below.
  989. if (processThreadableEdges(Condition, BB, Preference, Terminator))
  990. return true;
  991. return ConstantFolded;
  992. }
  993. if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
  994. // If we're branching on a conditional, LVI might be able to determine
  995. // it's value at the branch instruction. We only handle comparisons
  996. // against a constant at this time.
  997. // TODO: This should be extended to handle switches as well.
  998. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  999. Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
  1000. if (CondBr && CondConst) {
  1001. // We should have returned as soon as we turn a conditional branch to
  1002. // unconditional. Because its no longer interesting as far as jump
  1003. // threading is concerned.
  1004. assert(CondBr->isConditional() && "Threading on unconditional terminator");
  1005. LazyValueInfo::Tristate Ret =
  1006. LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
  1007. CondConst, CondBr, /*UseBlockValue=*/false);
  1008. if (Ret != LazyValueInfo::Unknown) {
  1009. unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0;
  1010. unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1;
  1011. BasicBlock *ToRemoveSucc = CondBr->getSuccessor(ToRemove);
  1012. ToRemoveSucc->removePredecessor(BB, true);
  1013. BranchInst *UncondBr =
  1014. BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
  1015. UncondBr->setDebugLoc(CondBr->getDebugLoc());
  1016. ++NumFolds;
  1017. CondBr->eraseFromParent();
  1018. if (CondCmp->use_empty())
  1019. CondCmp->eraseFromParent();
  1020. // We can safely replace *some* uses of the CondInst if it has
  1021. // exactly one value as returned by LVI. RAUW is incorrect in the
  1022. // presence of guards and assumes, that have the `Cond` as the use. This
  1023. // is because we use the guards/assume to reason about the `Cond` value
  1024. // at the end of block, but RAUW unconditionally replaces all uses
  1025. // including the guards/assumes themselves and the uses before the
  1026. // guard/assume.
  1027. else if (CondCmp->getParent() == BB) {
  1028. auto *CI = Ret == LazyValueInfo::True ?
  1029. ConstantInt::getTrue(CondCmp->getType()) :
  1030. ConstantInt::getFalse(CondCmp->getType());
  1031. replaceFoldableUses(CondCmp, CI);
  1032. }
  1033. DTU->applyUpdatesPermissive(
  1034. {{DominatorTree::Delete, BB, ToRemoveSucc}});
  1035. if (HasProfileData)
  1036. BPI->eraseBlock(BB);
  1037. return true;
  1038. }
  1039. // We did not manage to simplify this branch, try to see whether
  1040. // CondCmp depends on a known phi-select pattern.
  1041. if (tryToUnfoldSelect(CondCmp, BB))
  1042. return true;
  1043. }
  1044. }
  1045. if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
  1046. if (tryToUnfoldSelect(SI, BB))
  1047. return true;
  1048. // Check for some cases that are worth simplifying. Right now we want to look
  1049. // for loads that are used by a switch or by the condition for the branch. If
  1050. // we see one, check to see if it's partially redundant. If so, insert a PHI
  1051. // which can then be used to thread the values.
  1052. Value *SimplifyValue = CondInst;
  1053. if (auto *FI = dyn_cast<FreezeInst>(SimplifyValue))
  1054. // Look into freeze's operand
  1055. SimplifyValue = FI->getOperand(0);
  1056. if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
  1057. if (isa<Constant>(CondCmp->getOperand(1)))
  1058. SimplifyValue = CondCmp->getOperand(0);
  1059. // TODO: There are other places where load PRE would be profitable, such as
  1060. // more complex comparisons.
  1061. if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
  1062. if (simplifyPartiallyRedundantLoad(LoadI))
  1063. return true;
  1064. // Before threading, try to propagate profile data backwards:
  1065. if (PHINode *PN = dyn_cast<PHINode>(CondInst))
  1066. if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
  1067. updatePredecessorProfileMetadata(PN, BB);
  1068. // Handle a variety of cases where we are branching on something derived from
  1069. // a PHI node in the current block. If we can prove that any predecessors
  1070. // compute a predictable value based on a PHI node, thread those predecessors.
  1071. if (processThreadableEdges(CondInst, BB, Preference, Terminator))
  1072. return true;
  1073. // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in
  1074. // the current block, see if we can simplify.
  1075. PHINode *PN = dyn_cast<PHINode>(
  1076. isa<FreezeInst>(CondInst) ? cast<FreezeInst>(CondInst)->getOperand(0)
  1077. : CondInst);
  1078. if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
  1079. return processBranchOnPHI(PN);
  1080. // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
  1081. if (CondInst->getOpcode() == Instruction::Xor &&
  1082. CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
  1083. return processBranchOnXOR(cast<BinaryOperator>(CondInst));
  1084. // Search for a stronger dominating condition that can be used to simplify a
  1085. // conditional branch leaving BB.
  1086. if (processImpliedCondition(BB))
  1087. return true;
  1088. return false;
  1089. }
  1090. bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) {
  1091. auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
  1092. if (!BI || !BI->isConditional())
  1093. return false;
  1094. Value *Cond = BI->getCondition();
  1095. BasicBlock *CurrentBB = BB;
  1096. BasicBlock *CurrentPred = BB->getSinglePredecessor();
  1097. unsigned Iter = 0;
  1098. auto &DL = BB->getModule()->getDataLayout();
  1099. while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
  1100. auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
  1101. if (!PBI || !PBI->isConditional())
  1102. return false;
  1103. if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
  1104. return false;
  1105. bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB;
  1106. Optional<bool> Implication =
  1107. isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue);
  1108. if (Implication) {
  1109. BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
  1110. BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
  1111. RemoveSucc->removePredecessor(BB);
  1112. BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI);
  1113. UncondBI->setDebugLoc(BI->getDebugLoc());
  1114. ++NumFolds;
  1115. BI->eraseFromParent();
  1116. DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}});
  1117. if (HasProfileData)
  1118. BPI->eraseBlock(BB);
  1119. return true;
  1120. }
  1121. CurrentBB = CurrentPred;
  1122. CurrentPred = CurrentBB->getSinglePredecessor();
  1123. }
  1124. return false;
  1125. }
  1126. /// Return true if Op is an instruction defined in the given block.
  1127. static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
  1128. if (Instruction *OpInst = dyn_cast<Instruction>(Op))
  1129. if (OpInst->getParent() == BB)
  1130. return true;
  1131. return false;
  1132. }
  1133. /// simplifyPartiallyRedundantLoad - If LoadI is an obviously partially
  1134. /// redundant load instruction, eliminate it by replacing it with a PHI node.
  1135. /// This is an important optimization that encourages jump threading, and needs
  1136. /// to be run interlaced with other jump threading tasks.
  1137. bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) {
  1138. // Don't hack volatile and ordered loads.
  1139. if (!LoadI->isUnordered()) return false;
  1140. // If the load is defined in a block with exactly one predecessor, it can't be
  1141. // partially redundant.
  1142. BasicBlock *LoadBB = LoadI->getParent();
  1143. if (LoadBB->getSinglePredecessor())
  1144. return false;
  1145. // If the load is defined in an EH pad, it can't be partially redundant,
  1146. // because the edges between the invoke and the EH pad cannot have other
  1147. // instructions between them.
  1148. if (LoadBB->isEHPad())
  1149. return false;
  1150. Value *LoadedPtr = LoadI->getOperand(0);
  1151. // If the loaded operand is defined in the LoadBB and its not a phi,
  1152. // it can't be available in predecessors.
  1153. if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
  1154. return false;
  1155. // Scan a few instructions up from the load, to see if it is obviously live at
  1156. // the entry to its block.
  1157. BasicBlock::iterator BBIt(LoadI);
  1158. bool IsLoadCSE;
  1159. if (Value *AvailableVal = FindAvailableLoadedValue(
  1160. LoadI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) {
  1161. // If the value of the load is locally available within the block, just use
  1162. // it. This frequently occurs for reg2mem'd allocas.
  1163. if (IsLoadCSE) {
  1164. LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
  1165. combineMetadataForCSE(NLoadI, LoadI, false);
  1166. };
  1167. // If the returned value is the load itself, replace with an undef. This can
  1168. // only happen in dead loops.
  1169. if (AvailableVal == LoadI)
  1170. AvailableVal = UndefValue::get(LoadI->getType());
  1171. if (AvailableVal->getType() != LoadI->getType())
  1172. AvailableVal = CastInst::CreateBitOrPointerCast(
  1173. AvailableVal, LoadI->getType(), "", LoadI);
  1174. LoadI->replaceAllUsesWith(AvailableVal);
  1175. LoadI->eraseFromParent();
  1176. return true;
  1177. }
  1178. // Otherwise, if we scanned the whole block and got to the top of the block,
  1179. // we know the block is locally transparent to the load. If not, something
  1180. // might clobber its value.
  1181. if (BBIt != LoadBB->begin())
  1182. return false;
  1183. // If all of the loads and stores that feed the value have the same AA tags,
  1184. // then we can propagate them onto any newly inserted loads.
  1185. AAMDNodes AATags = LoadI->getAAMetadata();
  1186. SmallPtrSet<BasicBlock*, 8> PredsScanned;
  1187. using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>;
  1188. AvailablePredsTy AvailablePreds;
  1189. BasicBlock *OneUnavailablePred = nullptr;
  1190. SmallVector<LoadInst*, 8> CSELoads;
  1191. // If we got here, the loaded value is transparent through to the start of the
  1192. // block. Check to see if it is available in any of the predecessor blocks.
  1193. for (BasicBlock *PredBB : predecessors(LoadBB)) {
  1194. // If we already scanned this predecessor, skip it.
  1195. if (!PredsScanned.insert(PredBB).second)
  1196. continue;
  1197. BBIt = PredBB->end();
  1198. unsigned NumScanedInst = 0;
  1199. Value *PredAvailable = nullptr;
  1200. // NOTE: We don't CSE load that is volatile or anything stronger than
  1201. // unordered, that should have been checked when we entered the function.
  1202. assert(LoadI->isUnordered() &&
  1203. "Attempting to CSE volatile or atomic loads");
  1204. // If this is a load on a phi pointer, phi-translate it and search
  1205. // for available load/store to the pointer in predecessors.
  1206. Type *AccessTy = LoadI->getType();
  1207. const auto &DL = LoadI->getModule()->getDataLayout();
  1208. MemoryLocation Loc(LoadedPtr->DoPHITranslation(LoadBB, PredBB),
  1209. LocationSize::precise(DL.getTypeStoreSize(AccessTy)),
  1210. AATags);
  1211. PredAvailable = findAvailablePtrLoadStore(Loc, AccessTy, LoadI->isAtomic(),
  1212. PredBB, BBIt, DefMaxInstsToScan,
  1213. AA, &IsLoadCSE, &NumScanedInst);
  1214. // If PredBB has a single predecessor, continue scanning through the
  1215. // single predecessor.
  1216. BasicBlock *SinglePredBB = PredBB;
  1217. while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
  1218. NumScanedInst < DefMaxInstsToScan) {
  1219. SinglePredBB = SinglePredBB->getSinglePredecessor();
  1220. if (SinglePredBB) {
  1221. BBIt = SinglePredBB->end();
  1222. PredAvailable = findAvailablePtrLoadStore(
  1223. Loc, AccessTy, LoadI->isAtomic(), SinglePredBB, BBIt,
  1224. (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
  1225. &NumScanedInst);
  1226. }
  1227. }
  1228. if (!PredAvailable) {
  1229. OneUnavailablePred = PredBB;
  1230. continue;
  1231. }
  1232. if (IsLoadCSE)
  1233. CSELoads.push_back(cast<LoadInst>(PredAvailable));
  1234. // If so, this load is partially redundant. Remember this info so that we
  1235. // can create a PHI node.
  1236. AvailablePreds.emplace_back(PredBB, PredAvailable);
  1237. }
  1238. // If the loaded value isn't available in any predecessor, it isn't partially
  1239. // redundant.
  1240. if (AvailablePreds.empty()) return false;
  1241. // Okay, the loaded value is available in at least one (and maybe all!)
  1242. // predecessors. If the value is unavailable in more than one unique
  1243. // predecessor, we want to insert a merge block for those common predecessors.
  1244. // This ensures that we only have to insert one reload, thus not increasing
  1245. // code size.
  1246. BasicBlock *UnavailablePred = nullptr;
  1247. // If the value is unavailable in one of predecessors, we will end up
  1248. // inserting a new instruction into them. It is only valid if all the
  1249. // instructions before LoadI are guaranteed to pass execution to its
  1250. // successor, or if LoadI is safe to speculate.
  1251. // TODO: If this logic becomes more complex, and we will perform PRE insertion
  1252. // farther than to a predecessor, we need to reuse the code from GVN's PRE.
  1253. // It requires domination tree analysis, so for this simple case it is an
  1254. // overkill.
  1255. if (PredsScanned.size() != AvailablePreds.size() &&
  1256. !isSafeToSpeculativelyExecute(LoadI))
  1257. for (auto I = LoadBB->begin(); &*I != LoadI; ++I)
  1258. if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
  1259. return false;
  1260. // If there is exactly one predecessor where the value is unavailable, the
  1261. // already computed 'OneUnavailablePred' block is it. If it ends in an
  1262. // unconditional branch, we know that it isn't a critical edge.
  1263. if (PredsScanned.size() == AvailablePreds.size()+1 &&
  1264. OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
  1265. UnavailablePred = OneUnavailablePred;
  1266. } else if (PredsScanned.size() != AvailablePreds.size()) {
  1267. // Otherwise, we had multiple unavailable predecessors or we had a critical
  1268. // edge from the one.
  1269. SmallVector<BasicBlock*, 8> PredsToSplit;
  1270. SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
  1271. for (const auto &AvailablePred : AvailablePreds)
  1272. AvailablePredSet.insert(AvailablePred.first);
  1273. // Add all the unavailable predecessors to the PredsToSplit list.
  1274. for (BasicBlock *P : predecessors(LoadBB)) {
  1275. // If the predecessor is an indirect goto, we can't split the edge.
  1276. // Same for CallBr.
  1277. if (isa<IndirectBrInst>(P->getTerminator()) ||
  1278. isa<CallBrInst>(P->getTerminator()))
  1279. return false;
  1280. if (!AvailablePredSet.count(P))
  1281. PredsToSplit.push_back(P);
  1282. }
  1283. // Split them out to their own block.
  1284. UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
  1285. }
  1286. // If the value isn't available in all predecessors, then there will be
  1287. // exactly one where it isn't available. Insert a load on that edge and add
  1288. // it to the AvailablePreds list.
  1289. if (UnavailablePred) {
  1290. assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
  1291. "Can't handle critical edge here!");
  1292. LoadInst *NewVal = new LoadInst(
  1293. LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
  1294. LoadI->getName() + ".pr", false, LoadI->getAlign(),
  1295. LoadI->getOrdering(), LoadI->getSyncScopeID(),
  1296. UnavailablePred->getTerminator());
  1297. NewVal->setDebugLoc(LoadI->getDebugLoc());
  1298. if (AATags)
  1299. NewVal->setAAMetadata(AATags);
  1300. AvailablePreds.emplace_back(UnavailablePred, NewVal);
  1301. }
  1302. // Now we know that each predecessor of this block has a value in
  1303. // AvailablePreds, sort them for efficient access as we're walking the preds.
  1304. array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
  1305. // Create a PHI node at the start of the block for the PRE'd load value.
  1306. pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
  1307. PHINode *PN = PHINode::Create(LoadI->getType(), std::distance(PB, PE), "",
  1308. &LoadBB->front());
  1309. PN->takeName(LoadI);
  1310. PN->setDebugLoc(LoadI->getDebugLoc());
  1311. // Insert new entries into the PHI for each predecessor. A single block may
  1312. // have multiple entries here.
  1313. for (pred_iterator PI = PB; PI != PE; ++PI) {
  1314. BasicBlock *P = *PI;
  1315. AvailablePredsTy::iterator I =
  1316. llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr));
  1317. assert(I != AvailablePreds.end() && I->first == P &&
  1318. "Didn't find entry for predecessor!");
  1319. // If we have an available predecessor but it requires casting, insert the
  1320. // cast in the predecessor and use the cast. Note that we have to update the
  1321. // AvailablePreds vector as we go so that all of the PHI entries for this
  1322. // predecessor use the same bitcast.
  1323. Value *&PredV = I->second;
  1324. if (PredV->getType() != LoadI->getType())
  1325. PredV = CastInst::CreateBitOrPointerCast(PredV, LoadI->getType(), "",
  1326. P->getTerminator());
  1327. PN->addIncoming(PredV, I->first);
  1328. }
  1329. for (LoadInst *PredLoadI : CSELoads) {
  1330. combineMetadataForCSE(PredLoadI, LoadI, true);
  1331. }
  1332. LoadI->replaceAllUsesWith(PN);
  1333. LoadI->eraseFromParent();
  1334. return true;
  1335. }
  1336. /// findMostPopularDest - The specified list contains multiple possible
  1337. /// threadable destinations. Pick the one that occurs the most frequently in
  1338. /// the list.
  1339. static BasicBlock *
  1340. findMostPopularDest(BasicBlock *BB,
  1341. const SmallVectorImpl<std::pair<BasicBlock *,
  1342. BasicBlock *>> &PredToDestList) {
  1343. assert(!PredToDestList.empty());
  1344. // Determine popularity. If there are multiple possible destinations, we
  1345. // explicitly choose to ignore 'undef' destinations. We prefer to thread
  1346. // blocks with known and real destinations to threading undef. We'll handle
  1347. // them later if interesting.
  1348. MapVector<BasicBlock *, unsigned> DestPopularity;
  1349. // Populate DestPopularity with the successors in the order they appear in the
  1350. // successor list. This way, we ensure determinism by iterating it in the
  1351. // same order in std::max_element below. We map nullptr to 0 so that we can
  1352. // return nullptr when PredToDestList contains nullptr only.
  1353. DestPopularity[nullptr] = 0;
  1354. for (auto *SuccBB : successors(BB))
  1355. DestPopularity[SuccBB] = 0;
  1356. for (const auto &PredToDest : PredToDestList)
  1357. if (PredToDest.second)
  1358. DestPopularity[PredToDest.second]++;
  1359. // Find the most popular dest.
  1360. using VT = decltype(DestPopularity)::value_type;
  1361. auto MostPopular = std::max_element(
  1362. DestPopularity.begin(), DestPopularity.end(),
  1363. [](const VT &L, const VT &R) { return L.second < R.second; });
  1364. // Okay, we have finally picked the most popular destination.
  1365. return MostPopular->first;
  1366. }
  1367. // Try to evaluate the value of V when the control flows from PredPredBB to
  1368. // BB->getSinglePredecessor() and then on to BB.
  1369. Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB,
  1370. BasicBlock *PredPredBB,
  1371. Value *V) {
  1372. BasicBlock *PredBB = BB->getSinglePredecessor();
  1373. assert(PredBB && "Expected a single predecessor");
  1374. if (Constant *Cst = dyn_cast<Constant>(V)) {
  1375. return Cst;
  1376. }
  1377. // Consult LVI if V is not an instruction in BB or PredBB.
  1378. Instruction *I = dyn_cast<Instruction>(V);
  1379. if (!I || (I->getParent() != BB && I->getParent() != PredBB)) {
  1380. return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr);
  1381. }
  1382. // Look into a PHI argument.
  1383. if (PHINode *PHI = dyn_cast<PHINode>(V)) {
  1384. if (PHI->getParent() == PredBB)
  1385. return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB));
  1386. return nullptr;
  1387. }
  1388. // If we have a CmpInst, try to fold it for each incoming edge into PredBB.
  1389. if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) {
  1390. if (CondCmp->getParent() == BB) {
  1391. Constant *Op0 =
  1392. evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0));
  1393. Constant *Op1 =
  1394. evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1));
  1395. if (Op0 && Op1) {
  1396. return ConstantExpr::getCompare(CondCmp->getPredicate(), Op0, Op1);
  1397. }
  1398. }
  1399. return nullptr;
  1400. }
  1401. return nullptr;
  1402. }
  1403. bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB,
  1404. ConstantPreference Preference,
  1405. Instruction *CxtI) {
  1406. // If threading this would thread across a loop header, don't even try to
  1407. // thread the edge.
  1408. if (LoopHeaders.count(BB))
  1409. return false;
  1410. PredValueInfoTy PredValues;
  1411. if (!computeValueKnownInPredecessors(Cond, BB, PredValues, Preference,
  1412. CxtI)) {
  1413. // We don't have known values in predecessors. See if we can thread through
  1414. // BB and its sole predecessor.
  1415. return maybethreadThroughTwoBasicBlocks(BB, Cond);
  1416. }
  1417. assert(!PredValues.empty() &&
  1418. "computeValueKnownInPredecessors returned true with no values");
  1419. LLVM_DEBUG(dbgs() << "IN BB: " << *BB;
  1420. for (const auto &PredValue : PredValues) {
  1421. dbgs() << " BB '" << BB->getName()
  1422. << "': FOUND condition = " << *PredValue.first
  1423. << " for pred '" << PredValue.second->getName() << "'.\n";
  1424. });
  1425. // Decide what we want to thread through. Convert our list of known values to
  1426. // a list of known destinations for each pred. This also discards duplicate
  1427. // predecessors and keeps track of the undefined inputs (which are represented
  1428. // as a null dest in the PredToDestList).
  1429. SmallPtrSet<BasicBlock*, 16> SeenPreds;
  1430. SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
  1431. BasicBlock *OnlyDest = nullptr;
  1432. BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
  1433. Constant *OnlyVal = nullptr;
  1434. Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
  1435. for (const auto &PredValue : PredValues) {
  1436. BasicBlock *Pred = PredValue.second;
  1437. if (!SeenPreds.insert(Pred).second)
  1438. continue; // Duplicate predecessor entry.
  1439. Constant *Val = PredValue.first;
  1440. BasicBlock *DestBB;
  1441. if (isa<UndefValue>(Val))
  1442. DestBB = nullptr;
  1443. else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
  1444. assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
  1445. DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
  1446. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  1447. assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
  1448. DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
  1449. } else {
  1450. assert(isa<IndirectBrInst>(BB->getTerminator())
  1451. && "Unexpected terminator");
  1452. assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress");
  1453. DestBB = cast<BlockAddress>(Val)->getBasicBlock();
  1454. }
  1455. // If we have exactly one destination, remember it for efficiency below.
  1456. if (PredToDestList.empty()) {
  1457. OnlyDest = DestBB;
  1458. OnlyVal = Val;
  1459. } else {
  1460. if (OnlyDest != DestBB)
  1461. OnlyDest = MultipleDestSentinel;
  1462. // It possible we have same destination, but different value, e.g. default
  1463. // case in switchinst.
  1464. if (Val != OnlyVal)
  1465. OnlyVal = MultipleVal;
  1466. }
  1467. // If the predecessor ends with an indirect goto, we can't change its
  1468. // destination. Same for CallBr.
  1469. if (isa<IndirectBrInst>(Pred->getTerminator()) ||
  1470. isa<CallBrInst>(Pred->getTerminator()))
  1471. continue;
  1472. PredToDestList.emplace_back(Pred, DestBB);
  1473. }
  1474. // If all edges were unthreadable, we fail.
  1475. if (PredToDestList.empty())
  1476. return false;
  1477. // If all the predecessors go to a single known successor, we want to fold,
  1478. // not thread. By doing so, we do not need to duplicate the current block and
  1479. // also miss potential opportunities in case we dont/cant duplicate.
  1480. if (OnlyDest && OnlyDest != MultipleDestSentinel) {
  1481. if (BB->hasNPredecessors(PredToDestList.size())) {
  1482. bool SeenFirstBranchToOnlyDest = false;
  1483. std::vector <DominatorTree::UpdateType> Updates;
  1484. Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1);
  1485. for (BasicBlock *SuccBB : successors(BB)) {
  1486. if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
  1487. SeenFirstBranchToOnlyDest = true; // Don't modify the first branch.
  1488. } else {
  1489. SuccBB->removePredecessor(BB, true); // This is unreachable successor.
  1490. Updates.push_back({DominatorTree::Delete, BB, SuccBB});
  1491. }
  1492. }
  1493. // Finally update the terminator.
  1494. Instruction *Term = BB->getTerminator();
  1495. BranchInst::Create(OnlyDest, Term);
  1496. ++NumFolds;
  1497. Term->eraseFromParent();
  1498. DTU->applyUpdatesPermissive(Updates);
  1499. if (HasProfileData)
  1500. BPI->eraseBlock(BB);
  1501. // If the condition is now dead due to the removal of the old terminator,
  1502. // erase it.
  1503. if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
  1504. if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
  1505. CondInst->eraseFromParent();
  1506. // We can safely replace *some* uses of the CondInst if it has
  1507. // exactly one value as returned by LVI. RAUW is incorrect in the
  1508. // presence of guards and assumes, that have the `Cond` as the use. This
  1509. // is because we use the guards/assume to reason about the `Cond` value
  1510. // at the end of block, but RAUW unconditionally replaces all uses
  1511. // including the guards/assumes themselves and the uses before the
  1512. // guard/assume.
  1513. else if (OnlyVal && OnlyVal != MultipleVal &&
  1514. CondInst->getParent() == BB)
  1515. replaceFoldableUses(CondInst, OnlyVal);
  1516. }
  1517. return true;
  1518. }
  1519. }
  1520. // Determine which is the most common successor. If we have many inputs and
  1521. // this block is a switch, we want to start by threading the batch that goes
  1522. // to the most popular destination first. If we only know about one
  1523. // threadable destination (the common case) we can avoid this.
  1524. BasicBlock *MostPopularDest = OnlyDest;
  1525. if (MostPopularDest == MultipleDestSentinel) {
  1526. // Remove any loop headers from the Dest list, threadEdge conservatively
  1527. // won't process them, but we might have other destination that are eligible
  1528. // and we still want to process.
  1529. erase_if(PredToDestList,
  1530. [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
  1531. return LoopHeaders.contains(PredToDest.second);
  1532. });
  1533. if (PredToDestList.empty())
  1534. return false;
  1535. MostPopularDest = findMostPopularDest(BB, PredToDestList);
  1536. }
  1537. // Now that we know what the most popular destination is, factor all
  1538. // predecessors that will jump to it into a single predecessor.
  1539. SmallVector<BasicBlock*, 16> PredsToFactor;
  1540. for (const auto &PredToDest : PredToDestList)
  1541. if (PredToDest.second == MostPopularDest) {
  1542. BasicBlock *Pred = PredToDest.first;
  1543. // This predecessor may be a switch or something else that has multiple
  1544. // edges to the block. Factor each of these edges by listing them
  1545. // according to # occurrences in PredsToFactor.
  1546. for (BasicBlock *Succ : successors(Pred))
  1547. if (Succ == BB)
  1548. PredsToFactor.push_back(Pred);
  1549. }
  1550. // If the threadable edges are branching on an undefined value, we get to pick
  1551. // the destination that these predecessors should get to.
  1552. if (!MostPopularDest)
  1553. MostPopularDest = BB->getTerminator()->
  1554. getSuccessor(getBestDestForJumpOnUndef(BB));
  1555. // Ok, try to thread it!
  1556. return tryThreadEdge(BB, PredsToFactor, MostPopularDest);
  1557. }
  1558. /// processBranchOnPHI - We have an otherwise unthreadable conditional branch on
  1559. /// a PHI node (or freeze PHI) in the current block. See if there are any
  1560. /// simplifications we can do based on inputs to the phi node.
  1561. bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) {
  1562. BasicBlock *BB = PN->getParent();
  1563. // TODO: We could make use of this to do it once for blocks with common PHI
  1564. // values.
  1565. SmallVector<BasicBlock*, 1> PredBBs;
  1566. PredBBs.resize(1);
  1567. // If any of the predecessor blocks end in an unconditional branch, we can
  1568. // *duplicate* the conditional branch into that block in order to further
  1569. // encourage jump threading and to eliminate cases where we have branch on a
  1570. // phi of an icmp (branch on icmp is much better).
  1571. // This is still beneficial when a frozen phi is used as the branch condition
  1572. // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp))
  1573. // to br(icmp(freeze ...)).
  1574. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1575. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1576. if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
  1577. if (PredBr->isUnconditional()) {
  1578. PredBBs[0] = PredBB;
  1579. // Try to duplicate BB into PredBB.
  1580. if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs))
  1581. return true;
  1582. }
  1583. }
  1584. return false;
  1585. }
  1586. /// processBranchOnXOR - We have an otherwise unthreadable conditional branch on
  1587. /// a xor instruction in the current block. See if there are any
  1588. /// simplifications we can do based on inputs to the xor.
  1589. bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) {
  1590. BasicBlock *BB = BO->getParent();
  1591. // If either the LHS or RHS of the xor is a constant, don't do this
  1592. // optimization.
  1593. if (isa<ConstantInt>(BO->getOperand(0)) ||
  1594. isa<ConstantInt>(BO->getOperand(1)))
  1595. return false;
  1596. // If the first instruction in BB isn't a phi, we won't be able to infer
  1597. // anything special about any particular predecessor.
  1598. if (!isa<PHINode>(BB->front()))
  1599. return false;
  1600. // If this BB is a landing pad, we won't be able to split the edge into it.
  1601. if (BB->isEHPad())
  1602. return false;
  1603. // If we have a xor as the branch input to this block, and we know that the
  1604. // LHS or RHS of the xor in any predecessor is true/false, then we can clone
  1605. // the condition into the predecessor and fix that value to true, saving some
  1606. // logical ops on that path and encouraging other paths to simplify.
  1607. //
  1608. // This copies something like this:
  1609. //
  1610. // BB:
  1611. // %X = phi i1 [1], [%X']
  1612. // %Y = icmp eq i32 %A, %B
  1613. // %Z = xor i1 %X, %Y
  1614. // br i1 %Z, ...
  1615. //
  1616. // Into:
  1617. // BB':
  1618. // %Y = icmp ne i32 %A, %B
  1619. // br i1 %Y, ...
  1620. PredValueInfoTy XorOpValues;
  1621. bool isLHS = true;
  1622. if (!computeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
  1623. WantInteger, BO)) {
  1624. assert(XorOpValues.empty());
  1625. if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
  1626. WantInteger, BO))
  1627. return false;
  1628. isLHS = false;
  1629. }
  1630. assert(!XorOpValues.empty() &&
  1631. "computeValueKnownInPredecessors returned true with no values");
  1632. // Scan the information to see which is most popular: true or false. The
  1633. // predecessors can be of the set true, false, or undef.
  1634. unsigned NumTrue = 0, NumFalse = 0;
  1635. for (const auto &XorOpValue : XorOpValues) {
  1636. if (isa<UndefValue>(XorOpValue.first))
  1637. // Ignore undefs for the count.
  1638. continue;
  1639. if (cast<ConstantInt>(XorOpValue.first)->isZero())
  1640. ++NumFalse;
  1641. else
  1642. ++NumTrue;
  1643. }
  1644. // Determine which value to split on, true, false, or undef if neither.
  1645. ConstantInt *SplitVal = nullptr;
  1646. if (NumTrue > NumFalse)
  1647. SplitVal = ConstantInt::getTrue(BB->getContext());
  1648. else if (NumTrue != 0 || NumFalse != 0)
  1649. SplitVal = ConstantInt::getFalse(BB->getContext());
  1650. // Collect all of the blocks that this can be folded into so that we can
  1651. // factor this once and clone it once.
  1652. SmallVector<BasicBlock*, 8> BlocksToFoldInto;
  1653. for (const auto &XorOpValue : XorOpValues) {
  1654. if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
  1655. continue;
  1656. BlocksToFoldInto.push_back(XorOpValue.second);
  1657. }
  1658. // If we inferred a value for all of the predecessors, then duplication won't
  1659. // help us. However, we can just replace the LHS or RHS with the constant.
  1660. if (BlocksToFoldInto.size() ==
  1661. cast<PHINode>(BB->front()).getNumIncomingValues()) {
  1662. if (!SplitVal) {
  1663. // If all preds provide undef, just nuke the xor, because it is undef too.
  1664. BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
  1665. BO->eraseFromParent();
  1666. } else if (SplitVal->isZero()) {
  1667. // If all preds provide 0, replace the xor with the other input.
  1668. BO->replaceAllUsesWith(BO->getOperand(isLHS));
  1669. BO->eraseFromParent();
  1670. } else {
  1671. // If all preds provide 1, set the computed value to 1.
  1672. BO->setOperand(!isLHS, SplitVal);
  1673. }
  1674. return true;
  1675. }
  1676. // If any of predecessors end with an indirect goto, we can't change its
  1677. // destination. Same for CallBr.
  1678. if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) {
  1679. return isa<IndirectBrInst>(Pred->getTerminator()) ||
  1680. isa<CallBrInst>(Pred->getTerminator());
  1681. }))
  1682. return false;
  1683. // Try to duplicate BB into PredBB.
  1684. return duplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
  1685. }
  1686. /// addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
  1687. /// predecessor to the PHIBB block. If it has PHI nodes, add entries for
  1688. /// NewPred using the entries from OldPred (suitably mapped).
  1689. static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
  1690. BasicBlock *OldPred,
  1691. BasicBlock *NewPred,
  1692. DenseMap<Instruction*, Value*> &ValueMap) {
  1693. for (PHINode &PN : PHIBB->phis()) {
  1694. // Ok, we have a PHI node. Figure out what the incoming value was for the
  1695. // DestBlock.
  1696. Value *IV = PN.getIncomingValueForBlock(OldPred);
  1697. // Remap the value if necessary.
  1698. if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
  1699. DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
  1700. if (I != ValueMap.end())
  1701. IV = I->second;
  1702. }
  1703. PN.addIncoming(IV, NewPred);
  1704. }
  1705. }
  1706. /// Merge basic block BB into its sole predecessor if possible.
  1707. bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) {
  1708. BasicBlock *SinglePred = BB->getSinglePredecessor();
  1709. if (!SinglePred)
  1710. return false;
  1711. const Instruction *TI = SinglePred->getTerminator();
  1712. if (TI->isExceptionalTerminator() || TI->getNumSuccessors() != 1 ||
  1713. SinglePred == BB || hasAddressTakenAndUsed(BB))
  1714. return false;
  1715. // If SinglePred was a loop header, BB becomes one.
  1716. if (LoopHeaders.erase(SinglePred))
  1717. LoopHeaders.insert(BB);
  1718. LVI->eraseBlock(SinglePred);
  1719. MergeBasicBlockIntoOnlyPred(BB, DTU);
  1720. // Now that BB is merged into SinglePred (i.e. SinglePred code followed by
  1721. // BB code within one basic block `BB`), we need to invalidate the LVI
  1722. // information associated with BB, because the LVI information need not be
  1723. // true for all of BB after the merge. For example,
  1724. // Before the merge, LVI info and code is as follows:
  1725. // SinglePred: <LVI info1 for %p val>
  1726. // %y = use of %p
  1727. // call @exit() // need not transfer execution to successor.
  1728. // assume(%p) // from this point on %p is true
  1729. // br label %BB
  1730. // BB: <LVI info2 for %p val, i.e. %p is true>
  1731. // %x = use of %p
  1732. // br label exit
  1733. //
  1734. // Note that this LVI info for blocks BB and SinglPred is correct for %p
  1735. // (info2 and info1 respectively). After the merge and the deletion of the
  1736. // LVI info1 for SinglePred. We have the following code:
  1737. // BB: <LVI info2 for %p val>
  1738. // %y = use of %p
  1739. // call @exit()
  1740. // assume(%p)
  1741. // %x = use of %p <-- LVI info2 is correct from here onwards.
  1742. // br label exit
  1743. // LVI info2 for BB is incorrect at the beginning of BB.
  1744. // Invalidate LVI information for BB if the LVI is not provably true for
  1745. // all of BB.
  1746. if (!isGuaranteedToTransferExecutionToSuccessor(BB))
  1747. LVI->eraseBlock(BB);
  1748. return true;
  1749. }
  1750. /// Update the SSA form. NewBB contains instructions that are copied from BB.
  1751. /// ValueMapping maps old values in BB to new ones in NewBB.
  1752. void JumpThreadingPass::updateSSA(
  1753. BasicBlock *BB, BasicBlock *NewBB,
  1754. DenseMap<Instruction *, Value *> &ValueMapping) {
  1755. // If there were values defined in BB that are used outside the block, then we
  1756. // now have to update all uses of the value to use either the original value,
  1757. // the cloned value, or some PHI derived value. This can require arbitrary
  1758. // PHI insertion, of which we are prepared to do, clean these up now.
  1759. SSAUpdater SSAUpdate;
  1760. SmallVector<Use *, 16> UsesToRename;
  1761. for (Instruction &I : *BB) {
  1762. // Scan all uses of this instruction to see if it is used outside of its
  1763. // block, and if so, record them in UsesToRename.
  1764. for (Use &U : I.uses()) {
  1765. Instruction *User = cast<Instruction>(U.getUser());
  1766. if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
  1767. if (UserPN->getIncomingBlock(U) == BB)
  1768. continue;
  1769. } else if (User->getParent() == BB)
  1770. continue;
  1771. UsesToRename.push_back(&U);
  1772. }
  1773. // If there are no uses outside the block, we're done with this instruction.
  1774. if (UsesToRename.empty())
  1775. continue;
  1776. LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
  1777. // We found a use of I outside of BB. Rename all uses of I that are outside
  1778. // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
  1779. // with the two values we know.
  1780. SSAUpdate.Initialize(I.getType(), I.getName());
  1781. SSAUpdate.AddAvailableValue(BB, &I);
  1782. SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
  1783. while (!UsesToRename.empty())
  1784. SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
  1785. LLVM_DEBUG(dbgs() << "\n");
  1786. }
  1787. }
  1788. /// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone
  1789. /// arguments that come from PredBB. Return the map from the variables in the
  1790. /// source basic block to the variables in the newly created basic block.
  1791. DenseMap<Instruction *, Value *>
  1792. JumpThreadingPass::cloneInstructions(BasicBlock::iterator BI,
  1793. BasicBlock::iterator BE, BasicBlock *NewBB,
  1794. BasicBlock *PredBB) {
  1795. // We are going to have to map operands from the source basic block to the new
  1796. // copy of the block 'NewBB'. If there are PHI nodes in the source basic
  1797. // block, evaluate them to account for entry from PredBB.
  1798. DenseMap<Instruction *, Value *> ValueMapping;
  1799. // Clone the phi nodes of the source basic block into NewBB. The resulting
  1800. // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater
  1801. // might need to rewrite the operand of the cloned phi.
  1802. for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
  1803. PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB);
  1804. NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB);
  1805. ValueMapping[PN] = NewPN;
  1806. }
  1807. // Clone noalias scope declarations in the threaded block. When threading a
  1808. // loop exit, we would otherwise end up with two idential scope declarations
  1809. // visible at the same time.
  1810. SmallVector<MDNode *> NoAliasScopes;
  1811. DenseMap<MDNode *, MDNode *> ClonedScopes;
  1812. LLVMContext &Context = PredBB->getContext();
  1813. identifyNoAliasScopesToClone(BI, BE, NoAliasScopes);
  1814. cloneNoAliasScopes(NoAliasScopes, ClonedScopes, "thread", Context);
  1815. // Clone the non-phi instructions of the source basic block into NewBB,
  1816. // keeping track of the mapping and using it to remap operands in the cloned
  1817. // instructions.
  1818. for (; BI != BE; ++BI) {
  1819. Instruction *New = BI->clone();
  1820. New->setName(BI->getName());
  1821. NewBB->getInstList().push_back(New);
  1822. ValueMapping[&*BI] = New;
  1823. adaptNoAliasScopes(New, ClonedScopes, Context);
  1824. // Remap operands to patch up intra-block references.
  1825. for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
  1826. if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
  1827. DenseMap<Instruction *, Value *>::iterator I = ValueMapping.find(Inst);
  1828. if (I != ValueMapping.end())
  1829. New->setOperand(i, I->second);
  1830. }
  1831. }
  1832. return ValueMapping;
  1833. }
  1834. /// Attempt to thread through two successive basic blocks.
  1835. bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB,
  1836. Value *Cond) {
  1837. // Consider:
  1838. //
  1839. // PredBB:
  1840. // %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ]
  1841. // %tobool = icmp eq i32 %cond, 0
  1842. // br i1 %tobool, label %BB, label ...
  1843. //
  1844. // BB:
  1845. // %cmp = icmp eq i32* %var, null
  1846. // br i1 %cmp, label ..., label ...
  1847. //
  1848. // We don't know the value of %var at BB even if we know which incoming edge
  1849. // we take to BB. However, once we duplicate PredBB for each of its incoming
  1850. // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of
  1851. // PredBB. Then we can thread edges PredBB1->BB and PredBB2->BB through BB.
  1852. // Require that BB end with a Branch for simplicity.
  1853. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  1854. if (!CondBr)
  1855. return false;
  1856. // BB must have exactly one predecessor.
  1857. BasicBlock *PredBB = BB->getSinglePredecessor();
  1858. if (!PredBB)
  1859. return false;
  1860. // Require that PredBB end with a conditional Branch. If PredBB ends with an
  1861. // unconditional branch, we should be merging PredBB and BB instead. For
  1862. // simplicity, we don't deal with a switch.
  1863. BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
  1864. if (!PredBBBranch || PredBBBranch->isUnconditional())
  1865. return false;
  1866. // If PredBB has exactly one incoming edge, we don't gain anything by copying
  1867. // PredBB.
  1868. if (PredBB->getSinglePredecessor())
  1869. return false;
  1870. // Don't thread through PredBB if it contains a successor edge to itself, in
  1871. // which case we would infinite loop. Suppose we are threading an edge from
  1872. // PredPredBB through PredBB and BB to SuccBB with PredBB containing a
  1873. // successor edge to itself. If we allowed jump threading in this case, we
  1874. // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread. Since
  1875. // PredBB.thread has a successor edge to PredBB, we would immediately come up
  1876. // with another jump threading opportunity from PredBB.thread through PredBB
  1877. // and BB to SuccBB. This jump threading would repeatedly occur. That is, we
  1878. // would keep peeling one iteration from PredBB.
  1879. if (llvm::is_contained(successors(PredBB), PredBB))
  1880. return false;
  1881. // Don't thread across a loop header.
  1882. if (LoopHeaders.count(PredBB))
  1883. return false;
  1884. // Avoid complication with duplicating EH pads.
  1885. if (PredBB->isEHPad())
  1886. return false;
  1887. // Find a predecessor that we can thread. For simplicity, we only consider a
  1888. // successor edge out of BB to which we thread exactly one incoming edge into
  1889. // PredBB.
  1890. unsigned ZeroCount = 0;
  1891. unsigned OneCount = 0;
  1892. BasicBlock *ZeroPred = nullptr;
  1893. BasicBlock *OnePred = nullptr;
  1894. for (BasicBlock *P : predecessors(PredBB)) {
  1895. if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(
  1896. evaluateOnPredecessorEdge(BB, P, Cond))) {
  1897. if (CI->isZero()) {
  1898. ZeroCount++;
  1899. ZeroPred = P;
  1900. } else if (CI->isOne()) {
  1901. OneCount++;
  1902. OnePred = P;
  1903. }
  1904. }
  1905. }
  1906. // Disregard complicated cases where we have to thread multiple edges.
  1907. BasicBlock *PredPredBB;
  1908. if (ZeroCount == 1) {
  1909. PredPredBB = ZeroPred;
  1910. } else if (OneCount == 1) {
  1911. PredPredBB = OnePred;
  1912. } else {
  1913. return false;
  1914. }
  1915. BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred);
  1916. // If threading to the same block as we come from, we would infinite loop.
  1917. if (SuccBB == BB) {
  1918. LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
  1919. << "' - would thread to self!\n");
  1920. return false;
  1921. }
  1922. // If threading this would thread across a loop header, don't thread the edge.
  1923. // See the comments above findLoopHeaders for justifications and caveats.
  1924. if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
  1925. LLVM_DEBUG({
  1926. bool BBIsHeader = LoopHeaders.count(BB);
  1927. bool SuccIsHeader = LoopHeaders.count(SuccBB);
  1928. dbgs() << " Not threading across "
  1929. << (BBIsHeader ? "loop header BB '" : "block BB '")
  1930. << BB->getName() << "' to dest "
  1931. << (SuccIsHeader ? "loop header BB '" : "block BB '")
  1932. << SuccBB->getName()
  1933. << "' - it might create an irreducible loop!\n";
  1934. });
  1935. return false;
  1936. }
  1937. // Compute the cost of duplicating BB and PredBB.
  1938. unsigned BBCost = getJumpThreadDuplicationCost(
  1939. TTI, BB, BB->getTerminator(), BBDupThreshold);
  1940. unsigned PredBBCost = getJumpThreadDuplicationCost(
  1941. TTI, PredBB, PredBB->getTerminator(), BBDupThreshold);
  1942. // Give up if costs are too high. We need to check BBCost and PredBBCost
  1943. // individually before checking their sum because getJumpThreadDuplicationCost
  1944. // return (unsigned)~0 for those basic blocks that cannot be duplicated.
  1945. if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold ||
  1946. BBCost + PredBBCost > BBDupThreshold) {
  1947. LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
  1948. << "' - Cost is too high: " << PredBBCost
  1949. << " for PredBB, " << BBCost << "for BB\n");
  1950. return false;
  1951. }
  1952. // Now we are ready to duplicate PredBB.
  1953. threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB);
  1954. return true;
  1955. }
  1956. void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB,
  1957. BasicBlock *PredBB,
  1958. BasicBlock *BB,
  1959. BasicBlock *SuccBB) {
  1960. LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '"
  1961. << BB->getName() << "'\n");
  1962. BranchInst *CondBr = cast<BranchInst>(BB->getTerminator());
  1963. BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator());
  1964. BasicBlock *NewBB =
  1965. BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread",
  1966. PredBB->getParent(), PredBB);
  1967. NewBB->moveAfter(PredBB);
  1968. // Set the block frequency of NewBB.
  1969. if (HasProfileData) {
  1970. auto NewBBFreq = BFI->getBlockFreq(PredPredBB) *
  1971. BPI->getEdgeProbability(PredPredBB, PredBB);
  1972. BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
  1973. }
  1974. // We are going to have to map operands from the original BB block to the new
  1975. // copy of the block 'NewBB'. If there are PHI nodes in PredBB, evaluate them
  1976. // to account for entry from PredPredBB.
  1977. DenseMap<Instruction *, Value *> ValueMapping =
  1978. cloneInstructions(PredBB->begin(), PredBB->end(), NewBB, PredPredBB);
  1979. // Copy the edge probabilities from PredBB to NewBB.
  1980. if (HasProfileData)
  1981. BPI->copyEdgeProbabilities(PredBB, NewBB);
  1982. // Update the terminator of PredPredBB to jump to NewBB instead of PredBB.
  1983. // This eliminates predecessors from PredPredBB, which requires us to simplify
  1984. // any PHI nodes in PredBB.
  1985. Instruction *PredPredTerm = PredPredBB->getTerminator();
  1986. for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i)
  1987. if (PredPredTerm->getSuccessor(i) == PredBB) {
  1988. PredBB->removePredecessor(PredPredBB, true);
  1989. PredPredTerm->setSuccessor(i, NewBB);
  1990. }
  1991. addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB,
  1992. ValueMapping);
  1993. addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB,
  1994. ValueMapping);
  1995. DTU->applyUpdatesPermissive(
  1996. {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)},
  1997. {DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)},
  1998. {DominatorTree::Insert, PredPredBB, NewBB},
  1999. {DominatorTree::Delete, PredPredBB, PredBB}});
  2000. updateSSA(PredBB, NewBB, ValueMapping);
  2001. // Clean up things like PHI nodes with single operands, dead instructions,
  2002. // etc.
  2003. SimplifyInstructionsInBlock(NewBB, TLI);
  2004. SimplifyInstructionsInBlock(PredBB, TLI);
  2005. SmallVector<BasicBlock *, 1> PredsToFactor;
  2006. PredsToFactor.push_back(NewBB);
  2007. threadEdge(BB, PredsToFactor, SuccBB);
  2008. }
  2009. /// tryThreadEdge - Thread an edge if it's safe and profitable to do so.
  2010. bool JumpThreadingPass::tryThreadEdge(
  2011. BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs,
  2012. BasicBlock *SuccBB) {
  2013. // If threading to the same block as we come from, we would infinite loop.
  2014. if (SuccBB == BB) {
  2015. LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
  2016. << "' - would thread to self!\n");
  2017. return false;
  2018. }
  2019. // If threading this would thread across a loop header, don't thread the edge.
  2020. // See the comments above findLoopHeaders for justifications and caveats.
  2021. if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
  2022. LLVM_DEBUG({
  2023. bool BBIsHeader = LoopHeaders.count(BB);
  2024. bool SuccIsHeader = LoopHeaders.count(SuccBB);
  2025. dbgs() << " Not threading across "
  2026. << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName()
  2027. << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '")
  2028. << SuccBB->getName() << "' - it might create an irreducible loop!\n";
  2029. });
  2030. return false;
  2031. }
  2032. unsigned JumpThreadCost = getJumpThreadDuplicationCost(
  2033. TTI, BB, BB->getTerminator(), BBDupThreshold);
  2034. if (JumpThreadCost > BBDupThreshold) {
  2035. LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
  2036. << "' - Cost is too high: " << JumpThreadCost << "\n");
  2037. return false;
  2038. }
  2039. threadEdge(BB, PredBBs, SuccBB);
  2040. return true;
  2041. }
  2042. /// threadEdge - We have decided that it is safe and profitable to factor the
  2043. /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
  2044. /// across BB. Transform the IR to reflect this change.
  2045. void JumpThreadingPass::threadEdge(BasicBlock *BB,
  2046. const SmallVectorImpl<BasicBlock *> &PredBBs,
  2047. BasicBlock *SuccBB) {
  2048. assert(SuccBB != BB && "Don't create an infinite loop");
  2049. assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&
  2050. "Don't thread across loop headers");
  2051. // And finally, do it! Start by factoring the predecessors if needed.
  2052. BasicBlock *PredBB;
  2053. if (PredBBs.size() == 1)
  2054. PredBB = PredBBs[0];
  2055. else {
  2056. LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
  2057. << " common predecessors.\n");
  2058. PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
  2059. }
  2060. // And finally, do it!
  2061. LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName()
  2062. << "' to '" << SuccBB->getName()
  2063. << ", across block:\n " << *BB << "\n");
  2064. LVI->threadEdge(PredBB, BB, SuccBB);
  2065. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
  2066. BB->getName()+".thread",
  2067. BB->getParent(), BB);
  2068. NewBB->moveAfter(PredBB);
  2069. // Set the block frequency of NewBB.
  2070. if (HasProfileData) {
  2071. auto NewBBFreq =
  2072. BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
  2073. BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
  2074. }
  2075. // Copy all the instructions from BB to NewBB except the terminator.
  2076. DenseMap<Instruction *, Value *> ValueMapping =
  2077. cloneInstructions(BB->begin(), std::prev(BB->end()), NewBB, PredBB);
  2078. // We didn't copy the terminator from BB over to NewBB, because there is now
  2079. // an unconditional jump to SuccBB. Insert the unconditional jump.
  2080. BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
  2081. NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
  2082. // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
  2083. // PHI nodes for NewBB now.
  2084. addPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
  2085. // Update the terminator of PredBB to jump to NewBB instead of BB. This
  2086. // eliminates predecessors from BB, which requires us to simplify any PHI
  2087. // nodes in BB.
  2088. Instruction *PredTerm = PredBB->getTerminator();
  2089. for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
  2090. if (PredTerm->getSuccessor(i) == BB) {
  2091. BB->removePredecessor(PredBB, true);
  2092. PredTerm->setSuccessor(i, NewBB);
  2093. }
  2094. // Enqueue required DT updates.
  2095. DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB},
  2096. {DominatorTree::Insert, PredBB, NewBB},
  2097. {DominatorTree::Delete, PredBB, BB}});
  2098. updateSSA(BB, NewBB, ValueMapping);
  2099. // At this point, the IR is fully up to date and consistent. Do a quick scan
  2100. // over the new instructions and zap any that are constants or dead. This
  2101. // frequently happens because of phi translation.
  2102. SimplifyInstructionsInBlock(NewBB, TLI);
  2103. // Update the edge weight from BB to SuccBB, which should be less than before.
  2104. updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
  2105. // Threaded an edge!
  2106. ++NumThreads;
  2107. }
  2108. /// Create a new basic block that will be the predecessor of BB and successor of
  2109. /// all blocks in Preds. When profile data is available, update the frequency of
  2110. /// this new block.
  2111. BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB,
  2112. ArrayRef<BasicBlock *> Preds,
  2113. const char *Suffix) {
  2114. SmallVector<BasicBlock *, 2> NewBBs;
  2115. // Collect the frequencies of all predecessors of BB, which will be used to
  2116. // update the edge weight of the result of splitting predecessors.
  2117. DenseMap<BasicBlock *, BlockFrequency> FreqMap;
  2118. if (HasProfileData)
  2119. for (auto Pred : Preds)
  2120. FreqMap.insert(std::make_pair(
  2121. Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
  2122. // In the case when BB is a LandingPad block we create 2 new predecessors
  2123. // instead of just one.
  2124. if (BB->isLandingPad()) {
  2125. std::string NewName = std::string(Suffix) + ".split-lp";
  2126. SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs);
  2127. } else {
  2128. NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix));
  2129. }
  2130. std::vector<DominatorTree::UpdateType> Updates;
  2131. Updates.reserve((2 * Preds.size()) + NewBBs.size());
  2132. for (auto NewBB : NewBBs) {
  2133. BlockFrequency NewBBFreq(0);
  2134. Updates.push_back({DominatorTree::Insert, NewBB, BB});
  2135. for (auto Pred : predecessors(NewBB)) {
  2136. Updates.push_back({DominatorTree::Delete, Pred, BB});
  2137. Updates.push_back({DominatorTree::Insert, Pred, NewBB});
  2138. if (HasProfileData) // Update frequencies between Pred -> NewBB.
  2139. NewBBFreq += FreqMap.lookup(Pred);
  2140. }
  2141. if (HasProfileData) // Apply the summed frequency to NewBB.
  2142. BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
  2143. }
  2144. DTU->applyUpdatesPermissive(Updates);
  2145. return NewBBs[0];
  2146. }
  2147. bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
  2148. const Instruction *TI = BB->getTerminator();
  2149. assert(TI->getNumSuccessors() > 1 && "not a split");
  2150. MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
  2151. if (!WeightsNode)
  2152. return false;
  2153. MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
  2154. if (MDName->getString() != "branch_weights")
  2155. return false;
  2156. // Ensure there are weights for all of the successors. Note that the first
  2157. // operand to the metadata node is a name, not a weight.
  2158. return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1;
  2159. }
  2160. /// Update the block frequency of BB and branch weight and the metadata on the
  2161. /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
  2162. /// Freq(PredBB->BB) / Freq(BB->SuccBB).
  2163. void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
  2164. BasicBlock *BB,
  2165. BasicBlock *NewBB,
  2166. BasicBlock *SuccBB) {
  2167. if (!HasProfileData)
  2168. return;
  2169. assert(BFI && BPI && "BFI & BPI should have been created here");
  2170. // As the edge from PredBB to BB is deleted, we have to update the block
  2171. // frequency of BB.
  2172. auto BBOrigFreq = BFI->getBlockFreq(BB);
  2173. auto NewBBFreq = BFI->getBlockFreq(NewBB);
  2174. auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
  2175. auto BBNewFreq = BBOrigFreq - NewBBFreq;
  2176. BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
  2177. // Collect updated outgoing edges' frequencies from BB and use them to update
  2178. // edge probabilities.
  2179. SmallVector<uint64_t, 4> BBSuccFreq;
  2180. for (BasicBlock *Succ : successors(BB)) {
  2181. auto SuccFreq = (Succ == SuccBB)
  2182. ? BB2SuccBBFreq - NewBBFreq
  2183. : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
  2184. BBSuccFreq.push_back(SuccFreq.getFrequency());
  2185. }
  2186. uint64_t MaxBBSuccFreq =
  2187. *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
  2188. SmallVector<BranchProbability, 4> BBSuccProbs;
  2189. if (MaxBBSuccFreq == 0)
  2190. BBSuccProbs.assign(BBSuccFreq.size(),
  2191. {1, static_cast<unsigned>(BBSuccFreq.size())});
  2192. else {
  2193. for (uint64_t Freq : BBSuccFreq)
  2194. BBSuccProbs.push_back(
  2195. BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
  2196. // Normalize edge probabilities so that they sum up to one.
  2197. BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
  2198. BBSuccProbs.end());
  2199. }
  2200. // Update edge probabilities in BPI.
  2201. BPI->setEdgeProbability(BB, BBSuccProbs);
  2202. // Update the profile metadata as well.
  2203. //
  2204. // Don't do this if the profile of the transformed blocks was statically
  2205. // estimated. (This could occur despite the function having an entry
  2206. // frequency in completely cold parts of the CFG.)
  2207. //
  2208. // In this case we don't want to suggest to subsequent passes that the
  2209. // calculated weights are fully consistent. Consider this graph:
  2210. //
  2211. // check_1
  2212. // 50% / |
  2213. // eq_1 | 50%
  2214. // \ |
  2215. // check_2
  2216. // 50% / |
  2217. // eq_2 | 50%
  2218. // \ |
  2219. // check_3
  2220. // 50% / |
  2221. // eq_3 | 50%
  2222. // \ |
  2223. //
  2224. // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
  2225. // the overall probabilities are inconsistent; the total probability that the
  2226. // value is either 1, 2 or 3 is 150%.
  2227. //
  2228. // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
  2229. // becomes 0%. This is even worse if the edge whose probability becomes 0% is
  2230. // the loop exit edge. Then based solely on static estimation we would assume
  2231. // the loop was extremely hot.
  2232. //
  2233. // FIXME this locally as well so that BPI and BFI are consistent as well. We
  2234. // shouldn't make edges extremely likely or unlikely based solely on static
  2235. // estimation.
  2236. if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
  2237. SmallVector<uint32_t, 4> Weights;
  2238. for (auto Prob : BBSuccProbs)
  2239. Weights.push_back(Prob.getNumerator());
  2240. auto TI = BB->getTerminator();
  2241. TI->setMetadata(
  2242. LLVMContext::MD_prof,
  2243. MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
  2244. }
  2245. }
  2246. /// duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
  2247. /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
  2248. /// If we can duplicate the contents of BB up into PredBB do so now, this
  2249. /// improves the odds that the branch will be on an analyzable instruction like
  2250. /// a compare.
  2251. bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred(
  2252. BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
  2253. assert(!PredBBs.empty() && "Can't handle an empty set");
  2254. // If BB is a loop header, then duplicating this block outside the loop would
  2255. // cause us to transform this into an irreducible loop, don't do this.
  2256. // See the comments above findLoopHeaders for justifications and caveats.
  2257. if (LoopHeaders.count(BB)) {
  2258. LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
  2259. << "' into predecessor block '" << PredBBs[0]->getName()
  2260. << "' - it might create an irreducible loop!\n");
  2261. return false;
  2262. }
  2263. unsigned DuplicationCost = getJumpThreadDuplicationCost(
  2264. TTI, BB, BB->getTerminator(), BBDupThreshold);
  2265. if (DuplicationCost > BBDupThreshold) {
  2266. LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
  2267. << "' - Cost is too high: " << DuplicationCost << "\n");
  2268. return false;
  2269. }
  2270. // And finally, do it! Start by factoring the predecessors if needed.
  2271. std::vector<DominatorTree::UpdateType> Updates;
  2272. BasicBlock *PredBB;
  2273. if (PredBBs.size() == 1)
  2274. PredBB = PredBBs[0];
  2275. else {
  2276. LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
  2277. << " common predecessors.\n");
  2278. PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
  2279. }
  2280. Updates.push_back({DominatorTree::Delete, PredBB, BB});
  2281. // Okay, we decided to do this! Clone all the instructions in BB onto the end
  2282. // of PredBB.
  2283. LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName()
  2284. << "' into end of '" << PredBB->getName()
  2285. << "' to eliminate branch on phi. Cost: "
  2286. << DuplicationCost << " block is:" << *BB << "\n");
  2287. // Unless PredBB ends with an unconditional branch, split the edge so that we
  2288. // can just clone the bits from BB into the end of the new PredBB.
  2289. BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
  2290. if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
  2291. BasicBlock *OldPredBB = PredBB;
  2292. PredBB = SplitEdge(OldPredBB, BB);
  2293. Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB});
  2294. Updates.push_back({DominatorTree::Insert, PredBB, BB});
  2295. Updates.push_back({DominatorTree::Delete, OldPredBB, BB});
  2296. OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
  2297. }
  2298. // We are going to have to map operands from the original BB block into the
  2299. // PredBB block. Evaluate PHI nodes in BB.
  2300. DenseMap<Instruction*, Value*> ValueMapping;
  2301. BasicBlock::iterator BI = BB->begin();
  2302. for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  2303. ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
  2304. // Clone the non-phi instructions of BB into PredBB, keeping track of the
  2305. // mapping and using it to remap operands in the cloned instructions.
  2306. for (; BI != BB->end(); ++BI) {
  2307. Instruction *New = BI->clone();
  2308. // Remap operands to patch up intra-block references.
  2309. for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
  2310. if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
  2311. DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
  2312. if (I != ValueMapping.end())
  2313. New->setOperand(i, I->second);
  2314. }
  2315. // If this instruction can be simplified after the operands are updated,
  2316. // just use the simplified value instead. This frequently happens due to
  2317. // phi translation.
  2318. if (Value *IV = SimplifyInstruction(
  2319. New,
  2320. {BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) {
  2321. ValueMapping[&*BI] = IV;
  2322. if (!New->mayHaveSideEffects()) {
  2323. New->deleteValue();
  2324. New = nullptr;
  2325. }
  2326. } else {
  2327. ValueMapping[&*BI] = New;
  2328. }
  2329. if (New) {
  2330. // Otherwise, insert the new instruction into the block.
  2331. New->setName(BI->getName());
  2332. PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
  2333. // Update Dominance from simplified New instruction operands.
  2334. for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
  2335. if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i)))
  2336. Updates.push_back({DominatorTree::Insert, PredBB, SuccBB});
  2337. }
  2338. }
  2339. // Check to see if the targets of the branch had PHI nodes. If so, we need to
  2340. // add entries to the PHI nodes for branch from PredBB now.
  2341. BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
  2342. addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
  2343. ValueMapping);
  2344. addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
  2345. ValueMapping);
  2346. updateSSA(BB, PredBB, ValueMapping);
  2347. // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
  2348. // that we nuked.
  2349. BB->removePredecessor(PredBB, true);
  2350. // Remove the unconditional branch at the end of the PredBB block.
  2351. OldPredBranch->eraseFromParent();
  2352. if (HasProfileData)
  2353. BPI->copyEdgeProbabilities(BB, PredBB);
  2354. DTU->applyUpdatesPermissive(Updates);
  2355. ++NumDupes;
  2356. return true;
  2357. }
  2358. // Pred is a predecessor of BB with an unconditional branch to BB. SI is
  2359. // a Select instruction in Pred. BB has other predecessors and SI is used in
  2360. // a PHI node in BB. SI has no other use.
  2361. // A new basic block, NewBB, is created and SI is converted to compare and
  2362. // conditional branch. SI is erased from parent.
  2363. void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB,
  2364. SelectInst *SI, PHINode *SIUse,
  2365. unsigned Idx) {
  2366. // Expand the select.
  2367. //
  2368. // Pred --
  2369. // | v
  2370. // | NewBB
  2371. // | |
  2372. // |-----
  2373. // v
  2374. // BB
  2375. BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator());
  2376. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
  2377. BB->getParent(), BB);
  2378. // Move the unconditional branch to NewBB.
  2379. PredTerm->removeFromParent();
  2380. NewBB->getInstList().insert(NewBB->end(), PredTerm);
  2381. // Create a conditional branch and update PHI nodes.
  2382. auto *BI = BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
  2383. BI->applyMergedLocation(PredTerm->getDebugLoc(), SI->getDebugLoc());
  2384. SIUse->setIncomingValue(Idx, SI->getFalseValue());
  2385. SIUse->addIncoming(SI->getTrueValue(), NewBB);
  2386. // The select is now dead.
  2387. SI->eraseFromParent();
  2388. DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB},
  2389. {DominatorTree::Insert, Pred, NewBB}});
  2390. // Update any other PHI nodes in BB.
  2391. for (BasicBlock::iterator BI = BB->begin();
  2392. PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
  2393. if (Phi != SIUse)
  2394. Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
  2395. }
  2396. bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) {
  2397. PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition());
  2398. if (!CondPHI || CondPHI->getParent() != BB)
  2399. return false;
  2400. for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) {
  2401. BasicBlock *Pred = CondPHI->getIncomingBlock(I);
  2402. SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I));
  2403. // The second and third condition can be potentially relaxed. Currently
  2404. // the conditions help to simplify the code and allow us to reuse existing
  2405. // code, developed for tryToUnfoldSelect(CmpInst *, BasicBlock *)
  2406. if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse())
  2407. continue;
  2408. BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
  2409. if (!PredTerm || !PredTerm->isUnconditional())
  2410. continue;
  2411. unfoldSelectInstr(Pred, BB, PredSI, CondPHI, I);
  2412. return true;
  2413. }
  2414. return false;
  2415. }
  2416. /// tryToUnfoldSelect - Look for blocks of the form
  2417. /// bb1:
  2418. /// %a = select
  2419. /// br bb2
  2420. ///
  2421. /// bb2:
  2422. /// %p = phi [%a, %bb1] ...
  2423. /// %c = icmp %p
  2424. /// br i1 %c
  2425. ///
  2426. /// And expand the select into a branch structure if one of its arms allows %c
  2427. /// to be folded. This later enables threading from bb1 over bb2.
  2428. bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
  2429. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  2430. PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
  2431. Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
  2432. if (!CondBr || !CondBr->isConditional() || !CondLHS ||
  2433. CondLHS->getParent() != BB)
  2434. return false;
  2435. for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
  2436. BasicBlock *Pred = CondLHS->getIncomingBlock(I);
  2437. SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
  2438. // Look if one of the incoming values is a select in the corresponding
  2439. // predecessor.
  2440. if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
  2441. continue;
  2442. BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
  2443. if (!PredTerm || !PredTerm->isUnconditional())
  2444. continue;
  2445. // Now check if one of the select values would allow us to constant fold the
  2446. // terminator in BB. We don't do the transform if both sides fold, those
  2447. // cases will be threaded in any case.
  2448. LazyValueInfo::Tristate LHSFolds =
  2449. LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
  2450. CondRHS, Pred, BB, CondCmp);
  2451. LazyValueInfo::Tristate RHSFolds =
  2452. LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
  2453. CondRHS, Pred, BB, CondCmp);
  2454. if ((LHSFolds != LazyValueInfo::Unknown ||
  2455. RHSFolds != LazyValueInfo::Unknown) &&
  2456. LHSFolds != RHSFolds) {
  2457. unfoldSelectInstr(Pred, BB, SI, CondLHS, I);
  2458. return true;
  2459. }
  2460. }
  2461. return false;
  2462. }
  2463. /// tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the
  2464. /// same BB in the form
  2465. /// bb:
  2466. /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
  2467. /// %s = select %p, trueval, falseval
  2468. ///
  2469. /// or
  2470. ///
  2471. /// bb:
  2472. /// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ...
  2473. /// %c = cmp %p, 0
  2474. /// %s = select %c, trueval, falseval
  2475. ///
  2476. /// And expand the select into a branch structure. This later enables
  2477. /// jump-threading over bb in this pass.
  2478. ///
  2479. /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
  2480. /// select if the associated PHI has at least one constant. If the unfolded
  2481. /// select is not jump-threaded, it will be folded again in the later
  2482. /// optimizations.
  2483. bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) {
  2484. // This transform would reduce the quality of msan diagnostics.
  2485. // Disable this transform under MemorySanitizer.
  2486. if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
  2487. return false;
  2488. // If threading this would thread across a loop header, don't thread the edge.
  2489. // See the comments above findLoopHeaders for justifications and caveats.
  2490. if (LoopHeaders.count(BB))
  2491. return false;
  2492. for (BasicBlock::iterator BI = BB->begin();
  2493. PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
  2494. // Look for a Phi having at least one constant incoming value.
  2495. if (llvm::all_of(PN->incoming_values(),
  2496. [](Value *V) { return !isa<ConstantInt>(V); }))
  2497. continue;
  2498. auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
  2499. using namespace PatternMatch;
  2500. // Check if SI is in BB and use V as condition.
  2501. if (SI->getParent() != BB)
  2502. return false;
  2503. Value *Cond = SI->getCondition();
  2504. bool IsAndOr = match(SI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()));
  2505. return Cond && Cond == V && Cond->getType()->isIntegerTy(1) && !IsAndOr;
  2506. };
  2507. SelectInst *SI = nullptr;
  2508. for (Use &U : PN->uses()) {
  2509. if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
  2510. // Look for a ICmp in BB that compares PN with a constant and is the
  2511. // condition of a Select.
  2512. if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
  2513. isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
  2514. if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
  2515. if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
  2516. SI = SelectI;
  2517. break;
  2518. }
  2519. } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
  2520. // Look for a Select in BB that uses PN as condition.
  2521. if (isUnfoldCandidate(SelectI, U.get())) {
  2522. SI = SelectI;
  2523. break;
  2524. }
  2525. }
  2526. }
  2527. if (!SI)
  2528. continue;
  2529. // Expand the select.
  2530. Value *Cond = SI->getCondition();
  2531. if (InsertFreezeWhenUnfoldingSelect &&
  2532. !isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI,
  2533. &DTU->getDomTree()))
  2534. Cond = new FreezeInst(Cond, "cond.fr", SI);
  2535. Instruction *Term = SplitBlockAndInsertIfThen(Cond, SI, false);
  2536. BasicBlock *SplitBB = SI->getParent();
  2537. BasicBlock *NewBB = Term->getParent();
  2538. PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
  2539. NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
  2540. NewPN->addIncoming(SI->getFalseValue(), BB);
  2541. SI->replaceAllUsesWith(NewPN);
  2542. SI->eraseFromParent();
  2543. // NewBB and SplitBB are newly created blocks which require insertion.
  2544. std::vector<DominatorTree::UpdateType> Updates;
  2545. Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
  2546. Updates.push_back({DominatorTree::Insert, BB, SplitBB});
  2547. Updates.push_back({DominatorTree::Insert, BB, NewBB});
  2548. Updates.push_back({DominatorTree::Insert, NewBB, SplitBB});
  2549. // BB's successors were moved to SplitBB, update DTU accordingly.
  2550. for (auto *Succ : successors(SplitBB)) {
  2551. Updates.push_back({DominatorTree::Delete, BB, Succ});
  2552. Updates.push_back({DominatorTree::Insert, SplitBB, Succ});
  2553. }
  2554. DTU->applyUpdatesPermissive(Updates);
  2555. return true;
  2556. }
  2557. return false;
  2558. }
  2559. /// Try to propagate a guard from the current BB into one of its predecessors
  2560. /// in case if another branch of execution implies that the condition of this
  2561. /// guard is always true. Currently we only process the simplest case that
  2562. /// looks like:
  2563. ///
  2564. /// Start:
  2565. /// %cond = ...
  2566. /// br i1 %cond, label %T1, label %F1
  2567. /// T1:
  2568. /// br label %Merge
  2569. /// F1:
  2570. /// br label %Merge
  2571. /// Merge:
  2572. /// %condGuard = ...
  2573. /// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
  2574. ///
  2575. /// And cond either implies condGuard or !condGuard. In this case all the
  2576. /// instructions before the guard can be duplicated in both branches, and the
  2577. /// guard is then threaded to one of them.
  2578. bool JumpThreadingPass::processGuards(BasicBlock *BB) {
  2579. using namespace PatternMatch;
  2580. // We only want to deal with two predecessors.
  2581. BasicBlock *Pred1, *Pred2;
  2582. auto PI = pred_begin(BB), PE = pred_end(BB);
  2583. if (PI == PE)
  2584. return false;
  2585. Pred1 = *PI++;
  2586. if (PI == PE)
  2587. return false;
  2588. Pred2 = *PI++;
  2589. if (PI != PE)
  2590. return false;
  2591. if (Pred1 == Pred2)
  2592. return false;
  2593. // Try to thread one of the guards of the block.
  2594. // TODO: Look up deeper than to immediate predecessor?
  2595. auto *Parent = Pred1->getSinglePredecessor();
  2596. if (!Parent || Parent != Pred2->getSinglePredecessor())
  2597. return false;
  2598. if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
  2599. for (auto &I : *BB)
  2600. if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&I), BI))
  2601. return true;
  2602. return false;
  2603. }
  2604. /// Try to propagate the guard from BB which is the lower block of a diamond
  2605. /// to one of its branches, in case if diamond's condition implies guard's
  2606. /// condition.
  2607. bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard,
  2608. BranchInst *BI) {
  2609. assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?");
  2610. assert(BI->isConditional() && "Unconditional branch has 2 successors?");
  2611. Value *GuardCond = Guard->getArgOperand(0);
  2612. Value *BranchCond = BI->getCondition();
  2613. BasicBlock *TrueDest = BI->getSuccessor(0);
  2614. BasicBlock *FalseDest = BI->getSuccessor(1);
  2615. auto &DL = BB->getModule()->getDataLayout();
  2616. bool TrueDestIsSafe = false;
  2617. bool FalseDestIsSafe = false;
  2618. // True dest is safe if BranchCond => GuardCond.
  2619. auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
  2620. if (Impl && *Impl)
  2621. TrueDestIsSafe = true;
  2622. else {
  2623. // False dest is safe if !BranchCond => GuardCond.
  2624. Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false);
  2625. if (Impl && *Impl)
  2626. FalseDestIsSafe = true;
  2627. }
  2628. if (!TrueDestIsSafe && !FalseDestIsSafe)
  2629. return false;
  2630. BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
  2631. BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
  2632. ValueToValueMapTy UnguardedMapping, GuardedMapping;
  2633. Instruction *AfterGuard = Guard->getNextNode();
  2634. unsigned Cost =
  2635. getJumpThreadDuplicationCost(TTI, BB, AfterGuard, BBDupThreshold);
  2636. if (Cost > BBDupThreshold)
  2637. return false;
  2638. // Duplicate all instructions before the guard and the guard itself to the
  2639. // branch where implication is not proved.
  2640. BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween(
  2641. BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
  2642. assert(GuardedBlock && "Could not create the guarded block?");
  2643. // Duplicate all instructions before the guard in the unguarded branch.
  2644. // Since we have successfully duplicated the guarded block and this block
  2645. // has fewer instructions, we expect it to succeed.
  2646. BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween(
  2647. BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
  2648. assert(UnguardedBlock && "Could not create the unguarded block?");
  2649. LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block "
  2650. << GuardedBlock->getName() << "\n");
  2651. // Some instructions before the guard may still have uses. For them, we need
  2652. // to create Phi nodes merging their copies in both guarded and unguarded
  2653. // branches. Those instructions that have no uses can be just removed.
  2654. SmallVector<Instruction *, 4> ToRemove;
  2655. for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
  2656. if (!isa<PHINode>(&*BI))
  2657. ToRemove.push_back(&*BI);
  2658. Instruction *InsertionPoint = &*BB->getFirstInsertionPt();
  2659. assert(InsertionPoint && "Empty block?");
  2660. // Substitute with Phis & remove.
  2661. for (auto *Inst : reverse(ToRemove)) {
  2662. if (!Inst->use_empty()) {
  2663. PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
  2664. NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
  2665. NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
  2666. NewPN->insertBefore(InsertionPoint);
  2667. Inst->replaceAllUsesWith(NewPN);
  2668. }
  2669. Inst->eraseFromParent();
  2670. }
  2671. return true;
  2672. }