BasicBlockUtils.cpp 31 KB

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