BasicBlockUtils.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999
  1. //===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
  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 family of functions perform manipulations on basic blocks, and
  10. // instructions contained within basic blocks.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Analysis/CFG.h"
  19. #include "llvm/Analysis/DomTreeUpdater.h"
  20. #include "llvm/Analysis/LoopInfo.h"
  21. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  22. #include "llvm/Analysis/MemorySSAUpdater.h"
  23. #include "llvm/IR/BasicBlock.h"
  24. #include "llvm/IR/CFG.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DebugInfo.h"
  27. #include "llvm/IR/DebugInfoMetadata.h"
  28. #include "llvm/IR/Dominators.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/InstrTypes.h"
  31. #include "llvm/IR/Instruction.h"
  32. #include "llvm/IR/Instructions.h"
  33. #include "llvm/IR/IntrinsicInst.h"
  34. #include "llvm/IR/LLVMContext.h"
  35. #include "llvm/IR/Type.h"
  36. #include "llvm/IR/User.h"
  37. #include "llvm/IR/Value.h"
  38. #include "llvm/IR/ValueHandle.h"
  39. #include "llvm/Support/Casting.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Transforms/Utils/Local.h"
  44. #include <cassert>
  45. #include <cstdint>
  46. #include <string>
  47. #include <utility>
  48. #include <vector>
  49. using namespace llvm;
  50. #define DEBUG_TYPE "basicblock-utils"
  51. static cl::opt<unsigned> MaxDeoptOrUnreachableSuccessorCheckDepth(
  52. "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
  53. cl::desc("Set the maximum path length when checking whether a basic block "
  54. "is followed by a block that either has a terminating "
  55. "deoptimizing call or is terminated with an unreachable"));
  56. void llvm::detachDeadBlocks(
  57. ArrayRef<BasicBlock *> BBs,
  58. SmallVectorImpl<DominatorTree::UpdateType> *Updates,
  59. bool KeepOneInputPHIs) {
  60. for (auto *BB : BBs) {
  61. // Loop through all of our successors and make sure they know that one
  62. // of their predecessors is going away.
  63. SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
  64. for (BasicBlock *Succ : successors(BB)) {
  65. Succ->removePredecessor(BB, KeepOneInputPHIs);
  66. if (Updates && UniqueSuccessors.insert(Succ).second)
  67. Updates->push_back({DominatorTree::Delete, BB, Succ});
  68. }
  69. // Zap all the instructions in the block.
  70. while (!BB->empty()) {
  71. Instruction &I = BB->back();
  72. // If this instruction is used, replace uses with an arbitrary value.
  73. // Because control flow can't get here, we don't care what we replace the
  74. // value with. Note that since this block is unreachable, and all values
  75. // contained within it must dominate their uses, that all uses will
  76. // eventually be removed (they are themselves dead).
  77. if (!I.use_empty())
  78. I.replaceAllUsesWith(PoisonValue::get(I.getType()));
  79. BB->back().eraseFromParent();
  80. }
  81. new UnreachableInst(BB->getContext(), BB);
  82. assert(BB->size() == 1 &&
  83. isa<UnreachableInst>(BB->getTerminator()) &&
  84. "The successor list of BB isn't empty before "
  85. "applying corresponding DTU updates.");
  86. }
  87. }
  88. void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
  89. bool KeepOneInputPHIs) {
  90. DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
  91. }
  92. void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
  93. bool KeepOneInputPHIs) {
  94. #ifndef NDEBUG
  95. // Make sure that all predecessors of each dead block is also dead.
  96. SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
  97. assert(Dead.size() == BBs.size() && "Duplicating blocks?");
  98. for (auto *BB : Dead)
  99. for (BasicBlock *Pred : predecessors(BB))
  100. assert(Dead.count(Pred) && "All predecessors must be dead!");
  101. #endif
  102. SmallVector<DominatorTree::UpdateType, 4> Updates;
  103. detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
  104. if (DTU)
  105. DTU->applyUpdates(Updates);
  106. for (BasicBlock *BB : BBs)
  107. if (DTU)
  108. DTU->deleteBB(BB);
  109. else
  110. BB->eraseFromParent();
  111. }
  112. bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
  113. bool KeepOneInputPHIs) {
  114. df_iterator_default_set<BasicBlock*> Reachable;
  115. // Mark all reachable blocks.
  116. for (BasicBlock *BB : depth_first_ext(&F, Reachable))
  117. (void)BB/* Mark all reachable blocks */;
  118. // Collect all dead blocks.
  119. std::vector<BasicBlock*> DeadBlocks;
  120. for (BasicBlock &BB : F)
  121. if (!Reachable.count(&BB))
  122. DeadBlocks.push_back(&BB);
  123. // Delete the dead blocks.
  124. DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
  125. return !DeadBlocks.empty();
  126. }
  127. bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
  128. MemoryDependenceResults *MemDep) {
  129. if (!isa<PHINode>(BB->begin()))
  130. return false;
  131. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  132. if (PN->getIncomingValue(0) != PN)
  133. PN->replaceAllUsesWith(PN->getIncomingValue(0));
  134. else
  135. PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
  136. if (MemDep)
  137. MemDep->removeInstruction(PN); // Memdep updates AA itself.
  138. PN->eraseFromParent();
  139. }
  140. return true;
  141. }
  142. bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI,
  143. MemorySSAUpdater *MSSAU) {
  144. // Recursively deleting a PHI may cause multiple PHIs to be deleted
  145. // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
  146. SmallVector<WeakTrackingVH, 8> PHIs;
  147. for (PHINode &PN : BB->phis())
  148. PHIs.push_back(&PN);
  149. bool Changed = false;
  150. for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
  151. if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
  152. Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
  153. return Changed;
  154. }
  155. bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
  156. LoopInfo *LI, MemorySSAUpdater *MSSAU,
  157. MemoryDependenceResults *MemDep,
  158. bool PredecessorWithTwoSuccessors,
  159. DominatorTree *DT) {
  160. if (BB->hasAddressTaken())
  161. return false;
  162. // Can't merge if there are multiple predecessors, or no predecessors.
  163. BasicBlock *PredBB = BB->getUniquePredecessor();
  164. if (!PredBB) return false;
  165. // Don't break self-loops.
  166. if (PredBB == BB) return false;
  167. // Don't break unwinding instructions or terminators with other side-effects.
  168. Instruction *PTI = PredBB->getTerminator();
  169. if (PTI->isExceptionalTerminator() || PTI->mayHaveSideEffects())
  170. return false;
  171. // Can't merge if there are multiple distinct successors.
  172. if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
  173. return false;
  174. // Currently only allow PredBB to have two predecessors, one being BB.
  175. // Update BI to branch to BB's only successor instead of BB.
  176. BranchInst *PredBB_BI;
  177. BasicBlock *NewSucc = nullptr;
  178. unsigned FallThruPath;
  179. if (PredecessorWithTwoSuccessors) {
  180. if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
  181. return false;
  182. BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
  183. if (!BB_JmpI || !BB_JmpI->isUnconditional())
  184. return false;
  185. NewSucc = BB_JmpI->getSuccessor(0);
  186. FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
  187. }
  188. // Can't merge if there is PHI loop.
  189. for (PHINode &PN : BB->phis())
  190. if (llvm::is_contained(PN.incoming_values(), &PN))
  191. return false;
  192. LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
  193. << PredBB->getName() << "\n");
  194. // Begin by getting rid of unneeded PHIs.
  195. SmallVector<AssertingVH<Value>, 4> IncomingValues;
  196. if (isa<PHINode>(BB->front())) {
  197. for (PHINode &PN : BB->phis())
  198. if (!isa<PHINode>(PN.getIncomingValue(0)) ||
  199. cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
  200. IncomingValues.push_back(PN.getIncomingValue(0));
  201. FoldSingleEntryPHINodes(BB, MemDep);
  202. }
  203. if (DT) {
  204. assert(!DTU && "cannot use both DT and DTU for updates");
  205. DomTreeNode *PredNode = DT->getNode(PredBB);
  206. DomTreeNode *BBNode = DT->getNode(BB);
  207. if (PredNode) {
  208. assert(BBNode && "PredNode unreachable but BBNode reachable?");
  209. for (DomTreeNode *C : to_vector(BBNode->children()))
  210. C->setIDom(PredNode);
  211. }
  212. }
  213. // DTU update: Collect all the edges that exit BB.
  214. // These dominator edges will be redirected from Pred.
  215. std::vector<DominatorTree::UpdateType> Updates;
  216. if (DTU) {
  217. assert(!DT && "cannot use both DT and DTU for updates");
  218. // To avoid processing the same predecessor more than once.
  219. SmallPtrSet<BasicBlock *, 8> SeenSuccs;
  220. SmallPtrSet<BasicBlock *, 2> SuccsOfPredBB(succ_begin(PredBB),
  221. succ_end(PredBB));
  222. Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
  223. // Add insert edges first. Experimentally, for the particular case of two
  224. // blocks that can be merged, with a single successor and single predecessor
  225. // respectively, it is beneficial to have all insert updates first. Deleting
  226. // edges first may lead to unreachable blocks, followed by inserting edges
  227. // making the blocks reachable again. Such DT updates lead to high compile
  228. // times. We add inserts before deletes here to reduce compile time.
  229. for (BasicBlock *SuccOfBB : successors(BB))
  230. // This successor of BB may already be a PredBB's successor.
  231. if (!SuccsOfPredBB.contains(SuccOfBB))
  232. if (SeenSuccs.insert(SuccOfBB).second)
  233. Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
  234. SeenSuccs.clear();
  235. for (BasicBlock *SuccOfBB : successors(BB))
  236. if (SeenSuccs.insert(SuccOfBB).second)
  237. Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
  238. Updates.push_back({DominatorTree::Delete, PredBB, BB});
  239. }
  240. Instruction *STI = BB->getTerminator();
  241. Instruction *Start = &*BB->begin();
  242. // If there's nothing to move, mark the starting instruction as the last
  243. // instruction in the block. Terminator instruction is handled separately.
  244. if (Start == STI)
  245. Start = PTI;
  246. // Move all definitions in the successor to the predecessor...
  247. PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
  248. if (MSSAU)
  249. MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
  250. // Make all PHI nodes that referred to BB now refer to Pred as their
  251. // source...
  252. BB->replaceAllUsesWith(PredBB);
  253. if (PredecessorWithTwoSuccessors) {
  254. // Delete the unconditional branch from BB.
  255. BB->back().eraseFromParent();
  256. // Update branch in the predecessor.
  257. PredBB_BI->setSuccessor(FallThruPath, NewSucc);
  258. } else {
  259. // Delete the unconditional branch from the predecessor.
  260. PredBB->back().eraseFromParent();
  261. // Move terminator instruction.
  262. PredBB->splice(PredBB->end(), BB);
  263. // Terminator may be a memory accessing instruction too.
  264. if (MSSAU)
  265. if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
  266. MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
  267. MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
  268. }
  269. // Add unreachable to now empty BB.
  270. new UnreachableInst(BB->getContext(), BB);
  271. // Inherit predecessors name if it exists.
  272. if (!PredBB->hasName())
  273. PredBB->takeName(BB);
  274. if (LI)
  275. LI->removeBlock(BB);
  276. if (MemDep)
  277. MemDep->invalidateCachedPredecessors();
  278. if (DTU)
  279. DTU->applyUpdates(Updates);
  280. if (DT) {
  281. assert(succ_empty(BB) &&
  282. "successors should have been transferred to PredBB");
  283. DT->eraseNode(BB);
  284. }
  285. // Finally, erase the old block and update dominator info.
  286. DeleteDeadBlock(BB, DTU);
  287. return true;
  288. }
  289. bool llvm::MergeBlockSuccessorsIntoGivenBlocks(
  290. SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU,
  291. LoopInfo *LI) {
  292. assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
  293. bool BlocksHaveBeenMerged = false;
  294. while (!MergeBlocks.empty()) {
  295. BasicBlock *BB = *MergeBlocks.begin();
  296. BasicBlock *Dest = BB->getSingleSuccessor();
  297. if (Dest && (!L || L->contains(Dest))) {
  298. BasicBlock *Fold = Dest->getUniquePredecessor();
  299. (void)Fold;
  300. if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
  301. assert(Fold == BB &&
  302. "Expecting BB to be unique predecessor of the Dest block");
  303. MergeBlocks.erase(Dest);
  304. BlocksHaveBeenMerged = true;
  305. } else
  306. MergeBlocks.erase(BB);
  307. } else
  308. MergeBlocks.erase(BB);
  309. }
  310. return BlocksHaveBeenMerged;
  311. }
  312. /// Remove redundant instructions within sequences of consecutive dbg.value
  313. /// instructions. This is done using a backward scan to keep the last dbg.value
  314. /// describing a specific variable/fragment.
  315. ///
  316. /// BackwardScan strategy:
  317. /// ----------------------
  318. /// Given a sequence of consecutive DbgValueInst like this
  319. ///
  320. /// dbg.value ..., "x", FragmentX1 (*)
  321. /// dbg.value ..., "y", FragmentY1
  322. /// dbg.value ..., "x", FragmentX2
  323. /// dbg.value ..., "x", FragmentX1 (**)
  324. ///
  325. /// then the instruction marked with (*) can be removed (it is guaranteed to be
  326. /// obsoleted by the instruction marked with (**) as the latter instruction is
  327. /// describing the same variable using the same fragment info).
  328. ///
  329. /// Possible improvements:
  330. /// - Check fully overlapping fragments and not only identical fragments.
  331. /// - Support dbg.addr, dbg.declare. dbg.label, and possibly other meta
  332. /// instructions being part of the sequence of consecutive instructions.
  333. static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
  334. SmallVector<DbgValueInst *, 8> ToBeRemoved;
  335. SmallDenseSet<DebugVariable> VariableSet;
  336. for (auto &I : reverse(*BB)) {
  337. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
  338. DebugVariable Key(DVI->getVariable(),
  339. DVI->getExpression(),
  340. DVI->getDebugLoc()->getInlinedAt());
  341. auto R = VariableSet.insert(Key);
  342. // If the variable fragment hasn't been seen before then we don't want
  343. // to remove this dbg intrinsic.
  344. if (R.second)
  345. continue;
  346. if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI)) {
  347. // Don't delete dbg.assign intrinsics that are linked to instructions.
  348. if (!at::getAssignmentInsts(DAI).empty())
  349. continue;
  350. // Unlinked dbg.assign intrinsics can be treated like dbg.values.
  351. }
  352. // If the same variable fragment is described more than once it is enough
  353. // to keep the last one (i.e. the first found since we for reverse
  354. // iteration).
  355. ToBeRemoved.push_back(DVI);
  356. continue;
  357. }
  358. // Sequence with consecutive dbg.value instrs ended. Clear the map to
  359. // restart identifying redundant instructions if case we find another
  360. // dbg.value sequence.
  361. VariableSet.clear();
  362. }
  363. for (auto &Instr : ToBeRemoved)
  364. Instr->eraseFromParent();
  365. return !ToBeRemoved.empty();
  366. }
  367. /// Remove redundant dbg.value instructions using a forward scan. This can
  368. /// remove a dbg.value instruction that is redundant due to indicating that a
  369. /// variable has the same value as already being indicated by an earlier
  370. /// dbg.value.
  371. ///
  372. /// ForwardScan strategy:
  373. /// ---------------------
  374. /// Given two identical dbg.value instructions, separated by a block of
  375. /// instructions that isn't describing the same variable, like this
  376. ///
  377. /// dbg.value X1, "x", FragmentX1 (**)
  378. /// <block of instructions, none being "dbg.value ..., "x", ...">
  379. /// dbg.value X1, "x", FragmentX1 (*)
  380. ///
  381. /// then the instruction marked with (*) can be removed. Variable "x" is already
  382. /// described as being mapped to the SSA value X1.
  383. ///
  384. /// Possible improvements:
  385. /// - Keep track of non-overlapping fragments.
  386. static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
  387. SmallVector<DbgValueInst *, 8> ToBeRemoved;
  388. DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
  389. VariableMap;
  390. for (auto &I : *BB) {
  391. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
  392. DebugVariable Key(DVI->getVariable(), std::nullopt,
  393. DVI->getDebugLoc()->getInlinedAt());
  394. auto VMI = VariableMap.find(Key);
  395. auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
  396. // A dbg.assign with no linked instructions can be treated like a
  397. // dbg.value (i.e. can be deleted).
  398. bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
  399. // Update the map if we found a new value/expression describing the
  400. // variable, or if the variable wasn't mapped already.
  401. SmallVector<Value *, 4> Values(DVI->getValues());
  402. if (VMI == VariableMap.end() || VMI->second.first != Values ||
  403. VMI->second.second != DVI->getExpression()) {
  404. // Use a sentinal value (nullptr) for the DIExpression when we see a
  405. // linked dbg.assign so that the next debug intrinsic will never match
  406. // it (i.e. always treat linked dbg.assigns as if they're unique).
  407. if (IsDbgValueKind)
  408. VariableMap[Key] = {Values, DVI->getExpression()};
  409. else
  410. VariableMap[Key] = {Values, nullptr};
  411. continue;
  412. }
  413. // Don't delete dbg.assign intrinsics that are linked to instructions.
  414. if (!IsDbgValueKind)
  415. continue;
  416. ToBeRemoved.push_back(DVI);
  417. }
  418. }
  419. for (auto &Instr : ToBeRemoved)
  420. Instr->eraseFromParent();
  421. return !ToBeRemoved.empty();
  422. }
  423. /// Remove redundant undef dbg.assign intrinsic from an entry block using a
  424. /// forward scan.
  425. /// Strategy:
  426. /// ---------------------
  427. /// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
  428. /// linked to an intrinsic, and don't share an aggregate variable with a debug
  429. /// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
  430. /// that come before non-undef debug intrinsics for the variable are
  431. /// deleted. Given:
  432. ///
  433. /// dbg.assign undef, "x", FragmentX1 (*)
  434. /// <block of instructions, none being "dbg.value ..., "x", ...">
  435. /// dbg.value %V, "x", FragmentX2
  436. /// <block of instructions, none being "dbg.value ..., "x", ...">
  437. /// dbg.assign undef, "x", FragmentX1
  438. ///
  439. /// then (only) the instruction marked with (*) can be removed.
  440. /// Possible improvements:
  441. /// - Keep track of non-overlapping fragments.
  442. static bool remomveUndefDbgAssignsFromEntryBlock(BasicBlock *BB) {
  443. assert(BB->isEntryBlock() && "expected entry block");
  444. SmallVector<DbgAssignIntrinsic *, 8> ToBeRemoved;
  445. DenseSet<DebugVariable> SeenDefForAggregate;
  446. // Returns the DebugVariable for DVI with no fragment info.
  447. auto GetAggregateVariable = [](DbgValueInst *DVI) {
  448. return DebugVariable(DVI->getVariable(), std::nullopt,
  449. DVI->getDebugLoc()->getInlinedAt());
  450. };
  451. // Remove undef dbg.assign intrinsics that are encountered before
  452. // any non-undef intrinsics from the entry block.
  453. for (auto &I : *BB) {
  454. DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I);
  455. if (!DVI)
  456. continue;
  457. auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
  458. bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
  459. DebugVariable Aggregate = GetAggregateVariable(DVI);
  460. if (!SeenDefForAggregate.contains(Aggregate)) {
  461. bool IsKill = DVI->isKillLocation() && IsDbgValueKind;
  462. if (!IsKill) {
  463. SeenDefForAggregate.insert(Aggregate);
  464. } else if (DAI) {
  465. ToBeRemoved.push_back(DAI);
  466. }
  467. }
  468. }
  469. for (DbgAssignIntrinsic *DAI : ToBeRemoved)
  470. DAI->eraseFromParent();
  471. return !ToBeRemoved.empty();
  472. }
  473. bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) {
  474. bool MadeChanges = false;
  475. // By using the "backward scan" strategy before the "forward scan" strategy we
  476. // can remove both dbg.value (2) and (3) in a situation like this:
  477. //
  478. // (1) dbg.value V1, "x", DIExpression()
  479. // ...
  480. // (2) dbg.value V2, "x", DIExpression()
  481. // (3) dbg.value V1, "x", DIExpression()
  482. //
  483. // The backward scan will remove (2), it is made obsolete by (3). After
  484. // getting (2) out of the way, the foward scan will remove (3) since "x"
  485. // already is described as having the value V1 at (1).
  486. MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB);
  487. if (BB->isEntryBlock() &&
  488. isAssignmentTrackingEnabled(*BB->getParent()->getParent()))
  489. MadeChanges |= remomveUndefDbgAssignsFromEntryBlock(BB);
  490. MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB);
  491. if (MadeChanges)
  492. LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
  493. << BB->getName() << "\n");
  494. return MadeChanges;
  495. }
  496. void llvm::ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V) {
  497. Instruction &I = *BI;
  498. // Replaces all of the uses of the instruction with uses of the value
  499. I.replaceAllUsesWith(V);
  500. // Make sure to propagate a name if there is one already.
  501. if (I.hasName() && !V->hasName())
  502. V->takeName(&I);
  503. // Delete the unnecessary instruction now...
  504. BI = BI->eraseFromParent();
  505. }
  506. void llvm::ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI,
  507. Instruction *I) {
  508. assert(I->getParent() == nullptr &&
  509. "ReplaceInstWithInst: Instruction already inserted into basic block!");
  510. // Copy debug location to newly added instruction, if it wasn't already set
  511. // by the caller.
  512. if (!I->getDebugLoc())
  513. I->setDebugLoc(BI->getDebugLoc());
  514. // Insert the new instruction into the basic block...
  515. BasicBlock::iterator New = I->insertInto(BB, BI);
  516. // Replace all uses of the old instruction, and delete it.
  517. ReplaceInstWithValue(BI, I);
  518. // Move BI back to point to the newly inserted instruction
  519. BI = New;
  520. }
  521. bool llvm::IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB) {
  522. // Remember visited blocks to avoid infinite loop
  523. SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
  524. unsigned Depth = 0;
  525. while (BB && Depth++ < MaxDeoptOrUnreachableSuccessorCheckDepth &&
  526. VisitedBlocks.insert(BB).second) {
  527. if (BB->getTerminatingDeoptimizeCall() ||
  528. isa<UnreachableInst>(BB->getTerminator()))
  529. return true;
  530. BB = BB->getUniqueSuccessor();
  531. }
  532. return false;
  533. }
  534. void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
  535. BasicBlock::iterator BI(From);
  536. ReplaceInstWithInst(From->getParent(), BI, To);
  537. }
  538. BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
  539. LoopInfo *LI, MemorySSAUpdater *MSSAU,
  540. const Twine &BBName) {
  541. unsigned SuccNum = GetSuccessorNumber(BB, Succ);
  542. Instruction *LatchTerm = BB->getTerminator();
  543. CriticalEdgeSplittingOptions Options =
  544. CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA();
  545. if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
  546. // If it is a critical edge, and the succesor is an exception block, handle
  547. // the split edge logic in this specific function
  548. if (Succ->isEHPad())
  549. return ehAwareSplitEdge(BB, Succ, nullptr, nullptr, Options, BBName);
  550. // If this is a critical edge, let SplitKnownCriticalEdge do it.
  551. return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
  552. }
  553. // If the edge isn't critical, then BB has a single successor or Succ has a
  554. // single pred. Split the block.
  555. if (BasicBlock *SP = Succ->getSinglePredecessor()) {
  556. // If the successor only has a single pred, split the top of the successor
  557. // block.
  558. assert(SP == BB && "CFG broken");
  559. SP = nullptr;
  560. return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
  561. /*Before=*/true);
  562. }
  563. // Otherwise, if BB has a single successor, split it at the bottom of the
  564. // block.
  565. assert(BB->getTerminator()->getNumSuccessors() == 1 &&
  566. "Should have a single succ!");
  567. return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
  568. }
  569. void llvm::setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
  570. if (auto *II = dyn_cast<InvokeInst>(TI))
  571. II->setUnwindDest(Succ);
  572. else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
  573. CS->setUnwindDest(Succ);
  574. else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
  575. CR->setUnwindDest(Succ);
  576. else
  577. llvm_unreachable("unexpected terminator instruction");
  578. }
  579. void llvm::updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
  580. BasicBlock *NewPred, PHINode *Until) {
  581. int BBIdx = 0;
  582. for (PHINode &PN : DestBB->phis()) {
  583. // We manually update the LandingPadReplacement PHINode and it is the last
  584. // PHI Node. So, if we find it, we are done.
  585. if (Until == &PN)
  586. break;
  587. // Reuse the previous value of BBIdx if it lines up. In cases where we
  588. // have multiple phi nodes with *lots* of predecessors, this is a speed
  589. // win because we don't have to scan the PHI looking for TIBB. This
  590. // happens because the BB list of PHI nodes are usually in the same
  591. // order.
  592. if (PN.getIncomingBlock(BBIdx) != OldPred)
  593. BBIdx = PN.getBasicBlockIndex(OldPred);
  594. assert(BBIdx != -1 && "Invalid PHI Index!");
  595. PN.setIncomingBlock(BBIdx, NewPred);
  596. }
  597. }
  598. BasicBlock *llvm::ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
  599. LandingPadInst *OriginalPad,
  600. PHINode *LandingPadReplacement,
  601. const CriticalEdgeSplittingOptions &Options,
  602. const Twine &BBName) {
  603. auto *PadInst = Succ->getFirstNonPHI();
  604. if (!LandingPadReplacement && !PadInst->isEHPad())
  605. return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
  606. auto *LI = Options.LI;
  607. SmallVector<BasicBlock *, 4> LoopPreds;
  608. // Check if extra modifications will be required to preserve loop-simplify
  609. // form after splitting. If it would require splitting blocks with IndirectBr
  610. // terminators, bail out if preserving loop-simplify form is requested.
  611. if (Options.PreserveLoopSimplify && LI) {
  612. if (Loop *BBLoop = LI->getLoopFor(BB)) {
  613. // The only way that we can break LoopSimplify form by splitting a
  614. // critical edge is when there exists some edge from BBLoop to Succ *and*
  615. // the only edge into Succ from outside of BBLoop is that of NewBB after
  616. // the split. If the first isn't true, then LoopSimplify still holds,
  617. // NewBB is the new exit block and it has no non-loop predecessors. If the
  618. // second isn't true, then Succ was not in LoopSimplify form prior to
  619. // the split as it had a non-loop predecessor. In both of these cases,
  620. // the predecessor must be directly in BBLoop, not in a subloop, or again
  621. // LoopSimplify doesn't hold.
  622. for (BasicBlock *P : predecessors(Succ)) {
  623. if (P == BB)
  624. continue; // The new block is known.
  625. if (LI->getLoopFor(P) != BBLoop) {
  626. // Loop is not in LoopSimplify form, no need to re simplify after
  627. // splitting edge.
  628. LoopPreds.clear();
  629. break;
  630. }
  631. LoopPreds.push_back(P);
  632. }
  633. // Loop-simplify form can be preserved, if we can split all in-loop
  634. // predecessors.
  635. if (any_of(LoopPreds, [](BasicBlock *Pred) {
  636. return isa<IndirectBrInst>(Pred->getTerminator());
  637. })) {
  638. return nullptr;
  639. }
  640. }
  641. }
  642. auto *NewBB =
  643. BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
  644. setUnwindEdgeTo(BB->getTerminator(), NewBB);
  645. updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
  646. if (LandingPadReplacement) {
  647. auto *NewLP = OriginalPad->clone();
  648. auto *Terminator = BranchInst::Create(Succ, NewBB);
  649. NewLP->insertBefore(Terminator);
  650. LandingPadReplacement->addIncoming(NewLP, NewBB);
  651. } else {
  652. Value *ParentPad = nullptr;
  653. if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
  654. ParentPad = FuncletPad->getParentPad();
  655. else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
  656. ParentPad = CatchSwitch->getParentPad();
  657. else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
  658. ParentPad = CleanupPad->getParentPad();
  659. else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
  660. ParentPad = LandingPad->getParent();
  661. else
  662. llvm_unreachable("handling for other EHPads not implemented yet");
  663. auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
  664. CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
  665. }
  666. auto *DT = Options.DT;
  667. auto *MSSAU = Options.MSSAU;
  668. if (!DT && !LI)
  669. return NewBB;
  670. if (DT) {
  671. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  672. SmallVector<DominatorTree::UpdateType, 3> Updates;
  673. Updates.push_back({DominatorTree::Insert, BB, NewBB});
  674. Updates.push_back({DominatorTree::Insert, NewBB, Succ});
  675. Updates.push_back({DominatorTree::Delete, BB, Succ});
  676. DTU.applyUpdates(Updates);
  677. DTU.flush();
  678. if (MSSAU) {
  679. MSSAU->applyUpdates(Updates, *DT);
  680. if (VerifyMemorySSA)
  681. MSSAU->getMemorySSA()->verifyMemorySSA();
  682. }
  683. }
  684. if (LI) {
  685. if (Loop *BBLoop = LI->getLoopFor(BB)) {
  686. // If one or the other blocks were not in a loop, the new block is not
  687. // either, and thus LI doesn't need to be updated.
  688. if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
  689. if (BBLoop == SuccLoop) {
  690. // Both in the same loop, the NewBB joins loop.
  691. SuccLoop->addBasicBlockToLoop(NewBB, *LI);
  692. } else if (BBLoop->contains(SuccLoop)) {
  693. // Edge from an outer loop to an inner loop. Add to the outer loop.
  694. BBLoop->addBasicBlockToLoop(NewBB, *LI);
  695. } else if (SuccLoop->contains(BBLoop)) {
  696. // Edge from an inner loop to an outer loop. Add to the outer loop.
  697. SuccLoop->addBasicBlockToLoop(NewBB, *LI);
  698. } else {
  699. // Edge from two loops with no containment relation. Because these
  700. // are natural loops, we know that the destination block must be the
  701. // header of its loop (adding a branch into a loop elsewhere would
  702. // create an irreducible loop).
  703. assert(SuccLoop->getHeader() == Succ &&
  704. "Should not create irreducible loops!");
  705. if (Loop *P = SuccLoop->getParentLoop())
  706. P->addBasicBlockToLoop(NewBB, *LI);
  707. }
  708. }
  709. // If BB is in a loop and Succ is outside of that loop, we may need to
  710. // update LoopSimplify form and LCSSA form.
  711. if (!BBLoop->contains(Succ)) {
  712. assert(!BBLoop->contains(NewBB) &&
  713. "Split point for loop exit is contained in loop!");
  714. // Update LCSSA form in the newly created exit block.
  715. if (Options.PreserveLCSSA) {
  716. createPHIsForSplitLoopExit(BB, NewBB, Succ);
  717. }
  718. if (!LoopPreds.empty()) {
  719. BasicBlock *NewExitBB = SplitBlockPredecessors(
  720. Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
  721. if (Options.PreserveLCSSA)
  722. createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
  723. }
  724. }
  725. }
  726. }
  727. return NewBB;
  728. }
  729. void llvm::createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
  730. BasicBlock *SplitBB, BasicBlock *DestBB) {
  731. // SplitBB shouldn't have anything non-trivial in it yet.
  732. assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
  733. SplitBB->isLandingPad()) &&
  734. "SplitBB has non-PHI nodes!");
  735. // For each PHI in the destination block.
  736. for (PHINode &PN : DestBB->phis()) {
  737. int Idx = PN.getBasicBlockIndex(SplitBB);
  738. assert(Idx >= 0 && "Invalid Block Index");
  739. Value *V = PN.getIncomingValue(Idx);
  740. // If the input is a PHI which already satisfies LCSSA, don't create
  741. // a new one.
  742. if (const PHINode *VP = dyn_cast<PHINode>(V))
  743. if (VP->getParent() == SplitBB)
  744. continue;
  745. // Otherwise a new PHI is needed. Create one and populate it.
  746. PHINode *NewPN = PHINode::Create(
  747. PN.getType(), Preds.size(), "split",
  748. SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
  749. for (BasicBlock *BB : Preds)
  750. NewPN->addIncoming(V, BB);
  751. // Update the original PHI.
  752. PN.setIncomingValue(Idx, NewPN);
  753. }
  754. }
  755. unsigned
  756. llvm::SplitAllCriticalEdges(Function &F,
  757. const CriticalEdgeSplittingOptions &Options) {
  758. unsigned NumBroken = 0;
  759. for (BasicBlock &BB : F) {
  760. Instruction *TI = BB.getTerminator();
  761. if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
  762. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  763. if (SplitCriticalEdge(TI, i, Options))
  764. ++NumBroken;
  765. }
  766. return NumBroken;
  767. }
  768. static BasicBlock *SplitBlockImpl(BasicBlock *Old, Instruction *SplitPt,
  769. DomTreeUpdater *DTU, DominatorTree *DT,
  770. LoopInfo *LI, MemorySSAUpdater *MSSAU,
  771. const Twine &BBName, bool Before) {
  772. if (Before) {
  773. DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  774. return splitBlockBefore(Old, SplitPt,
  775. DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
  776. BBName);
  777. }
  778. BasicBlock::iterator SplitIt = SplitPt->getIterator();
  779. while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
  780. ++SplitIt;
  781. assert(SplitIt != SplitPt->getParent()->end());
  782. }
  783. std::string Name = BBName.str();
  784. BasicBlock *New = Old->splitBasicBlock(
  785. SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
  786. // The new block lives in whichever loop the old one did. This preserves
  787. // LCSSA as well, because we force the split point to be after any PHI nodes.
  788. if (LI)
  789. if (Loop *L = LI->getLoopFor(Old))
  790. L->addBasicBlockToLoop(New, *LI);
  791. if (DTU) {
  792. SmallVector<DominatorTree::UpdateType, 8> Updates;
  793. // Old dominates New. New node dominates all other nodes dominated by Old.
  794. SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
  795. Updates.push_back({DominatorTree::Insert, Old, New});
  796. Updates.reserve(Updates.size() + 2 * succ_size(New));
  797. for (BasicBlock *SuccessorOfOld : successors(New))
  798. if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
  799. Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
  800. Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
  801. }
  802. DTU->applyUpdates(Updates);
  803. } else if (DT)
  804. // Old dominates New. New node dominates all other nodes dominated by Old.
  805. if (DomTreeNode *OldNode = DT->getNode(Old)) {
  806. std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
  807. DomTreeNode *NewNode = DT->addNewBlock(New, Old);
  808. for (DomTreeNode *I : Children)
  809. DT->changeImmediateDominator(I, NewNode);
  810. }
  811. // Move MemoryAccesses still tracked in Old, but part of New now.
  812. // Update accesses in successor blocks accordingly.
  813. if (MSSAU)
  814. MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
  815. return New;
  816. }
  817. BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
  818. DominatorTree *DT, LoopInfo *LI,
  819. MemorySSAUpdater *MSSAU, const Twine &BBName,
  820. bool Before) {
  821. return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
  822. Before);
  823. }
  824. BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
  825. DomTreeUpdater *DTU, LoopInfo *LI,
  826. MemorySSAUpdater *MSSAU, const Twine &BBName,
  827. bool Before) {
  828. return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
  829. Before);
  830. }
  831. BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, Instruction *SplitPt,
  832. DomTreeUpdater *DTU, LoopInfo *LI,
  833. MemorySSAUpdater *MSSAU,
  834. const Twine &BBName) {
  835. BasicBlock::iterator SplitIt = SplitPt->getIterator();
  836. while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
  837. ++SplitIt;
  838. std::string Name = BBName.str();
  839. BasicBlock *New = Old->splitBasicBlock(
  840. SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
  841. /* Before=*/true);
  842. // The new block lives in whichever loop the old one did. This preserves
  843. // LCSSA as well, because we force the split point to be after any PHI nodes.
  844. if (LI)
  845. if (Loop *L = LI->getLoopFor(Old))
  846. L->addBasicBlockToLoop(New, *LI);
  847. if (DTU) {
  848. SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
  849. // New dominates Old. The predecessor nodes of the Old node dominate
  850. // New node.
  851. SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
  852. DTUpdates.push_back({DominatorTree::Insert, New, Old});
  853. DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
  854. for (BasicBlock *PredecessorOfOld : predecessors(New))
  855. if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
  856. DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
  857. DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
  858. }
  859. DTU->applyUpdates(DTUpdates);
  860. // Move MemoryAccesses still tracked in Old, but part of New now.
  861. // Update accesses in successor blocks accordingly.
  862. if (MSSAU) {
  863. MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
  864. if (VerifyMemorySSA)
  865. MSSAU->getMemorySSA()->verifyMemorySSA();
  866. }
  867. }
  868. return New;
  869. }
  870. /// Update DominatorTree, LoopInfo, and LCCSA analysis information.
  871. static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
  872. ArrayRef<BasicBlock *> Preds,
  873. DomTreeUpdater *DTU, DominatorTree *DT,
  874. LoopInfo *LI, MemorySSAUpdater *MSSAU,
  875. bool PreserveLCSSA, bool &HasLoopExit) {
  876. // Update dominator tree if available.
  877. if (DTU) {
  878. // Recalculation of DomTree is needed when updating a forward DomTree and
  879. // the Entry BB is replaced.
  880. if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
  881. // The entry block was removed and there is no external interface for
  882. // the dominator tree to be notified of this change. In this corner-case
  883. // we recalculate the entire tree.
  884. DTU->recalculate(*NewBB->getParent());
  885. } else {
  886. // Split block expects NewBB to have a non-empty set of predecessors.
  887. SmallVector<DominatorTree::UpdateType, 8> Updates;
  888. SmallPtrSet<BasicBlock *, 8> UniquePreds;
  889. Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
  890. Updates.reserve(Updates.size() + 2 * Preds.size());
  891. for (auto *Pred : Preds)
  892. if (UniquePreds.insert(Pred).second) {
  893. Updates.push_back({DominatorTree::Insert, Pred, NewBB});
  894. Updates.push_back({DominatorTree::Delete, Pred, OldBB});
  895. }
  896. DTU->applyUpdates(Updates);
  897. }
  898. } else if (DT) {
  899. if (OldBB == DT->getRootNode()->getBlock()) {
  900. assert(NewBB->isEntryBlock());
  901. DT->setNewRoot(NewBB);
  902. } else {
  903. // Split block expects NewBB to have a non-empty set of predecessors.
  904. DT->splitBlock(NewBB);
  905. }
  906. }
  907. // Update MemoryPhis after split if MemorySSA is available
  908. if (MSSAU)
  909. MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
  910. // The rest of the logic is only relevant for updating the loop structures.
  911. if (!LI)
  912. return;
  913. if (DTU && DTU->hasDomTree())
  914. DT = &DTU->getDomTree();
  915. assert(DT && "DT should be available to update LoopInfo!");
  916. Loop *L = LI->getLoopFor(OldBB);
  917. // If we need to preserve loop analyses, collect some information about how
  918. // this split will affect loops.
  919. bool IsLoopEntry = !!L;
  920. bool SplitMakesNewLoopHeader = false;
  921. for (BasicBlock *Pred : Preds) {
  922. // Preds that are not reachable from entry should not be used to identify if
  923. // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
  924. // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
  925. // as true and make the NewBB the header of some loop. This breaks LI.
  926. if (!DT->isReachableFromEntry(Pred))
  927. continue;
  928. // If we need to preserve LCSSA, determine if any of the preds is a loop
  929. // exit.
  930. if (PreserveLCSSA)
  931. if (Loop *PL = LI->getLoopFor(Pred))
  932. if (!PL->contains(OldBB))
  933. HasLoopExit = true;
  934. // If we need to preserve LoopInfo, note whether any of the preds crosses
  935. // an interesting loop boundary.
  936. if (!L)
  937. continue;
  938. if (L->contains(Pred))
  939. IsLoopEntry = false;
  940. else
  941. SplitMakesNewLoopHeader = true;
  942. }
  943. // Unless we have a loop for OldBB, nothing else to do here.
  944. if (!L)
  945. return;
  946. if (IsLoopEntry) {
  947. // Add the new block to the nearest enclosing loop (and not an adjacent
  948. // loop). To find this, examine each of the predecessors and determine which
  949. // loops enclose them, and select the most-nested loop which contains the
  950. // loop containing the block being split.
  951. Loop *InnermostPredLoop = nullptr;
  952. for (BasicBlock *Pred : Preds) {
  953. if (Loop *PredLoop = LI->getLoopFor(Pred)) {
  954. // Seek a loop which actually contains the block being split (to avoid
  955. // adjacent loops).
  956. while (PredLoop && !PredLoop->contains(OldBB))
  957. PredLoop = PredLoop->getParentLoop();
  958. // Select the most-nested of these loops which contains the block.
  959. if (PredLoop && PredLoop->contains(OldBB) &&
  960. (!InnermostPredLoop ||
  961. InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
  962. InnermostPredLoop = PredLoop;
  963. }
  964. }
  965. if (InnermostPredLoop)
  966. InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
  967. } else {
  968. L->addBasicBlockToLoop(NewBB, *LI);
  969. if (SplitMakesNewLoopHeader)
  970. L->moveToHeader(NewBB);
  971. }
  972. }
  973. /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
  974. /// This also updates AliasAnalysis, if available.
  975. static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
  976. ArrayRef<BasicBlock *> Preds, BranchInst *BI,
  977. bool HasLoopExit) {
  978. // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
  979. SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
  980. for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
  981. PHINode *PN = cast<PHINode>(I++);
  982. // Check to see if all of the values coming in are the same. If so, we
  983. // don't need to create a new PHI node, unless it's needed for LCSSA.
  984. Value *InVal = nullptr;
  985. if (!HasLoopExit) {
  986. InVal = PN->getIncomingValueForBlock(Preds[0]);
  987. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  988. if (!PredSet.count(PN->getIncomingBlock(i)))
  989. continue;
  990. if (!InVal)
  991. InVal = PN->getIncomingValue(i);
  992. else if (InVal != PN->getIncomingValue(i)) {
  993. InVal = nullptr;
  994. break;
  995. }
  996. }
  997. }
  998. if (InVal) {
  999. // If all incoming values for the new PHI would be the same, just don't
  1000. // make a new PHI. Instead, just remove the incoming values from the old
  1001. // PHI.
  1002. // NOTE! This loop walks backwards for a reason! First off, this minimizes
  1003. // the cost of removal if we end up removing a large number of values, and
  1004. // second off, this ensures that the indices for the incoming values
  1005. // aren't invalidated when we remove one.
  1006. for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
  1007. if (PredSet.count(PN->getIncomingBlock(i)))
  1008. PN->removeIncomingValue(i, false);
  1009. // Add an incoming value to the PHI node in the loop for the preheader
  1010. // edge.
  1011. PN->addIncoming(InVal, NewBB);
  1012. continue;
  1013. }
  1014. // If the values coming into the block are not the same, we need a new
  1015. // PHI.
  1016. // Create the new PHI node, insert it into NewBB at the end of the block
  1017. PHINode *NewPHI =
  1018. PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
  1019. // NOTE! This loop walks backwards for a reason! First off, this minimizes
  1020. // the cost of removal if we end up removing a large number of values, and
  1021. // second off, this ensures that the indices for the incoming values aren't
  1022. // invalidated when we remove one.
  1023. for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
  1024. BasicBlock *IncomingBB = PN->getIncomingBlock(i);
  1025. if (PredSet.count(IncomingBB)) {
  1026. Value *V = PN->removeIncomingValue(i, false);
  1027. NewPHI->addIncoming(V, IncomingBB);
  1028. }
  1029. }
  1030. PN->addIncoming(NewPHI, NewBB);
  1031. }
  1032. }
  1033. static void SplitLandingPadPredecessorsImpl(
  1034. BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
  1035. const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
  1036. DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
  1037. MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
  1038. static BasicBlock *
  1039. SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
  1040. const char *Suffix, DomTreeUpdater *DTU,
  1041. DominatorTree *DT, LoopInfo *LI,
  1042. MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
  1043. // Do not attempt to split that which cannot be split.
  1044. if (!BB->canSplitPredecessors())
  1045. return nullptr;
  1046. // For the landingpads we need to act a bit differently.
  1047. // Delegate this work to the SplitLandingPadPredecessors.
  1048. if (BB->isLandingPad()) {
  1049. SmallVector<BasicBlock*, 2> NewBBs;
  1050. std::string NewName = std::string(Suffix) + ".split-lp";
  1051. SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
  1052. DTU, DT, LI, MSSAU, PreserveLCSSA);
  1053. return NewBBs[0];
  1054. }
  1055. // Create new basic block, insert right before the original block.
  1056. BasicBlock *NewBB = BasicBlock::Create(
  1057. BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
  1058. // The new block unconditionally branches to the old block.
  1059. BranchInst *BI = BranchInst::Create(BB, NewBB);
  1060. Loop *L = nullptr;
  1061. BasicBlock *OldLatch = nullptr;
  1062. // Splitting the predecessors of a loop header creates a preheader block.
  1063. if (LI && LI->isLoopHeader(BB)) {
  1064. L = LI->getLoopFor(BB);
  1065. // Using the loop start line number prevents debuggers stepping into the
  1066. // loop body for this instruction.
  1067. BI->setDebugLoc(L->getStartLoc());
  1068. // If BB is the header of the Loop, it is possible that the loop is
  1069. // modified, such that the current latch does not remain the latch of the
  1070. // loop. If that is the case, the loop metadata from the current latch needs
  1071. // to be applied to the new latch.
  1072. OldLatch = L->getLoopLatch();
  1073. } else
  1074. BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
  1075. // Move the edges from Preds to point to NewBB instead of BB.
  1076. for (BasicBlock *Pred : Preds) {
  1077. // This is slightly more strict than necessary; the minimum requirement
  1078. // is that there be no more than one indirectbr branching to BB. And
  1079. // all BlockAddress uses would need to be updated.
  1080. assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
  1081. "Cannot split an edge from an IndirectBrInst");
  1082. Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
  1083. }
  1084. // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
  1085. // node becomes an incoming value for BB's phi node. However, if the Preds
  1086. // list is empty, we need to insert dummy entries into the PHI nodes in BB to
  1087. // account for the newly created predecessor.
  1088. if (Preds.empty()) {
  1089. // Insert dummy values as the incoming value.
  1090. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
  1091. cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
  1092. }
  1093. // Update DominatorTree, LoopInfo, and LCCSA analysis information.
  1094. bool HasLoopExit = false;
  1095. UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
  1096. HasLoopExit);
  1097. if (!Preds.empty()) {
  1098. // Update the PHI nodes in BB with the values coming from NewBB.
  1099. UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
  1100. }
  1101. if (OldLatch) {
  1102. BasicBlock *NewLatch = L->getLoopLatch();
  1103. if (NewLatch != OldLatch) {
  1104. MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop");
  1105. NewLatch->getTerminator()->setMetadata("llvm.loop", MD);
  1106. // It's still possible that OldLatch is the latch of another inner loop,
  1107. // in which case we do not remove the metadata.
  1108. Loop *IL = LI->getLoopFor(OldLatch);
  1109. if (IL && IL->getLoopLatch() != OldLatch)
  1110. OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr);
  1111. }
  1112. }
  1113. return NewBB;
  1114. }
  1115. BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
  1116. ArrayRef<BasicBlock *> Preds,
  1117. const char *Suffix, DominatorTree *DT,
  1118. LoopInfo *LI, MemorySSAUpdater *MSSAU,
  1119. bool PreserveLCSSA) {
  1120. return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
  1121. MSSAU, PreserveLCSSA);
  1122. }
  1123. BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
  1124. ArrayRef<BasicBlock *> Preds,
  1125. const char *Suffix,
  1126. DomTreeUpdater *DTU, LoopInfo *LI,
  1127. MemorySSAUpdater *MSSAU,
  1128. bool PreserveLCSSA) {
  1129. return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
  1130. /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
  1131. }
  1132. static void SplitLandingPadPredecessorsImpl(
  1133. BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
  1134. const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
  1135. DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
  1136. MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
  1137. assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
  1138. // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
  1139. // it right before the original block.
  1140. BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
  1141. OrigBB->getName() + Suffix1,
  1142. OrigBB->getParent(), OrigBB);
  1143. NewBBs.push_back(NewBB1);
  1144. // The new block unconditionally branches to the old block.
  1145. BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
  1146. BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
  1147. // Move the edges from Preds to point to NewBB1 instead of OrigBB.
  1148. for (BasicBlock *Pred : Preds) {
  1149. // This is slightly more strict than necessary; the minimum requirement
  1150. // is that there be no more than one indirectbr branching to BB. And
  1151. // all BlockAddress uses would need to be updated.
  1152. assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
  1153. "Cannot split an edge from an IndirectBrInst");
  1154. Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
  1155. }
  1156. bool HasLoopExit = false;
  1157. UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
  1158. PreserveLCSSA, HasLoopExit);
  1159. // Update the PHI nodes in OrigBB with the values coming from NewBB1.
  1160. UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
  1161. // Move the remaining edges from OrigBB to point to NewBB2.
  1162. SmallVector<BasicBlock*, 8> NewBB2Preds;
  1163. for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
  1164. i != e; ) {
  1165. BasicBlock *Pred = *i++;
  1166. if (Pred == NewBB1) continue;
  1167. assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
  1168. "Cannot split an edge from an IndirectBrInst");
  1169. NewBB2Preds.push_back(Pred);
  1170. e = pred_end(OrigBB);
  1171. }
  1172. BasicBlock *NewBB2 = nullptr;
  1173. if (!NewBB2Preds.empty()) {
  1174. // Create another basic block for the rest of OrigBB's predecessors.
  1175. NewBB2 = BasicBlock::Create(OrigBB->getContext(),
  1176. OrigBB->getName() + Suffix2,
  1177. OrigBB->getParent(), OrigBB);
  1178. NewBBs.push_back(NewBB2);
  1179. // The new block unconditionally branches to the old block.
  1180. BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
  1181. BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
  1182. // Move the remaining edges from OrigBB to point to NewBB2.
  1183. for (BasicBlock *NewBB2Pred : NewBB2Preds)
  1184. NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
  1185. // Update DominatorTree, LoopInfo, and LCCSA analysis information.
  1186. HasLoopExit = false;
  1187. UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
  1188. PreserveLCSSA, HasLoopExit);
  1189. // Update the PHI nodes in OrigBB with the values coming from NewBB2.
  1190. UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
  1191. }
  1192. LandingPadInst *LPad = OrigBB->getLandingPadInst();
  1193. Instruction *Clone1 = LPad->clone();
  1194. Clone1->setName(Twine("lpad") + Suffix1);
  1195. Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
  1196. if (NewBB2) {
  1197. Instruction *Clone2 = LPad->clone();
  1198. Clone2->setName(Twine("lpad") + Suffix2);
  1199. Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
  1200. // Create a PHI node for the two cloned landingpad instructions only
  1201. // if the original landingpad instruction has some uses.
  1202. if (!LPad->use_empty()) {
  1203. assert(!LPad->getType()->isTokenTy() &&
  1204. "Split cannot be applied if LPad is token type. Otherwise an "
  1205. "invalid PHINode of token type would be created.");
  1206. PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
  1207. PN->addIncoming(Clone1, NewBB1);
  1208. PN->addIncoming(Clone2, NewBB2);
  1209. LPad->replaceAllUsesWith(PN);
  1210. }
  1211. LPad->eraseFromParent();
  1212. } else {
  1213. // There is no second clone. Just replace the landing pad with the first
  1214. // clone.
  1215. LPad->replaceAllUsesWith(Clone1);
  1216. LPad->eraseFromParent();
  1217. }
  1218. }
  1219. void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
  1220. ArrayRef<BasicBlock *> Preds,
  1221. const char *Suffix1, const char *Suffix2,
  1222. SmallVectorImpl<BasicBlock *> &NewBBs,
  1223. DominatorTree *DT, LoopInfo *LI,
  1224. MemorySSAUpdater *MSSAU,
  1225. bool PreserveLCSSA) {
  1226. return SplitLandingPadPredecessorsImpl(
  1227. OrigBB, Preds, Suffix1, Suffix2, NewBBs,
  1228. /*DTU=*/nullptr, DT, LI, MSSAU, PreserveLCSSA);
  1229. }
  1230. void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
  1231. ArrayRef<BasicBlock *> Preds,
  1232. const char *Suffix1, const char *Suffix2,
  1233. SmallVectorImpl<BasicBlock *> &NewBBs,
  1234. DomTreeUpdater *DTU, LoopInfo *LI,
  1235. MemorySSAUpdater *MSSAU,
  1236. bool PreserveLCSSA) {
  1237. return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
  1238. NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
  1239. PreserveLCSSA);
  1240. }
  1241. ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
  1242. BasicBlock *Pred,
  1243. DomTreeUpdater *DTU) {
  1244. Instruction *UncondBranch = Pred->getTerminator();
  1245. // Clone the return and add it to the end of the predecessor.
  1246. Instruction *NewRet = RI->clone();
  1247. NewRet->insertInto(Pred, Pred->end());
  1248. // If the return instruction returns a value, and if the value was a
  1249. // PHI node in "BB", propagate the right value into the return.
  1250. for (Use &Op : NewRet->operands()) {
  1251. Value *V = Op;
  1252. Instruction *NewBC = nullptr;
  1253. if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
  1254. // Return value might be bitcasted. Clone and insert it before the
  1255. // return instruction.
  1256. V = BCI->getOperand(0);
  1257. NewBC = BCI->clone();
  1258. NewBC->insertInto(Pred, NewRet->getIterator());
  1259. Op = NewBC;
  1260. }
  1261. Instruction *NewEV = nullptr;
  1262. if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
  1263. V = EVI->getOperand(0);
  1264. NewEV = EVI->clone();
  1265. if (NewBC) {
  1266. NewBC->setOperand(0, NewEV);
  1267. NewEV->insertInto(Pred, NewBC->getIterator());
  1268. } else {
  1269. NewEV->insertInto(Pred, NewRet->getIterator());
  1270. Op = NewEV;
  1271. }
  1272. }
  1273. if (PHINode *PN = dyn_cast<PHINode>(V)) {
  1274. if (PN->getParent() == BB) {
  1275. if (NewEV) {
  1276. NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
  1277. } else if (NewBC)
  1278. NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
  1279. else
  1280. Op = PN->getIncomingValueForBlock(Pred);
  1281. }
  1282. }
  1283. }
  1284. // Update any PHI nodes in the returning block to realize that we no
  1285. // longer branch to them.
  1286. BB->removePredecessor(Pred);
  1287. UncondBranch->eraseFromParent();
  1288. if (DTU)
  1289. DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
  1290. return cast<ReturnInst>(NewRet);
  1291. }
  1292. static Instruction *
  1293. SplitBlockAndInsertIfThenImpl(Value *Cond, Instruction *SplitBefore,
  1294. bool Unreachable, MDNode *BranchWeights,
  1295. DomTreeUpdater *DTU, DominatorTree *DT,
  1296. LoopInfo *LI, BasicBlock *ThenBlock) {
  1297. SmallVector<DominatorTree::UpdateType, 8> Updates;
  1298. BasicBlock *Head = SplitBefore->getParent();
  1299. BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
  1300. if (DTU) {
  1301. SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfHead;
  1302. Updates.push_back({DominatorTree::Insert, Head, Tail});
  1303. Updates.reserve(Updates.size() + 2 * succ_size(Tail));
  1304. for (BasicBlock *SuccessorOfHead : successors(Tail))
  1305. if (UniqueSuccessorsOfHead.insert(SuccessorOfHead).second) {
  1306. Updates.push_back({DominatorTree::Insert, Tail, SuccessorOfHead});
  1307. Updates.push_back({DominatorTree::Delete, Head, SuccessorOfHead});
  1308. }
  1309. }
  1310. Instruction *HeadOldTerm = Head->getTerminator();
  1311. LLVMContext &C = Head->getContext();
  1312. Instruction *CheckTerm;
  1313. bool CreateThenBlock = (ThenBlock == nullptr);
  1314. if (CreateThenBlock) {
  1315. ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  1316. if (Unreachable)
  1317. CheckTerm = new UnreachableInst(C, ThenBlock);
  1318. else {
  1319. CheckTerm = BranchInst::Create(Tail, ThenBlock);
  1320. if (DTU)
  1321. Updates.push_back({DominatorTree::Insert, ThenBlock, Tail});
  1322. }
  1323. CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
  1324. } else
  1325. CheckTerm = ThenBlock->getTerminator();
  1326. BranchInst *HeadNewTerm =
  1327. BranchInst::Create(/*ifTrue*/ ThenBlock, /*ifFalse*/ Tail, Cond);
  1328. if (DTU)
  1329. Updates.push_back({DominatorTree::Insert, Head, ThenBlock});
  1330. HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
  1331. ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
  1332. if (DTU)
  1333. DTU->applyUpdates(Updates);
  1334. else if (DT) {
  1335. if (DomTreeNode *OldNode = DT->getNode(Head)) {
  1336. std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
  1337. DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
  1338. for (DomTreeNode *Child : Children)
  1339. DT->changeImmediateDominator(Child, NewNode);
  1340. // Head dominates ThenBlock.
  1341. if (CreateThenBlock)
  1342. DT->addNewBlock(ThenBlock, Head);
  1343. else
  1344. DT->changeImmediateDominator(ThenBlock, Head);
  1345. }
  1346. }
  1347. if (LI) {
  1348. if (Loop *L = LI->getLoopFor(Head)) {
  1349. L->addBasicBlockToLoop(ThenBlock, *LI);
  1350. L->addBasicBlockToLoop(Tail, *LI);
  1351. }
  1352. }
  1353. return CheckTerm;
  1354. }
  1355. Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
  1356. Instruction *SplitBefore,
  1357. bool Unreachable,
  1358. MDNode *BranchWeights,
  1359. DominatorTree *DT, LoopInfo *LI,
  1360. BasicBlock *ThenBlock) {
  1361. return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable,
  1362. BranchWeights,
  1363. /*DTU=*/nullptr, DT, LI, ThenBlock);
  1364. }
  1365. Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
  1366. Instruction *SplitBefore,
  1367. bool Unreachable,
  1368. MDNode *BranchWeights,
  1369. DomTreeUpdater *DTU, LoopInfo *LI,
  1370. BasicBlock *ThenBlock) {
  1371. return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable,
  1372. BranchWeights, DTU, /*DT=*/nullptr, LI,
  1373. ThenBlock);
  1374. }
  1375. void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
  1376. Instruction **ThenTerm,
  1377. Instruction **ElseTerm,
  1378. MDNode *BranchWeights,
  1379. DomTreeUpdater *DTU) {
  1380. BasicBlock *Head = SplitBefore->getParent();
  1381. SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
  1382. if (DTU)
  1383. UniqueOrigSuccessors.insert(succ_begin(Head), succ_end(Head));
  1384. BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
  1385. Instruction *HeadOldTerm = Head->getTerminator();
  1386. LLVMContext &C = Head->getContext();
  1387. BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  1388. BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  1389. *ThenTerm = BranchInst::Create(Tail, ThenBlock);
  1390. (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
  1391. *ElseTerm = BranchInst::Create(Tail, ElseBlock);
  1392. (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
  1393. BranchInst *HeadNewTerm =
  1394. BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
  1395. HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
  1396. ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
  1397. if (DTU) {
  1398. SmallVector<DominatorTree::UpdateType, 8> Updates;
  1399. Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
  1400. for (BasicBlock *Succ : successors(Head)) {
  1401. Updates.push_back({DominatorTree::Insert, Head, Succ});
  1402. Updates.push_back({DominatorTree::Insert, Succ, Tail});
  1403. }
  1404. for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
  1405. Updates.push_back({DominatorTree::Insert, Tail, UniqueOrigSuccessor});
  1406. for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
  1407. Updates.push_back({DominatorTree::Delete, Head, UniqueOrigSuccessor});
  1408. DTU->applyUpdates(Updates);
  1409. }
  1410. }
  1411. BranchInst *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
  1412. BasicBlock *&IfFalse) {
  1413. PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
  1414. BasicBlock *Pred1 = nullptr;
  1415. BasicBlock *Pred2 = nullptr;
  1416. if (SomePHI) {
  1417. if (SomePHI->getNumIncomingValues() != 2)
  1418. return nullptr;
  1419. Pred1 = SomePHI->getIncomingBlock(0);
  1420. Pred2 = SomePHI->getIncomingBlock(1);
  1421. } else {
  1422. pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
  1423. if (PI == PE) // No predecessor
  1424. return nullptr;
  1425. Pred1 = *PI++;
  1426. if (PI == PE) // Only one predecessor
  1427. return nullptr;
  1428. Pred2 = *PI++;
  1429. if (PI != PE) // More than two predecessors
  1430. return nullptr;
  1431. }
  1432. // We can only handle branches. Other control flow will be lowered to
  1433. // branches if possible anyway.
  1434. BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
  1435. BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
  1436. if (!Pred1Br || !Pred2Br)
  1437. return nullptr;
  1438. // Eliminate code duplication by ensuring that Pred1Br is conditional if
  1439. // either are.
  1440. if (Pred2Br->isConditional()) {
  1441. // If both branches are conditional, we don't have an "if statement". In
  1442. // reality, we could transform this case, but since the condition will be
  1443. // required anyway, we stand no chance of eliminating it, so the xform is
  1444. // probably not profitable.
  1445. if (Pred1Br->isConditional())
  1446. return nullptr;
  1447. std::swap(Pred1, Pred2);
  1448. std::swap(Pred1Br, Pred2Br);
  1449. }
  1450. if (Pred1Br->isConditional()) {
  1451. // The only thing we have to watch out for here is to make sure that Pred2
  1452. // doesn't have incoming edges from other blocks. If it does, the condition
  1453. // doesn't dominate BB.
  1454. if (!Pred2->getSinglePredecessor())
  1455. return nullptr;
  1456. // If we found a conditional branch predecessor, make sure that it branches
  1457. // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
  1458. if (Pred1Br->getSuccessor(0) == BB &&
  1459. Pred1Br->getSuccessor(1) == Pred2) {
  1460. IfTrue = Pred1;
  1461. IfFalse = Pred2;
  1462. } else if (Pred1Br->getSuccessor(0) == Pred2 &&
  1463. Pred1Br->getSuccessor(1) == BB) {
  1464. IfTrue = Pred2;
  1465. IfFalse = Pred1;
  1466. } else {
  1467. // We know that one arm of the conditional goes to BB, so the other must
  1468. // go somewhere unrelated, and this must not be an "if statement".
  1469. return nullptr;
  1470. }
  1471. return Pred1Br;
  1472. }
  1473. // Ok, if we got here, both predecessors end with an unconditional branch to
  1474. // BB. Don't panic! If both blocks only have a single (identical)
  1475. // predecessor, and THAT is a conditional branch, then we're all ok!
  1476. BasicBlock *CommonPred = Pred1->getSinglePredecessor();
  1477. if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
  1478. return nullptr;
  1479. // Otherwise, if this is a conditional branch, then we can use it!
  1480. BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
  1481. if (!BI) return nullptr;
  1482. assert(BI->isConditional() && "Two successors but not conditional?");
  1483. if (BI->getSuccessor(0) == Pred1) {
  1484. IfTrue = Pred1;
  1485. IfFalse = Pred2;
  1486. } else {
  1487. IfTrue = Pred2;
  1488. IfFalse = Pred1;
  1489. }
  1490. return BI;
  1491. }
  1492. // After creating a control flow hub, the operands of PHINodes in an outgoing
  1493. // block Out no longer match the predecessors of that block. Predecessors of Out
  1494. // that are incoming blocks to the hub are now replaced by just one edge from
  1495. // the hub. To match this new control flow, the corresponding values from each
  1496. // PHINode must now be moved a new PHINode in the first guard block of the hub.
  1497. //
  1498. // This operation cannot be performed with SSAUpdater, because it involves one
  1499. // new use: If the block Out is in the list of Incoming blocks, then the newly
  1500. // created PHI in the Hub will use itself along that edge from Out to Hub.
  1501. static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock,
  1502. const SetVector<BasicBlock *> &Incoming,
  1503. BasicBlock *FirstGuardBlock) {
  1504. auto I = Out->begin();
  1505. while (I != Out->end() && isa<PHINode>(I)) {
  1506. auto Phi = cast<PHINode>(I);
  1507. auto NewPhi =
  1508. PHINode::Create(Phi->getType(), Incoming.size(),
  1509. Phi->getName() + ".moved", &FirstGuardBlock->front());
  1510. for (auto *In : Incoming) {
  1511. Value *V = UndefValue::get(Phi->getType());
  1512. if (In == Out) {
  1513. V = NewPhi;
  1514. } else if (Phi->getBasicBlockIndex(In) != -1) {
  1515. V = Phi->removeIncomingValue(In, false);
  1516. }
  1517. NewPhi->addIncoming(V, In);
  1518. }
  1519. assert(NewPhi->getNumIncomingValues() == Incoming.size());
  1520. if (Phi->getNumOperands() == 0) {
  1521. Phi->replaceAllUsesWith(NewPhi);
  1522. I = Phi->eraseFromParent();
  1523. continue;
  1524. }
  1525. Phi->addIncoming(NewPhi, GuardBlock);
  1526. ++I;
  1527. }
  1528. }
  1529. using BBPredicates = DenseMap<BasicBlock *, Instruction *>;
  1530. using BBSetVector = SetVector<BasicBlock *>;
  1531. // Redirects the terminator of the incoming block to the first guard
  1532. // block in the hub. The condition of the original terminator (if it
  1533. // was conditional) and its original successors are returned as a
  1534. // tuple <condition, succ0, succ1>. The function additionally filters
  1535. // out successors that are not in the set of outgoing blocks.
  1536. //
  1537. // - condition is non-null iff the branch is conditional.
  1538. // - Succ1 is non-null iff the sole/taken target is an outgoing block.
  1539. // - Succ2 is non-null iff condition is non-null and the fallthrough
  1540. // target is an outgoing block.
  1541. static std::tuple<Value *, BasicBlock *, BasicBlock *>
  1542. redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock,
  1543. const BBSetVector &Outgoing) {
  1544. assert(isa<BranchInst>(BB->getTerminator()) &&
  1545. "Only support branch terminator.");
  1546. auto Branch = cast<BranchInst>(BB->getTerminator());
  1547. auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
  1548. BasicBlock *Succ0 = Branch->getSuccessor(0);
  1549. BasicBlock *Succ1 = nullptr;
  1550. Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr;
  1551. if (Branch->isUnconditional()) {
  1552. Branch->setSuccessor(0, FirstGuardBlock);
  1553. assert(Succ0);
  1554. } else {
  1555. Succ1 = Branch->getSuccessor(1);
  1556. Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr;
  1557. assert(Succ0 || Succ1);
  1558. if (Succ0 && !Succ1) {
  1559. Branch->setSuccessor(0, FirstGuardBlock);
  1560. } else if (Succ1 && !Succ0) {
  1561. Branch->setSuccessor(1, FirstGuardBlock);
  1562. } else {
  1563. Branch->eraseFromParent();
  1564. BranchInst::Create(FirstGuardBlock, BB);
  1565. }
  1566. }
  1567. assert(Succ0 || Succ1);
  1568. return std::make_tuple(Condition, Succ0, Succ1);
  1569. }
  1570. // Setup the branch instructions for guard blocks.
  1571. //
  1572. // Each guard block terminates in a conditional branch that transfers
  1573. // control to the corresponding outgoing block or the next guard
  1574. // block. The last guard block has two outgoing blocks as successors
  1575. // since the condition for the final outgoing block is trivially
  1576. // true. So we create one less block (including the first guard block)
  1577. // than the number of outgoing blocks.
  1578. static void setupBranchForGuard(SmallVectorImpl<BasicBlock *> &GuardBlocks,
  1579. const BBSetVector &Outgoing,
  1580. BBPredicates &GuardPredicates) {
  1581. // To help keep the loop simple, temporarily append the last
  1582. // outgoing block to the list of guard blocks.
  1583. GuardBlocks.push_back(Outgoing.back());
  1584. for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) {
  1585. auto Out = Outgoing[i];
  1586. assert(GuardPredicates.count(Out));
  1587. BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out],
  1588. GuardBlocks[i]);
  1589. }
  1590. // Remove the last block from the guard list.
  1591. GuardBlocks.pop_back();
  1592. }
  1593. /// We are using one integer to represent the block we are branching to. Then at
  1594. /// each guard block, the predicate was calcuated using a simple `icmp eq`.
  1595. static void calcPredicateUsingInteger(
  1596. const BBSetVector &Incoming, const BBSetVector &Outgoing,
  1597. SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates) {
  1598. auto &Context = Incoming.front()->getContext();
  1599. auto FirstGuardBlock = GuardBlocks.front();
  1600. auto Phi = PHINode::Create(Type::getInt32Ty(Context), Incoming.size(),
  1601. "merged.bb.idx", FirstGuardBlock);
  1602. for (auto In : Incoming) {
  1603. Value *Condition;
  1604. BasicBlock *Succ0;
  1605. BasicBlock *Succ1;
  1606. std::tie(Condition, Succ0, Succ1) =
  1607. redirectToHub(In, FirstGuardBlock, Outgoing);
  1608. Value *IncomingId = nullptr;
  1609. if (Succ0 && Succ1) {
  1610. // target_bb_index = Condition ? index_of_succ0 : index_of_succ1.
  1611. auto Succ0Iter = find(Outgoing, Succ0);
  1612. auto Succ1Iter = find(Outgoing, Succ1);
  1613. Value *Id0 = ConstantInt::get(Type::getInt32Ty(Context),
  1614. std::distance(Outgoing.begin(), Succ0Iter));
  1615. Value *Id1 = ConstantInt::get(Type::getInt32Ty(Context),
  1616. std::distance(Outgoing.begin(), Succ1Iter));
  1617. IncomingId = SelectInst::Create(Condition, Id0, Id1, "target.bb.idx",
  1618. In->getTerminator());
  1619. } else {
  1620. // Get the index of the non-null successor.
  1621. auto SuccIter = Succ0 ? find(Outgoing, Succ0) : find(Outgoing, Succ1);
  1622. IncomingId = ConstantInt::get(Type::getInt32Ty(Context),
  1623. std::distance(Outgoing.begin(), SuccIter));
  1624. }
  1625. Phi->addIncoming(IncomingId, In);
  1626. }
  1627. for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
  1628. auto Out = Outgoing[i];
  1629. auto Cmp = ICmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, Phi,
  1630. ConstantInt::get(Type::getInt32Ty(Context), i),
  1631. Out->getName() + ".predicate", GuardBlocks[i]);
  1632. GuardPredicates[Out] = Cmp;
  1633. }
  1634. }
  1635. /// We record the predicate of each outgoing block using a phi of boolean.
  1636. static void calcPredicateUsingBooleans(
  1637. const BBSetVector &Incoming, const BBSetVector &Outgoing,
  1638. SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates,
  1639. SmallVectorImpl<WeakVH> &DeletionCandidates) {
  1640. auto &Context = Incoming.front()->getContext();
  1641. auto BoolTrue = ConstantInt::getTrue(Context);
  1642. auto BoolFalse = ConstantInt::getFalse(Context);
  1643. auto FirstGuardBlock = GuardBlocks.front();
  1644. // The predicate for the last outgoing is trivially true, and so we
  1645. // process only the first N-1 successors.
  1646. for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
  1647. auto Out = Outgoing[i];
  1648. LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n");
  1649. auto Phi =
  1650. PHINode::Create(Type::getInt1Ty(Context), Incoming.size(),
  1651. StringRef("Guard.") + Out->getName(), FirstGuardBlock);
  1652. GuardPredicates[Out] = Phi;
  1653. }
  1654. for (auto *In : Incoming) {
  1655. Value *Condition;
  1656. BasicBlock *Succ0;
  1657. BasicBlock *Succ1;
  1658. std::tie(Condition, Succ0, Succ1) =
  1659. redirectToHub(In, FirstGuardBlock, Outgoing);
  1660. // Optimization: Consider an incoming block A with both successors
  1661. // Succ0 and Succ1 in the set of outgoing blocks. The predicates
  1662. // for Succ0 and Succ1 complement each other. If Succ0 is visited
  1663. // first in the loop below, control will branch to Succ0 using the
  1664. // corresponding predicate. But if that branch is not taken, then
  1665. // control must reach Succ1, which means that the incoming value of
  1666. // the predicate from `In` is true for Succ1.
  1667. bool OneSuccessorDone = false;
  1668. for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
  1669. auto Out = Outgoing[i];
  1670. PHINode *Phi = cast<PHINode>(GuardPredicates[Out]);
  1671. if (Out != Succ0 && Out != Succ1) {
  1672. Phi->addIncoming(BoolFalse, In);
  1673. } else if (!Succ0 || !Succ1 || OneSuccessorDone) {
  1674. // Optimization: When only one successor is an outgoing block,
  1675. // the incoming predicate from `In` is always true.
  1676. Phi->addIncoming(BoolTrue, In);
  1677. } else {
  1678. assert(Succ0 && Succ1);
  1679. if (Out == Succ0) {
  1680. Phi->addIncoming(Condition, In);
  1681. } else {
  1682. auto Inverted = invertCondition(Condition);
  1683. DeletionCandidates.push_back(Condition);
  1684. Phi->addIncoming(Inverted, In);
  1685. }
  1686. OneSuccessorDone = true;
  1687. }
  1688. }
  1689. }
  1690. }
  1691. // Capture the existing control flow as guard predicates, and redirect
  1692. // control flow from \p Incoming block through the \p GuardBlocks to the
  1693. // \p Outgoing blocks.
  1694. //
  1695. // There is one guard predicate for each outgoing block OutBB. The
  1696. // predicate represents whether the hub should transfer control flow
  1697. // to OutBB. These predicates are NOT ORTHOGONAL. The Hub evaluates
  1698. // them in the same order as the Outgoing set-vector, and control
  1699. // branches to the first outgoing block whose predicate evaluates to true.
  1700. static void
  1701. convertToGuardPredicates(SmallVectorImpl<BasicBlock *> &GuardBlocks,
  1702. SmallVectorImpl<WeakVH> &DeletionCandidates,
  1703. const BBSetVector &Incoming,
  1704. const BBSetVector &Outgoing, const StringRef Prefix,
  1705. std::optional<unsigned> MaxControlFlowBooleans) {
  1706. BBPredicates GuardPredicates;
  1707. auto F = Incoming.front()->getParent();
  1708. for (int i = 0, e = Outgoing.size() - 1; i != e; ++i)
  1709. GuardBlocks.push_back(
  1710. BasicBlock::Create(F->getContext(), Prefix + ".guard", F));
  1711. // When we are using an integer to record which target block to jump to, we
  1712. // are creating less live values, actually we are using one single integer to
  1713. // store the index of the target block. When we are using booleans to store
  1714. // the branching information, we need (N-1) boolean values, where N is the
  1715. // number of outgoing block.
  1716. if (!MaxControlFlowBooleans || Outgoing.size() <= *MaxControlFlowBooleans)
  1717. calcPredicateUsingBooleans(Incoming, Outgoing, GuardBlocks, GuardPredicates,
  1718. DeletionCandidates);
  1719. else
  1720. calcPredicateUsingInteger(Incoming, Outgoing, GuardBlocks, GuardPredicates);
  1721. setupBranchForGuard(GuardBlocks, Outgoing, GuardPredicates);
  1722. }
  1723. BasicBlock *llvm::CreateControlFlowHub(
  1724. DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
  1725. const BBSetVector &Incoming, const BBSetVector &Outgoing,
  1726. const StringRef Prefix, std::optional<unsigned> MaxControlFlowBooleans) {
  1727. if (Outgoing.size() < 2)
  1728. return Outgoing.front();
  1729. SmallVector<DominatorTree::UpdateType, 16> Updates;
  1730. if (DTU) {
  1731. for (auto *In : Incoming) {
  1732. for (auto Succ : successors(In))
  1733. if (Outgoing.count(Succ))
  1734. Updates.push_back({DominatorTree::Delete, In, Succ});
  1735. }
  1736. }
  1737. SmallVector<WeakVH, 8> DeletionCandidates;
  1738. convertToGuardPredicates(GuardBlocks, DeletionCandidates, Incoming, Outgoing,
  1739. Prefix, MaxControlFlowBooleans);
  1740. auto FirstGuardBlock = GuardBlocks.front();
  1741. // Update the PHINodes in each outgoing block to match the new control flow.
  1742. for (int i = 0, e = GuardBlocks.size(); i != e; ++i)
  1743. reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock);
  1744. reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock);
  1745. if (DTU) {
  1746. int NumGuards = GuardBlocks.size();
  1747. assert((int)Outgoing.size() == NumGuards + 1);
  1748. for (auto In : Incoming)
  1749. Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock});
  1750. for (int i = 0; i != NumGuards - 1; ++i) {
  1751. Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]});
  1752. Updates.push_back(
  1753. {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]});
  1754. }
  1755. Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
  1756. Outgoing[NumGuards - 1]});
  1757. Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
  1758. Outgoing[NumGuards]});
  1759. DTU->applyUpdates(Updates);
  1760. }
  1761. for (auto I : DeletionCandidates) {
  1762. if (I->use_empty())
  1763. if (auto Inst = dyn_cast_or_null<Instruction>(I))
  1764. Inst->eraseFromParent();
  1765. }
  1766. return FirstGuardBlock;
  1767. }