BasicBlockUtils.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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/Analysis/PostDominators.h"
  24. #include "llvm/IR/BasicBlock.h"
  25. #include "llvm/IR/CFG.h"
  26. #include "llvm/IR/Constants.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/Debug.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include "llvm/Transforms/Utils/Local.h"
  43. #include <cassert>
  44. #include <cstdint>
  45. #include <string>
  46. #include <utility>
  47. #include <vector>
  48. using namespace llvm;
  49. #define DEBUG_TYPE "basicblock-utils"
  50. void llvm::DetatchDeadBlocks(
  51. ArrayRef<BasicBlock *> BBs,
  52. SmallVectorImpl<DominatorTree::UpdateType> *Updates,
  53. bool KeepOneInputPHIs) {
  54. for (auto *BB : BBs) {
  55. // Loop through all of our successors and make sure they know that one
  56. // of their predecessors is going away.
  57. SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
  58. for (BasicBlock *Succ : successors(BB)) {
  59. Succ->removePredecessor(BB, KeepOneInputPHIs);
  60. if (Updates && UniqueSuccessors.insert(Succ).second)
  61. Updates->push_back({DominatorTree::Delete, BB, Succ});
  62. }
  63. // Zap all the instructions in the block.
  64. while (!BB->empty()) {
  65. Instruction &I = BB->back();
  66. // If this instruction is used, replace uses with an arbitrary value.
  67. // Because control flow can't get here, we don't care what we replace the
  68. // value with. Note that since this block is unreachable, and all values
  69. // contained within it must dominate their uses, that all uses will
  70. // eventually be removed (they are themselves dead).
  71. if (!I.use_empty())
  72. I.replaceAllUsesWith(UndefValue::get(I.getType()));
  73. BB->getInstList().pop_back();
  74. }
  75. new UnreachableInst(BB->getContext(), BB);
  76. assert(BB->getInstList().size() == 1 &&
  77. isa<UnreachableInst>(BB->getTerminator()) &&
  78. "The successor list of BB isn't empty before "
  79. "applying corresponding DTU updates.");
  80. }
  81. }
  82. void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
  83. bool KeepOneInputPHIs) {
  84. DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
  85. }
  86. void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
  87. bool KeepOneInputPHIs) {
  88. #ifndef NDEBUG
  89. // Make sure that all predecessors of each dead block is also dead.
  90. SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
  91. assert(Dead.size() == BBs.size() && "Duplicating blocks?");
  92. for (auto *BB : Dead)
  93. for (BasicBlock *Pred : predecessors(BB))
  94. assert(Dead.count(Pred) && "All predecessors must be dead!");
  95. #endif
  96. SmallVector<DominatorTree::UpdateType, 4> Updates;
  97. DetatchDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
  98. if (DTU)
  99. DTU->applyUpdatesPermissive(Updates);
  100. for (BasicBlock *BB : BBs)
  101. if (DTU)
  102. DTU->deleteBB(BB);
  103. else
  104. BB->eraseFromParent();
  105. }
  106. bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
  107. bool KeepOneInputPHIs) {
  108. df_iterator_default_set<BasicBlock*> Reachable;
  109. // Mark all reachable blocks.
  110. for (BasicBlock *BB : depth_first_ext(&F, Reachable))
  111. (void)BB/* Mark all reachable blocks */;
  112. // Collect all dead blocks.
  113. std::vector<BasicBlock*> DeadBlocks;
  114. for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
  115. if (!Reachable.count(&*I)) {
  116. BasicBlock *BB = &*I;
  117. DeadBlocks.push_back(BB);
  118. }
  119. // Delete the dead blocks.
  120. DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
  121. return !DeadBlocks.empty();
  122. }
  123. void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
  124. MemoryDependenceResults *MemDep) {
  125. if (!isa<PHINode>(BB->begin())) return;
  126. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  127. if (PN->getIncomingValue(0) != PN)
  128. PN->replaceAllUsesWith(PN->getIncomingValue(0));
  129. else
  130. PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
  131. if (MemDep)
  132. MemDep->removeInstruction(PN); // Memdep updates AA itself.
  133. PN->eraseFromParent();
  134. }
  135. }
  136. bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
  137. // Recursively deleting a PHI may cause multiple PHIs to be deleted
  138. // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
  139. SmallVector<WeakTrackingVH, 8> PHIs;
  140. for (PHINode &PN : BB->phis())
  141. PHIs.push_back(&PN);
  142. bool Changed = false;
  143. for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
  144. if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
  145. Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
  146. return Changed;
  147. }
  148. bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
  149. LoopInfo *LI, MemorySSAUpdater *MSSAU,
  150. MemoryDependenceResults *MemDep) {
  151. if (BB->hasAddressTaken())
  152. return false;
  153. // Can't merge if there are multiple predecessors, or no predecessors.
  154. BasicBlock *PredBB = BB->getUniquePredecessor();
  155. if (!PredBB) return false;
  156. // Don't break self-loops.
  157. if (PredBB == BB) return false;
  158. // Don't break unwinding instructions.
  159. if (PredBB->getTerminator()->isExceptionalTerminator())
  160. return false;
  161. // Can't merge if there are multiple distinct successors.
  162. if (PredBB->getUniqueSuccessor() != BB)
  163. return false;
  164. // Can't merge if there is PHI loop.
  165. for (PHINode &PN : BB->phis())
  166. for (Value *IncValue : PN.incoming_values())
  167. if (IncValue == &PN)
  168. return false;
  169. LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
  170. << PredBB->getName() << "\n");
  171. // Begin by getting rid of unneeded PHIs.
  172. SmallVector<AssertingVH<Value>, 4> IncomingValues;
  173. if (isa<PHINode>(BB->front())) {
  174. for (PHINode &PN : BB->phis())
  175. if (!isa<PHINode>(PN.getIncomingValue(0)) ||
  176. cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
  177. IncomingValues.push_back(PN.getIncomingValue(0));
  178. FoldSingleEntryPHINodes(BB, MemDep);
  179. }
  180. // DTU update: Collect all the edges that exit BB.
  181. // These dominator edges will be redirected from Pred.
  182. std::vector<DominatorTree::UpdateType> Updates;
  183. if (DTU) {
  184. Updates.reserve(1 + (2 * succ_size(BB)));
  185. // Add insert edges first. Experimentally, for the particular case of two
  186. // blocks that can be merged, with a single successor and single predecessor
  187. // respectively, it is beneficial to have all insert updates first. Deleting
  188. // edges first may lead to unreachable blocks, followed by inserting edges
  189. // making the blocks reachable again. Such DT updates lead to high compile
  190. // times. We add inserts before deletes here to reduce compile time.
  191. for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
  192. // This successor of BB may already have PredBB as a predecessor.
  193. if (llvm::find(successors(PredBB), *I) == succ_end(PredBB))
  194. Updates.push_back({DominatorTree::Insert, PredBB, *I});
  195. for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
  196. Updates.push_back({DominatorTree::Delete, BB, *I});
  197. Updates.push_back({DominatorTree::Delete, PredBB, BB});
  198. }
  199. if (MSSAU)
  200. MSSAU->moveAllAfterMergeBlocks(BB, PredBB, &*(BB->begin()));
  201. // Delete the unconditional branch from the predecessor...
  202. PredBB->getInstList().pop_back();
  203. // Make all PHI nodes that referred to BB now refer to Pred as their
  204. // source...
  205. BB->replaceAllUsesWith(PredBB);
  206. // Move all definitions in the successor to the predecessor...
  207. PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
  208. new UnreachableInst(BB->getContext(), BB);
  209. // Eliminate duplicate dbg.values describing the entry PHI node post-splice.
  210. for (auto Incoming : IncomingValues) {
  211. if (isa<Instruction>(*Incoming)) {
  212. SmallVector<DbgValueInst *, 2> DbgValues;
  213. SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2>
  214. DbgValueSet;
  215. llvm::findDbgValues(DbgValues, Incoming);
  216. for (auto &DVI : DbgValues) {
  217. auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()});
  218. if (!R.second)
  219. DVI->eraseFromParent();
  220. }
  221. }
  222. }
  223. // Inherit predecessors name if it exists.
  224. if (!PredBB->hasName())
  225. PredBB->takeName(BB);
  226. if (LI)
  227. LI->removeBlock(BB);
  228. if (MemDep)
  229. MemDep->invalidateCachedPredecessors();
  230. // Finally, erase the old block and update dominator info.
  231. if (DTU) {
  232. assert(BB->getInstList().size() == 1 &&
  233. isa<UnreachableInst>(BB->getTerminator()) &&
  234. "The successor list of BB isn't empty before "
  235. "applying corresponding DTU updates.");
  236. DTU->applyUpdatesPermissive(Updates);
  237. DTU->deleteBB(BB);
  238. }
  239. else {
  240. BB->eraseFromParent(); // Nuke BB if DTU is nullptr.
  241. }
  242. return true;
  243. }
  244. void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
  245. BasicBlock::iterator &BI, Value *V) {
  246. Instruction &I = *BI;
  247. // Replaces all of the uses of the instruction with uses of the value
  248. I.replaceAllUsesWith(V);
  249. // Make sure to propagate a name if there is one already.
  250. if (I.hasName() && !V->hasName())
  251. V->takeName(&I);
  252. // Delete the unnecessary instruction now...
  253. BI = BIL.erase(BI);
  254. }
  255. void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
  256. BasicBlock::iterator &BI, Instruction *I) {
  257. assert(I->getParent() == nullptr &&
  258. "ReplaceInstWithInst: Instruction already inserted into basic block!");
  259. // Copy debug location to newly added instruction, if it wasn't already set
  260. // by the caller.
  261. if (!I->getDebugLoc())
  262. I->setDebugLoc(BI->getDebugLoc());
  263. // Insert the new instruction into the basic block...
  264. BasicBlock::iterator New = BIL.insert(BI, I);
  265. // Replace all uses of the old instruction, and delete it.
  266. ReplaceInstWithValue(BIL, BI, I);
  267. // Move BI back to point to the newly inserted instruction
  268. BI = New;
  269. }
  270. void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
  271. BasicBlock::iterator BI(From);
  272. ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
  273. }
  274. BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
  275. LoopInfo *LI, MemorySSAUpdater *MSSAU) {
  276. unsigned SuccNum = GetSuccessorNumber(BB, Succ);
  277. // If this is a critical edge, let SplitCriticalEdge do it.
  278. Instruction *LatchTerm = BB->getTerminator();
  279. if (SplitCriticalEdge(
  280. LatchTerm, SuccNum,
  281. CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA()))
  282. return LatchTerm->getSuccessor(SuccNum);
  283. // If the edge isn't critical, then BB has a single successor or Succ has a
  284. // single pred. Split the block.
  285. if (BasicBlock *SP = Succ->getSinglePredecessor()) {
  286. // If the successor only has a single pred, split the top of the successor
  287. // block.
  288. assert(SP == BB && "CFG broken");
  289. SP = nullptr;
  290. return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU);
  291. }
  292. // Otherwise, if BB has a single successor, split it at the bottom of the
  293. // block.
  294. assert(BB->getTerminator()->getNumSuccessors() == 1 &&
  295. "Should have a single succ!");
  296. return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU);
  297. }
  298. unsigned
  299. llvm::SplitAllCriticalEdges(Function &F,
  300. const CriticalEdgeSplittingOptions &Options) {
  301. unsigned NumBroken = 0;
  302. for (BasicBlock &BB : F) {
  303. Instruction *TI = BB.getTerminator();
  304. if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
  305. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  306. if (SplitCriticalEdge(TI, i, Options))
  307. ++NumBroken;
  308. }
  309. return NumBroken;
  310. }
  311. BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
  312. DominatorTree *DT, LoopInfo *LI,
  313. MemorySSAUpdater *MSSAU) {
  314. BasicBlock::iterator SplitIt = SplitPt->getIterator();
  315. while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
  316. ++SplitIt;
  317. BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
  318. // The new block lives in whichever loop the old one did. This preserves
  319. // LCSSA as well, because we force the split point to be after any PHI nodes.
  320. if (LI)
  321. if (Loop *L = LI->getLoopFor(Old))
  322. L->addBasicBlockToLoop(New, *LI);
  323. if (DT)
  324. // Old dominates New. New node dominates all other nodes dominated by Old.
  325. if (DomTreeNode *OldNode = DT->getNode(Old)) {
  326. std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
  327. DomTreeNode *NewNode = DT->addNewBlock(New, Old);
  328. for (DomTreeNode *I : Children)
  329. DT->changeImmediateDominator(I, NewNode);
  330. }
  331. // Move MemoryAccesses still tracked in Old, but part of New now.
  332. // Update accesses in successor blocks accordingly.
  333. if (MSSAU)
  334. MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
  335. return New;
  336. }
  337. /// Update DominatorTree, LoopInfo, and LCCSA analysis information.
  338. static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
  339. ArrayRef<BasicBlock *> Preds,
  340. DominatorTree *DT, LoopInfo *LI,
  341. MemorySSAUpdater *MSSAU,
  342. bool PreserveLCSSA, bool &HasLoopExit) {
  343. // Update dominator tree if available.
  344. if (DT) {
  345. if (OldBB == DT->getRootNode()->getBlock()) {
  346. assert(NewBB == &NewBB->getParent()->getEntryBlock());
  347. DT->setNewRoot(NewBB);
  348. } else {
  349. // Split block expects NewBB to have a non-empty set of predecessors.
  350. DT->splitBlock(NewBB);
  351. }
  352. }
  353. // Update MemoryPhis after split if MemorySSA is available
  354. if (MSSAU)
  355. MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
  356. // The rest of the logic is only relevant for updating the loop structures.
  357. if (!LI)
  358. return;
  359. assert(DT && "DT should be available to update LoopInfo!");
  360. Loop *L = LI->getLoopFor(OldBB);
  361. // If we need to preserve loop analyses, collect some information about how
  362. // this split will affect loops.
  363. bool IsLoopEntry = !!L;
  364. bool SplitMakesNewLoopHeader = false;
  365. for (BasicBlock *Pred : Preds) {
  366. // Preds that are not reachable from entry should not be used to identify if
  367. // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
  368. // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
  369. // as true and make the NewBB the header of some loop. This breaks LI.
  370. if (!DT->isReachableFromEntry(Pred))
  371. continue;
  372. // If we need to preserve LCSSA, determine if any of the preds is a loop
  373. // exit.
  374. if (PreserveLCSSA)
  375. if (Loop *PL = LI->getLoopFor(Pred))
  376. if (!PL->contains(OldBB))
  377. HasLoopExit = true;
  378. // If we need to preserve LoopInfo, note whether any of the preds crosses
  379. // an interesting loop boundary.
  380. if (!L)
  381. continue;
  382. if (L->contains(Pred))
  383. IsLoopEntry = false;
  384. else
  385. SplitMakesNewLoopHeader = true;
  386. }
  387. // Unless we have a loop for OldBB, nothing else to do here.
  388. if (!L)
  389. return;
  390. if (IsLoopEntry) {
  391. // Add the new block to the nearest enclosing loop (and not an adjacent
  392. // loop). To find this, examine each of the predecessors and determine which
  393. // loops enclose them, and select the most-nested loop which contains the
  394. // loop containing the block being split.
  395. Loop *InnermostPredLoop = nullptr;
  396. for (BasicBlock *Pred : Preds) {
  397. if (Loop *PredLoop = LI->getLoopFor(Pred)) {
  398. // Seek a loop which actually contains the block being split (to avoid
  399. // adjacent loops).
  400. while (PredLoop && !PredLoop->contains(OldBB))
  401. PredLoop = PredLoop->getParentLoop();
  402. // Select the most-nested of these loops which contains the block.
  403. if (PredLoop && PredLoop->contains(OldBB) &&
  404. (!InnermostPredLoop ||
  405. InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
  406. InnermostPredLoop = PredLoop;
  407. }
  408. }
  409. if (InnermostPredLoop)
  410. InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
  411. } else {
  412. L->addBasicBlockToLoop(NewBB, *LI);
  413. if (SplitMakesNewLoopHeader)
  414. L->moveToHeader(NewBB);
  415. }
  416. }
  417. /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
  418. /// This also updates AliasAnalysis, if available.
  419. static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
  420. ArrayRef<BasicBlock *> Preds, BranchInst *BI,
  421. bool HasLoopExit) {
  422. // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
  423. SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
  424. for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
  425. PHINode *PN = cast<PHINode>(I++);
  426. // Check to see if all of the values coming in are the same. If so, we
  427. // don't need to create a new PHI node, unless it's needed for LCSSA.
  428. Value *InVal = nullptr;
  429. if (!HasLoopExit) {
  430. InVal = PN->getIncomingValueForBlock(Preds[0]);
  431. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  432. if (!PredSet.count(PN->getIncomingBlock(i)))
  433. continue;
  434. if (!InVal)
  435. InVal = PN->getIncomingValue(i);
  436. else if (InVal != PN->getIncomingValue(i)) {
  437. InVal = nullptr;
  438. break;
  439. }
  440. }
  441. }
  442. if (InVal) {
  443. // If all incoming values for the new PHI would be the same, just don't
  444. // make a new PHI. Instead, just remove the incoming values from the old
  445. // PHI.
  446. // NOTE! This loop walks backwards for a reason! First off, this minimizes
  447. // the cost of removal if we end up removing a large number of values, and
  448. // second off, this ensures that the indices for the incoming values
  449. // aren't invalidated when we remove one.
  450. for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
  451. if (PredSet.count(PN->getIncomingBlock(i)))
  452. PN->removeIncomingValue(i, false);
  453. // Add an incoming value to the PHI node in the loop for the preheader
  454. // edge.
  455. PN->addIncoming(InVal, NewBB);
  456. continue;
  457. }
  458. // If the values coming into the block are not the same, we need a new
  459. // PHI.
  460. // Create the new PHI node, insert it into NewBB at the end of the block
  461. PHINode *NewPHI =
  462. PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
  463. // NOTE! This loop walks backwards for a reason! First off, this minimizes
  464. // the cost of removal if we end up removing a large number of values, and
  465. // second off, this ensures that the indices for the incoming values aren't
  466. // invalidated when we remove one.
  467. for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
  468. BasicBlock *IncomingBB = PN->getIncomingBlock(i);
  469. if (PredSet.count(IncomingBB)) {
  470. Value *V = PN->removeIncomingValue(i, false);
  471. NewPHI->addIncoming(V, IncomingBB);
  472. }
  473. }
  474. PN->addIncoming(NewPHI, NewBB);
  475. }
  476. }
  477. BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
  478. ArrayRef<BasicBlock *> Preds,
  479. const char *Suffix, DominatorTree *DT,
  480. LoopInfo *LI, MemorySSAUpdater *MSSAU,
  481. bool PreserveLCSSA) {
  482. // Do not attempt to split that which cannot be split.
  483. if (!BB->canSplitPredecessors())
  484. return nullptr;
  485. // For the landingpads we need to act a bit differently.
  486. // Delegate this work to the SplitLandingPadPredecessors.
  487. if (BB->isLandingPad()) {
  488. SmallVector<BasicBlock*, 2> NewBBs;
  489. std::string NewName = std::string(Suffix) + ".split-lp";
  490. SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
  491. LI, MSSAU, PreserveLCSSA);
  492. return NewBBs[0];
  493. }
  494. // Create new basic block, insert right before the original block.
  495. BasicBlock *NewBB = BasicBlock::Create(
  496. BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
  497. // The new block unconditionally branches to the old block.
  498. BranchInst *BI = BranchInst::Create(BB, NewBB);
  499. // Splitting the predecessors of a loop header creates a preheader block.
  500. if (LI && LI->isLoopHeader(BB))
  501. // Using the loop start line number prevents debuggers stepping into the
  502. // loop body for this instruction.
  503. BI->setDebugLoc(LI->getLoopFor(BB)->getStartLoc());
  504. else
  505. BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
  506. // Move the edges from Preds to point to NewBB instead of BB.
  507. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  508. // This is slightly more strict than necessary; the minimum requirement
  509. // is that there be no more than one indirectbr branching to BB. And
  510. // all BlockAddress uses would need to be updated.
  511. assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
  512. "Cannot split an edge from an IndirectBrInst");
  513. assert(!isa<CallBrInst>(Preds[i]->getTerminator()) &&
  514. "Cannot split an edge from a CallBrInst");
  515. Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
  516. }
  517. // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
  518. // node becomes an incoming value for BB's phi node. However, if the Preds
  519. // list is empty, we need to insert dummy entries into the PHI nodes in BB to
  520. // account for the newly created predecessor.
  521. if (Preds.empty()) {
  522. // Insert dummy values as the incoming value.
  523. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
  524. cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
  525. }
  526. // Update DominatorTree, LoopInfo, and LCCSA analysis information.
  527. bool HasLoopExit = false;
  528. UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, MSSAU, PreserveLCSSA,
  529. HasLoopExit);
  530. if (!Preds.empty()) {
  531. // Update the PHI nodes in BB with the values coming from NewBB.
  532. UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
  533. }
  534. return NewBB;
  535. }
  536. void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
  537. ArrayRef<BasicBlock *> Preds,
  538. const char *Suffix1, const char *Suffix2,
  539. SmallVectorImpl<BasicBlock *> &NewBBs,
  540. DominatorTree *DT, LoopInfo *LI,
  541. MemorySSAUpdater *MSSAU,
  542. bool PreserveLCSSA) {
  543. assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
  544. // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
  545. // it right before the original block.
  546. BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
  547. OrigBB->getName() + Suffix1,
  548. OrigBB->getParent(), OrigBB);
  549. NewBBs.push_back(NewBB1);
  550. // The new block unconditionally branches to the old block.
  551. BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
  552. BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
  553. // Move the edges from Preds to point to NewBB1 instead of OrigBB.
  554. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  555. // This is slightly more strict than necessary; the minimum requirement
  556. // is that there be no more than one indirectbr branching to BB. And
  557. // all BlockAddress uses would need to be updated.
  558. assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
  559. "Cannot split an edge from an IndirectBrInst");
  560. Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
  561. }
  562. bool HasLoopExit = false;
  563. UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, MSSAU, PreserveLCSSA,
  564. HasLoopExit);
  565. // Update the PHI nodes in OrigBB with the values coming from NewBB1.
  566. UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
  567. // Move the remaining edges from OrigBB to point to NewBB2.
  568. SmallVector<BasicBlock*, 8> NewBB2Preds;
  569. for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
  570. i != e; ) {
  571. BasicBlock *Pred = *i++;
  572. if (Pred == NewBB1) continue;
  573. assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
  574. "Cannot split an edge from an IndirectBrInst");
  575. NewBB2Preds.push_back(Pred);
  576. e = pred_end(OrigBB);
  577. }
  578. BasicBlock *NewBB2 = nullptr;
  579. if (!NewBB2Preds.empty()) {
  580. // Create another basic block for the rest of OrigBB's predecessors.
  581. NewBB2 = BasicBlock::Create(OrigBB->getContext(),
  582. OrigBB->getName() + Suffix2,
  583. OrigBB->getParent(), OrigBB);
  584. NewBBs.push_back(NewBB2);
  585. // The new block unconditionally branches to the old block.
  586. BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
  587. BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
  588. // Move the remaining edges from OrigBB to point to NewBB2.
  589. for (BasicBlock *NewBB2Pred : NewBB2Preds)
  590. NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
  591. // Update DominatorTree, LoopInfo, and LCCSA analysis information.
  592. HasLoopExit = false;
  593. UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, MSSAU,
  594. PreserveLCSSA, HasLoopExit);
  595. // Update the PHI nodes in OrigBB with the values coming from NewBB2.
  596. UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
  597. }
  598. LandingPadInst *LPad = OrigBB->getLandingPadInst();
  599. Instruction *Clone1 = LPad->clone();
  600. Clone1->setName(Twine("lpad") + Suffix1);
  601. NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
  602. if (NewBB2) {
  603. Instruction *Clone2 = LPad->clone();
  604. Clone2->setName(Twine("lpad") + Suffix2);
  605. NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
  606. // Create a PHI node for the two cloned landingpad instructions only
  607. // if the original landingpad instruction has some uses.
  608. if (!LPad->use_empty()) {
  609. assert(!LPad->getType()->isTokenTy() &&
  610. "Split cannot be applied if LPad is token type. Otherwise an "
  611. "invalid PHINode of token type would be created.");
  612. PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
  613. PN->addIncoming(Clone1, NewBB1);
  614. PN->addIncoming(Clone2, NewBB2);
  615. LPad->replaceAllUsesWith(PN);
  616. }
  617. LPad->eraseFromParent();
  618. } else {
  619. // There is no second clone. Just replace the landing pad with the first
  620. // clone.
  621. LPad->replaceAllUsesWith(Clone1);
  622. LPad->eraseFromParent();
  623. }
  624. }
  625. ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
  626. BasicBlock *Pred,
  627. DomTreeUpdater *DTU) {
  628. Instruction *UncondBranch = Pred->getTerminator();
  629. // Clone the return and add it to the end of the predecessor.
  630. Instruction *NewRet = RI->clone();
  631. Pred->getInstList().push_back(NewRet);
  632. // If the return instruction returns a value, and if the value was a
  633. // PHI node in "BB", propagate the right value into the return.
  634. for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
  635. i != e; ++i) {
  636. Value *V = *i;
  637. Instruction *NewBC = nullptr;
  638. if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
  639. // Return value might be bitcasted. Clone and insert it before the
  640. // return instruction.
  641. V = BCI->getOperand(0);
  642. NewBC = BCI->clone();
  643. Pred->getInstList().insert(NewRet->getIterator(), NewBC);
  644. *i = NewBC;
  645. }
  646. if (PHINode *PN = dyn_cast<PHINode>(V)) {
  647. if (PN->getParent() == BB) {
  648. if (NewBC)
  649. NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
  650. else
  651. *i = PN->getIncomingValueForBlock(Pred);
  652. }
  653. }
  654. }
  655. // Update any PHI nodes in the returning block to realize that we no
  656. // longer branch to them.
  657. BB->removePredecessor(Pred);
  658. UncondBranch->eraseFromParent();
  659. if (DTU)
  660. DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
  661. return cast<ReturnInst>(NewRet);
  662. }
  663. Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
  664. Instruction *SplitBefore,
  665. bool Unreachable,
  666. MDNode *BranchWeights,
  667. DominatorTree *DT, LoopInfo *LI,
  668. BasicBlock *ThenBlock) {
  669. BasicBlock *Head = SplitBefore->getParent();
  670. BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
  671. Instruction *HeadOldTerm = Head->getTerminator();
  672. LLVMContext &C = Head->getContext();
  673. Instruction *CheckTerm;
  674. bool CreateThenBlock = (ThenBlock == nullptr);
  675. if (CreateThenBlock) {
  676. ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  677. if (Unreachable)
  678. CheckTerm = new UnreachableInst(C, ThenBlock);
  679. else
  680. CheckTerm = BranchInst::Create(Tail, ThenBlock);
  681. CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
  682. } else
  683. CheckTerm = ThenBlock->getTerminator();
  684. BranchInst *HeadNewTerm =
  685. BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
  686. HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
  687. ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
  688. if (DT) {
  689. if (DomTreeNode *OldNode = DT->getNode(Head)) {
  690. std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
  691. DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
  692. for (DomTreeNode *Child : Children)
  693. DT->changeImmediateDominator(Child, NewNode);
  694. // Head dominates ThenBlock.
  695. if (CreateThenBlock)
  696. DT->addNewBlock(ThenBlock, Head);
  697. else
  698. DT->changeImmediateDominator(ThenBlock, Head);
  699. }
  700. }
  701. if (LI) {
  702. if (Loop *L = LI->getLoopFor(Head)) {
  703. L->addBasicBlockToLoop(ThenBlock, *LI);
  704. L->addBasicBlockToLoop(Tail, *LI);
  705. }
  706. }
  707. return CheckTerm;
  708. }
  709. void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
  710. Instruction **ThenTerm,
  711. Instruction **ElseTerm,
  712. MDNode *BranchWeights) {
  713. BasicBlock *Head = SplitBefore->getParent();
  714. BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
  715. Instruction *HeadOldTerm = Head->getTerminator();
  716. LLVMContext &C = Head->getContext();
  717. BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  718. BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  719. *ThenTerm = BranchInst::Create(Tail, ThenBlock);
  720. (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
  721. *ElseTerm = BranchInst::Create(Tail, ElseBlock);
  722. (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
  723. BranchInst *HeadNewTerm =
  724. BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
  725. HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
  726. ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
  727. }
  728. Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
  729. BasicBlock *&IfFalse) {
  730. PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
  731. BasicBlock *Pred1 = nullptr;
  732. BasicBlock *Pred2 = nullptr;
  733. if (SomePHI) {
  734. if (SomePHI->getNumIncomingValues() != 2)
  735. return nullptr;
  736. Pred1 = SomePHI->getIncomingBlock(0);
  737. Pred2 = SomePHI->getIncomingBlock(1);
  738. } else {
  739. pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
  740. if (PI == PE) // No predecessor
  741. return nullptr;
  742. Pred1 = *PI++;
  743. if (PI == PE) // Only one predecessor
  744. return nullptr;
  745. Pred2 = *PI++;
  746. if (PI != PE) // More than two predecessors
  747. return nullptr;
  748. }
  749. // We can only handle branches. Other control flow will be lowered to
  750. // branches if possible anyway.
  751. BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
  752. BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
  753. if (!Pred1Br || !Pred2Br)
  754. return nullptr;
  755. // Eliminate code duplication by ensuring that Pred1Br is conditional if
  756. // either are.
  757. if (Pred2Br->isConditional()) {
  758. // If both branches are conditional, we don't have an "if statement". In
  759. // reality, we could transform this case, but since the condition will be
  760. // required anyway, we stand no chance of eliminating it, so the xform is
  761. // probably not profitable.
  762. if (Pred1Br->isConditional())
  763. return nullptr;
  764. std::swap(Pred1, Pred2);
  765. std::swap(Pred1Br, Pred2Br);
  766. }
  767. if (Pred1Br->isConditional()) {
  768. // The only thing we have to watch out for here is to make sure that Pred2
  769. // doesn't have incoming edges from other blocks. If it does, the condition
  770. // doesn't dominate BB.
  771. if (!Pred2->getSinglePredecessor())
  772. return nullptr;
  773. // If we found a conditional branch predecessor, make sure that it branches
  774. // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
  775. if (Pred1Br->getSuccessor(0) == BB &&
  776. Pred1Br->getSuccessor(1) == Pred2) {
  777. IfTrue = Pred1;
  778. IfFalse = Pred2;
  779. } else if (Pred1Br->getSuccessor(0) == Pred2 &&
  780. Pred1Br->getSuccessor(1) == BB) {
  781. IfTrue = Pred2;
  782. IfFalse = Pred1;
  783. } else {
  784. // We know that one arm of the conditional goes to BB, so the other must
  785. // go somewhere unrelated, and this must not be an "if statement".
  786. return nullptr;
  787. }
  788. return Pred1Br->getCondition();
  789. }
  790. // Ok, if we got here, both predecessors end with an unconditional branch to
  791. // BB. Don't panic! If both blocks only have a single (identical)
  792. // predecessor, and THAT is a conditional branch, then we're all ok!
  793. BasicBlock *CommonPred = Pred1->getSinglePredecessor();
  794. if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
  795. return nullptr;
  796. // Otherwise, if this is a conditional branch, then we can use it!
  797. BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
  798. if (!BI) return nullptr;
  799. assert(BI->isConditional() && "Two successors but not conditional?");
  800. if (BI->getSuccessor(0) == Pred1) {
  801. IfTrue = Pred1;
  802. IfFalse = Pred2;
  803. } else {
  804. IfTrue = Pred2;
  805. IfFalse = Pred1;
  806. }
  807. return BI->getCondition();
  808. }